pw_user.c revision 253157
1251875Speter/*-
2251875Speter * Copyright (C) 1996
3251875Speter *	David L. Nugent.  All rights reserved.
4251875Speter *
5251875Speter * Redistribution and use in source and binary forms, with or without
6251875Speter * modification, are permitted provided that the following conditions
7251875Speter * are met:
8251875Speter * 1. Redistributions of source code must retain the above copyright
9251875Speter *    notice, this list of conditions and the following disclaimer.
10251875Speter * 2. Redistributions in binary form must reproduce the above copyright
11251875Speter *    notice, this list of conditions and the following disclaimer in the
12251875Speter *    documentation and/or other materials provided with the distribution.
13251875Speter *
14251875Speter * THIS SOFTWARE IS PROVIDED BY DAVID L. NUGENT AND CONTRIBUTORS ``AS IS'' AND
15251875Speter * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16251875Speter * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17251875Speter * ARE DISCLAIMED.  IN NO EVENT SHALL DAVID L. NUGENT OR CONTRIBUTORS BE LIABLE
18251875Speter * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19251875Speter * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20251875Speter * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21251875Speter * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22251875Speter * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23251875Speter * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24251875Speter * SUCH DAMAGE.
25251875Speter *
26251875Speter */
27251875Speter
28251875Speter#ifndef lint
29251875Speterstatic const char rcsid[] =
30251875Speter  "$FreeBSD: stable/9/usr.sbin/pw/pw_user.c 253157 2013-07-10 14:16:39Z des $";
31251875Speter#endif /* not lint */
32251875Speter
33251875Speter#include <ctype.h>
34251875Speter#include <err.h>
35251875Speter#include <fcntl.h>
36251875Speter#include <sys/param.h>
37251875Speter#include <dirent.h>
38251875Speter#include <paths.h>
39251875Speter#include <termios.h>
40251875Speter#include <sys/types.h>
41251875Speter#include <sys/time.h>
42251875Speter#include <sys/resource.h>
43251875Speter#include <unistd.h>
44251875Speter#include <login_cap.h>
45251875Speter#include "pw.h"
46251875Speter#include "bitmap.h"
47251875Speter
48251875Speter#define LOGNAMESIZE (MAXLOGNAME-1)
49251875Speter
50251875Speterstatic		char locked_str[] = "*LOCKED*";
51251875Speter
52251875Speterstatic int      print_user(struct passwd * pwd, int pretty, int v7);
53251875Speterstatic uid_t    pw_uidpolicy(struct userconf * cnf, struct cargs * args);
54251875Speterstatic uid_t    pw_gidpolicy(struct userconf * cnf, struct cargs * args, char *nam, gid_t prefer);
55251875Speterstatic time_t   pw_pwdpolicy(struct userconf * cnf, struct cargs * args);
56251875Speterstatic time_t   pw_exppolicy(struct userconf * cnf, struct cargs * args);
57251875Speterstatic char    *pw_homepolicy(struct userconf * cnf, struct cargs * args, char const * user);
58251875Speterstatic char    *pw_shellpolicy(struct userconf * cnf, struct cargs * args, char *newshell);
59251875Speterstatic char    *pw_password(struct userconf * cnf, struct cargs * args, char const * user);
60251875Speterstatic char    *shell_path(char const * path, char *shells[], char *sh);
61251875Speterstatic void     rmat(uid_t uid);
62251875Speterstatic void     rmopie(char const * name);
63251875Speter
64251875Speter/*-
65251875Speter * -C config      configuration file
66251875Speter * -q             quiet operation
67251875Speter * -n name        login name
68251875Speter * -u uid         user id
69251875Speter * -c comment     user name/comment
70251875Speter * -d directory   home directory
71251875Speter * -e date        account expiry date
72251875Speter * -p date        password expiry date
73251875Speter * -g grp         primary group
74251875Speter * -G grp1,grp2   additional groups
75251875Speter * -m [ -k dir ]  create and set up home
76251875Speter * -s shell       name of login shell
77251875Speter * -o             duplicate uid ok
78251875Speter * -L class       user class
79251875Speter * -l name        new login name
80251875Speter * -h fd          password filehandle
81251875Speter * -H fd          encrypted password filehandle
82251875Speter * -F             force print or add
83251875Speter *   Setting defaults:
84251875Speter * -D             set user defaults
85251875Speter * -b dir         default home root dir
86251875Speter * -e period      default expiry period
87251875Speter * -p period      default password change period
88251875Speter * -g group       default group
89251875Speter * -G             grp1,grp2.. default additional groups
90251875Speter * -L class       default login class
91251875Speter * -k dir         default home skeleton
92251875Speter * -s shell       default shell
93251875Speter * -w method      default password method
94251875Speter */
95251875Speter
96251875Speterint
97251875Speterpw_user(struct userconf * cnf, int mode, struct cargs * args)
98251875Speter{
99251875Speter	int	        rc, edited = 0;
100251875Speter	char           *p = NULL;
101251875Speter	char					 *passtmp;
102251875Speter	struct carg    *a_name;
103251875Speter	struct carg    *a_uid;
104251875Speter	struct carg    *arg;
105251875Speter	struct passwd  *pwd = NULL;
106251875Speter	struct group   *grp;
107251875Speter	struct stat     st;
108251875Speter	char            line[_PASSWORD_LEN+1];
109251875Speter	FILE	       *fp;
110251875Speter	char *dmode_c;
111251875Speter	void *set = NULL;
112251875Speter
113251875Speter	static struct passwd fakeuser =
114251875Speter	{
115251875Speter		NULL,
116251875Speter		"*",
117251875Speter		-1,
118251875Speter		-1,
119251875Speter		0,
120251875Speter		"",
121251875Speter		"User &",
122251875Speter		"/nonexistent",
123251875Speter		"/bin/sh",
124251875Speter		0
125251875Speter#if defined(__FreeBSD__)
126251875Speter		,0
127251875Speter#endif
128251875Speter	};
129251875Speter
130251875Speter
131251875Speter	/*
132251875Speter	 * With M_NEXT, we only need to return the
133251875Speter	 * next uid to stdout
134251875Speter	 */
135251875Speter	if (mode == M_NEXT)
136251875Speter	{
137251875Speter		uid_t next = pw_uidpolicy(cnf, args);
138251875Speter		if (getarg(args, 'q'))
139251875Speter			return next;
140251875Speter		printf("%ld:", (long)next);
141251875Speter		pw_group(cnf, mode, args);
142251875Speter		return EXIT_SUCCESS;
143251875Speter	}
144251875Speter
145251875Speter	/*
146251875Speter	 * We can do all of the common legwork here
147251875Speter	 */
148251875Speter
149251875Speter	if ((arg = getarg(args, 'b')) != NULL) {
150251875Speter		cnf->home = arg->val;
151251875Speter	}
152251875Speter
153251875Speter	if ((arg = getarg(args, 'M')) != NULL) {
154251875Speter		dmode_c = arg->val;
155251875Speter		if ((set = setmode(dmode_c)) == NULL)
156251875Speter			errx(EX_DATAERR, "invalid directory creation mode '%s'",
157251875Speter			    dmode_c);
158251875Speter		cnf->homemode = getmode(set, _DEF_DIRMODE);
159251875Speter		free(set);
160251875Speter	}
161251875Speter
162251875Speter	/*
163251875Speter	 * If we'll need to use it or we're updating it,
164251875Speter	 * then create the base home directory if necessary
165251875Speter	 */
166251875Speter	if (arg != NULL || getarg(args, 'm') != NULL) {
167251875Speter		int	l = strlen(cnf->home);
168251875Speter
169251875Speter		if (l > 1 && cnf->home[l-1] == '/')	/* Shave off any trailing path delimiter */
170251875Speter			cnf->home[--l] = '\0';
171251875Speter
172251875Speter		if (l < 2 || *cnf->home != '/')		/* Check for absolute path name */
173251875Speter			errx(EX_DATAERR, "invalid base directory for home '%s'", cnf->home);
174251875Speter
175251875Speter		if (stat(cnf->home, &st) == -1) {
176251875Speter			char	dbuf[MAXPATHLEN];
177251875Speter
178251875Speter			/*
179251875Speter			 * This is a kludge especially for Joerg :)
180251875Speter			 * If the home directory would be created in the root partition, then
181251875Speter			 * we really create it under /usr which is likely to have more space.
182251875Speter			 * But we create a symlink from cnf->home -> "/usr" -> cnf->home
183251875Speter			 */
184251875Speter			if (strchr(cnf->home+1, '/') == NULL) {
185251875Speter				strcpy(dbuf, "/usr");
186251875Speter				strncat(dbuf, cnf->home, MAXPATHLEN-5);
187251875Speter				if (mkdir(dbuf, _DEF_DIRMODE) != -1 || errno == EEXIST) {
188251875Speter					chown(dbuf, 0, 0);
189251875Speter					/*
190251875Speter					 * Skip first "/" and create symlink:
191251875Speter					 * /home -> usr/home
192251875Speter					 */
193251875Speter					symlink(dbuf+1, cnf->home);
194251875Speter				}
195251875Speter				/* If this falls, fall back to old method */
196251875Speter			}
197251875Speter			strlcpy(dbuf, cnf->home, sizeof(dbuf));
198251875Speter			p = dbuf;
199251875Speter			if (stat(dbuf, &st) == -1) {
200251875Speter				while ((p = strchr(++p, '/')) != NULL) {
201251875Speter					*p = '\0';
202251875Speter					if (stat(dbuf, &st) == -1) {
203251875Speter						if (mkdir(dbuf, _DEF_DIRMODE) == -1)
204251875Speter							goto direrr;
205251875Speter						chown(dbuf, 0, 0);
206251875Speter					} else if (!S_ISDIR(st.st_mode))
207251875Speter						errx(EX_OSFILE, "'%s' (root home parent) is not a directory", dbuf);
208251875Speter					*p = '/';
209251875Speter				}
210251875Speter			}
211251875Speter			if (stat(dbuf, &st) == -1) {
212251875Speter				if (mkdir(dbuf, _DEF_DIRMODE) == -1) {
213251875Speter				direrr:	err(EX_OSFILE, "mkdir '%s'", dbuf);
214251875Speter				}
215251875Speter				chown(dbuf, 0, 0);
216251875Speter			}
217251875Speter		} else if (!S_ISDIR(st.st_mode))
218251875Speter			errx(EX_OSFILE, "root home `%s' is not a directory", cnf->home);
219251875Speter	}
220251875Speter
221251875Speter	if ((arg = getarg(args, 'e')) != NULL)
222251875Speter		cnf->expire_days = atoi(arg->val);
223251875Speter
224251875Speter	if ((arg = getarg(args, 'y')) != NULL)
225251875Speter		cnf->nispasswd = arg->val;
226251875Speter
227251875Speter	if ((arg = getarg(args, 'p')) != NULL && arg->val)
228251875Speter		cnf->password_days = atoi(arg->val);
229251875Speter
230251875Speter	if ((arg = getarg(args, 'g')) != NULL) {
231251875Speter		if (!*(p = arg->val))	/* Handle empty group list specially */
232251875Speter			cnf->default_group = "";
233251875Speter		else {
234251875Speter			if ((grp = GETGRNAM(p)) == NULL) {
235251875Speter				if (!isdigit((unsigned char)*p) || (grp = GETGRGID((gid_t) atoi(p))) == NULL)
236251875Speter					errx(EX_NOUSER, "group `%s' does not exist", p);
237251875Speter			}
238251875Speter			cnf->default_group = newstr(grp->gr_name);
239251875Speter		}
240251875Speter	}
241251875Speter	if ((arg = getarg(args, 'L')) != NULL)
242251875Speter		cnf->default_class = pw_checkname((u_char *)arg->val, 0);
243251875Speter
244251875Speter	if ((arg = getarg(args, 'G')) != NULL && arg->val) {
245251875Speter		int i = 0;
246251875Speter
247251875Speter		for (p = strtok(arg->val, ", \t"); p != NULL; p = strtok(NULL, ", \t")) {
248251875Speter			if ((grp = GETGRNAM(p)) == NULL) {
249251875Speter				if (!isdigit((unsigned char)*p) || (grp = GETGRGID((gid_t) atoi(p))) == NULL)
250251875Speter					errx(EX_NOUSER, "group `%s' does not exist", p);
251251875Speter			}
252251875Speter			if (extendarray(&cnf->groups, &cnf->numgroups, i + 2) != -1)
253251875Speter				cnf->groups[i++] = newstr(grp->gr_name);
254251875Speter		}
255251875Speter		while (i < cnf->numgroups)
256251875Speter			cnf->groups[i++] = NULL;
257251875Speter	}
258251875Speter
259251875Speter	if ((arg = getarg(args, 'k')) != NULL) {
260251875Speter		if (stat(cnf->dotdir = arg->val, &st) == -1 || !S_ISDIR(st.st_mode))
261251875Speter			errx(EX_OSFILE, "skeleton `%s' is not a directory or does not exist", cnf->dotdir);
262251875Speter	}
263251875Speter
264251875Speter	if ((arg = getarg(args, 's')) != NULL)
265251875Speter		cnf->shell_default = arg->val;
266251875Speter
267251875Speter	if ((arg = getarg(args, 'w')) != NULL)
268251875Speter		cnf->default_password = boolean_val(arg->val, cnf->default_password);
269251875Speter	if (mode == M_ADD && getarg(args, 'D')) {
270251875Speter		if (getarg(args, 'n') != NULL)
271251875Speter			errx(EX_DATAERR, "can't combine `-D' with `-n name'");
272251875Speter		if ((arg = getarg(args, 'u')) != NULL && (p = strtok(arg->val, ", \t")) != NULL) {
273251875Speter			if ((cnf->min_uid = (uid_t) atoi(p)) == 0)
274251875Speter				cnf->min_uid = 1000;
275251875Speter			if ((p = strtok(NULL, " ,\t")) == NULL || (cnf->max_uid = (uid_t) atoi(p)) < cnf->min_uid)
276251875Speter				cnf->max_uid = 32000;
277251875Speter		}
278251875Speter		if ((arg = getarg(args, 'i')) != NULL && (p = strtok(arg->val, ", \t")) != NULL) {
279251875Speter			if ((cnf->min_gid = (gid_t) atoi(p)) == 0)
280251875Speter				cnf->min_gid = 1000;
281251875Speter			if ((p = strtok(NULL, " ,\t")) == NULL || (cnf->max_gid = (gid_t) atoi(p)) < cnf->min_gid)
282251875Speter				cnf->max_gid = 32000;
283251875Speter		}
284251875Speter
285251875Speter		arg = getarg(args, 'C');
286251875Speter		if (write_userconfig(arg ? arg->val : NULL))
287251875Speter			return EXIT_SUCCESS;
288251875Speter		warn("config update");
289251875Speter		return EX_IOERR;
290251875Speter	}
291251875Speter
292251875Speter	if (mode == M_PRINT && getarg(args, 'a')) {
293251875Speter		int             pretty = getarg(args, 'P') != NULL;
294251875Speter		int		v7 = getarg(args, '7') != NULL;
295251875Speter
296251875Speter		SETPWENT();
297251875Speter		while ((pwd = GETPWENT()) != NULL)
298251875Speter			print_user(pwd, pretty, v7);
299251875Speter		ENDPWENT();
300251875Speter		return EXIT_SUCCESS;
301251875Speter	}
302251875Speter
303251875Speter	if ((a_name = getarg(args, 'n')) != NULL)
304251875Speter		pwd = GETPWNAM(pw_checkname((u_char *)a_name->val, 0));
305251875Speter	a_uid = getarg(args, 'u');
306251875Speter
307251875Speter	if (a_uid == NULL) {
308251875Speter		if (a_name == NULL)
309251875Speter			errx(EX_DATAERR, "user name or id required");
310251875Speter
311251875Speter		/*
312251875Speter		 * Determine whether 'n' switch is name or uid - we don't
313251875Speter		 * really don't really care which we have, but we need to
314251875Speter		 * know.
315251875Speter		 */
316251875Speter		if (mode != M_ADD && pwd == NULL
317251875Speter		    && strspn(a_name->val, "0123456789") == strlen(a_name->val)
318251875Speter		    && *a_name->val) {
319251875Speter			(a_uid = a_name)->ch = 'u';
320251875Speter			a_name = NULL;
321251875Speter		}
322251875Speter	}
323251875Speter
324251875Speter	/*
325251875Speter	 * Update, delete & print require that the user exists
326251875Speter	 */
327251875Speter	if (mode == M_UPDATE || mode == M_DELETE ||
328251875Speter	    mode == M_PRINT  || mode == M_LOCK   || mode == M_UNLOCK) {
329251875Speter
330251875Speter		if (a_name == NULL && pwd == NULL)	/* Try harder */
331251875Speter			pwd = GETPWUID(atoi(a_uid->val));
332251875Speter
333251875Speter		if (pwd == NULL) {
334251875Speter			if (mode == M_PRINT && getarg(args, 'F')) {
335251875Speter				fakeuser.pw_name = a_name ? a_name->val : "nouser";
336251875Speter				fakeuser.pw_uid = a_uid ? (uid_t) atol(a_uid->val) : -1;
337251875Speter				return print_user(&fakeuser,
338251875Speter						  getarg(args, 'P') != NULL,
339251875Speter						  getarg(args, '7') != NULL);
340251875Speter			}
341251875Speter			if (a_name == NULL)
342251875Speter				errx(EX_NOUSER, "no such uid `%s'", a_uid->val);
343251875Speter			errx(EX_NOUSER, "no such user `%s'", a_name->val);
344251875Speter		}
345251875Speter
346251875Speter		if (a_name == NULL)	/* May be needed later */
347251875Speter			a_name = addarg(args, 'n', newstr(pwd->pw_name));
348251875Speter
349251875Speter		/*
350251875Speter		 * The M_LOCK and M_UNLOCK functions simply add or remove
351251875Speter		 * a "*LOCKED*" prefix from in front of the password to
352251875Speter		 * prevent it decoding correctly, and therefore prevents
353251875Speter		 * access. Of course, this only prevents access via
354251875Speter		 * password authentication (not ssh, kerberos or any
355251875Speter		 * other method that does not use the UNIX password) but
356251875Speter		 * that is a known limitation.
357251875Speter		 */
358251875Speter
359251875Speter		if (mode == M_LOCK) {
360251875Speter			if (strncmp(pwd->pw_passwd, locked_str, sizeof(locked_str)-1) == 0)
361251875Speter				errx(EX_DATAERR, "user '%s' is already locked", pwd->pw_name);
362251875Speter			passtmp = malloc(strlen(pwd->pw_passwd) + sizeof(locked_str));
363251875Speter			if (passtmp == NULL)	/* disaster */
364251875Speter				errx(EX_UNAVAILABLE, "out of memory");
365251875Speter			strcpy(passtmp, locked_str);
366251875Speter			strcat(passtmp, pwd->pw_passwd);
367251875Speter			pwd->pw_passwd = passtmp;
368251875Speter			edited = 1;
369251875Speter		} else if (mode == M_UNLOCK) {
370251875Speter			if (strncmp(pwd->pw_passwd, locked_str, sizeof(locked_str)-1) != 0)
371251875Speter				errx(EX_DATAERR, "user '%s' is not locked", pwd->pw_name);
372251875Speter			pwd->pw_passwd += sizeof(locked_str)-1;
373251875Speter			edited = 1;
374251875Speter		} else if (mode == M_DELETE) {
375251875Speter			/*
376251875Speter			 * Handle deletions now
377251875Speter			 */
378251875Speter			char            file[MAXPATHLEN];
379251875Speter			char            home[MAXPATHLEN];
380251875Speter			uid_t           uid = pwd->pw_uid;
381251875Speter
382251875Speter			if (strcmp(pwd->pw_name, "root") == 0)
383251875Speter				errx(EX_DATAERR, "cannot remove user 'root'");
384251875Speter
385251875Speter			if (!PWALTDIR()) {
386251875Speter				/*
387251875Speter				 * Remove opie record from /etc/opiekeys
388251875Speter		        	 */
389251875Speter
390251875Speter				rmopie(pwd->pw_name);
391251875Speter
392251875Speter				/*
393251875Speter				 * Remove crontabs
394251875Speter				 */
395251875Speter				sprintf(file, "/var/cron/tabs/%s", pwd->pw_name);
396251875Speter				if (access(file, F_OK) == 0) {
397251875Speter					sprintf(file, "crontab -u %s -r", pwd->pw_name);
398251875Speter					system(file);
399251875Speter				}
400251875Speter			}
401251875Speter			/*
402251875Speter			 * Save these for later, since contents of pwd may be
403251875Speter			 * invalidated by deletion
404251875Speter			 */
405251875Speter			sprintf(file, "%s/%s", _PATH_MAILDIR, pwd->pw_name);
406251875Speter			strlcpy(home, pwd->pw_dir, sizeof(home));
407251875Speter
408251875Speter			rc = delpwent(pwd);
409251875Speter			if (rc == -1)
410251875Speter				err(EX_IOERR, "user '%s' does not exist", pwd->pw_name);
411251875Speter			else if (rc != 0) {
412251875Speter				warn("passwd update");
413251875Speter				return EX_IOERR;
414251875Speter			}
415251875Speter
416251875Speter			if (cnf->nispasswd && *cnf->nispasswd=='/') {
417251875Speter				rc = delnispwent(cnf->nispasswd, a_name->val);
418251875Speter				if (rc == -1)
419251875Speter					warnx("WARNING: user '%s' does not exist in NIS passwd", pwd->pw_name);
420251875Speter				else if (rc != 0)
421251875Speter					warn("WARNING: NIS passwd update");
422251875Speter				/* non-fatal */
423251875Speter			}
424251875Speter
425251875Speter			editgroups(a_name->val, NULL);
426251875Speter
427251875Speter			pw_log(cnf, mode, W_USER, "%s(%ld) account removed", a_name->val, (long) uid);
428251875Speter
429251875Speter			if (!PWALTDIR()) {
430251875Speter				/*
431251875Speter				 * Remove mail file
432251875Speter				 */
433251875Speter				remove(file);
434251875Speter
435251875Speter				/*
436251875Speter				 * Remove at jobs
437251875Speter				 */
438251875Speter				if (getpwuid(uid) == NULL)
439251875Speter					rmat(uid);
440251875Speter
441251875Speter				/*
442251875Speter				 * Remove home directory and contents
443251875Speter				 */
444				if (getarg(args, 'r') != NULL && *home == '/' && getpwuid(uid) == NULL) {
445					if (stat(home, &st) != -1) {
446						rm_r(home, uid);
447						pw_log(cnf, mode, W_USER, "%s(%ld) home '%s' %sremoved",
448						       a_name->val, (long) uid, home,
449						       stat(home, &st) == -1 ? "" : "not completely ");
450					}
451				}
452			}
453			return EXIT_SUCCESS;
454		} else if (mode == M_PRINT)
455			return print_user(pwd,
456					  getarg(args, 'P') != NULL,
457					  getarg(args, '7') != NULL);
458
459		/*
460		 * The rest is edit code
461		 */
462		if ((arg = getarg(args, 'l')) != NULL) {
463			if (strcmp(pwd->pw_name, "root") == 0)
464				errx(EX_DATAERR, "can't rename `root' account");
465			pwd->pw_name = pw_checkname((u_char *)arg->val, 0);
466			edited = 1;
467		}
468
469		if ((arg = getarg(args, 'u')) != NULL && isdigit((unsigned char)*arg->val)) {
470			pwd->pw_uid = (uid_t) atol(arg->val);
471			edited = 1;
472			if (pwd->pw_uid != 0 && strcmp(pwd->pw_name, "root") == 0)
473				errx(EX_DATAERR, "can't change uid of `root' account");
474			if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
475				warnx("WARNING: account `%s' will have a uid of 0 (superuser access!)", pwd->pw_name);
476		}
477
478		if ((arg = getarg(args, 'g')) != NULL && pwd->pw_uid != 0) {	/* Already checked this */
479			gid_t newgid = (gid_t) GETGRNAM(cnf->default_group)->gr_gid;
480			if (newgid != pwd->pw_gid) {
481				edited = 1;
482				pwd->pw_gid = newgid;
483			}
484		}
485
486		if ((arg = getarg(args, 'p')) != NULL) {
487			if (*arg->val == '\0' || strcmp(arg->val, "0") == 0) {
488				if (pwd->pw_change != 0) {
489					pwd->pw_change = 0;
490					edited = 1;
491				}
492			}
493			else {
494				time_t          now = time(NULL);
495				time_t          expire = parse_date(now, arg->val);
496
497				if (pwd->pw_change != expire) {
498					pwd->pw_change = expire;
499					edited = 1;
500				}
501			}
502		}
503
504		if ((arg = getarg(args, 'e')) != NULL) {
505			if (*arg->val == '\0' || strcmp(arg->val, "0") == 0) {
506				if (pwd->pw_expire != 0) {
507					pwd->pw_expire = 0;
508					edited = 1;
509				}
510			}
511			else {
512				time_t          now = time(NULL);
513				time_t          expire = parse_date(now, arg->val);
514
515				if (pwd->pw_expire != expire) {
516					pwd->pw_expire = expire;
517					edited = 1;
518				}
519			}
520		}
521
522		if ((arg = getarg(args, 's')) != NULL) {
523			char *shell = shell_path(cnf->shelldir, cnf->shells, arg->val);
524			if (shell == NULL)
525				shell = "";
526			if (strcmp(shell, pwd->pw_shell) != 0) {
527				pwd->pw_shell = shell;
528				edited = 1;
529			}
530		}
531
532		if (getarg(args, 'L')) {
533			if (cnf->default_class == NULL)
534				cnf->default_class = "";
535			if (strcmp(pwd->pw_class, cnf->default_class) != 0) {
536				pwd->pw_class = cnf->default_class;
537				edited = 1;
538			}
539		}
540
541		if ((arg  = getarg(args, 'd')) != NULL) {
542			if (strcmp(pwd->pw_dir, arg->val))
543				edited = 1;
544			if (stat(pwd->pw_dir = arg->val, &st) == -1) {
545				if (getarg(args, 'm') == NULL && strcmp(pwd->pw_dir, "/nonexistent") != 0)
546				  warnx("WARNING: home `%s' does not exist", pwd->pw_dir);
547			} else if (!S_ISDIR(st.st_mode))
548				warnx("WARNING: home `%s' is not a directory", pwd->pw_dir);
549		}
550
551		if ((arg = getarg(args, 'w')) != NULL &&
552		    getarg(args, 'h') == NULL && getarg(args, 'H') == NULL) {
553			login_cap_t *lc;
554
555			lc = login_getpwclass(pwd);
556			if (lc == NULL ||
557			    login_setcryptfmt(lc, "sha512", NULL) == NULL)
558				warn("setting crypt(3) format");
559			login_close(lc);
560			pwd->pw_passwd = pw_password(cnf, args, pwd->pw_name);
561			edited = 1;
562		}
563
564	} else {
565		login_cap_t *lc;
566
567		/*
568		 * Add code
569		 */
570
571		if (a_name == NULL)	/* Required */
572			errx(EX_DATAERR, "login name required");
573		else if ((pwd = GETPWNAM(a_name->val)) != NULL)	/* Exists */
574			errx(EX_DATAERR, "login name `%s' already exists", a_name->val);
575
576		/*
577		 * Now, set up defaults for a new user
578		 */
579		pwd = &fakeuser;
580		pwd->pw_name = a_name->val;
581		pwd->pw_class = cnf->default_class ? cnf->default_class : "";
582		pwd->pw_uid = pw_uidpolicy(cnf, args);
583		pwd->pw_gid = pw_gidpolicy(cnf, args, pwd->pw_name, (gid_t) pwd->pw_uid);
584		pwd->pw_change = pw_pwdpolicy(cnf, args);
585		pwd->pw_expire = pw_exppolicy(cnf, args);
586		pwd->pw_dir = pw_homepolicy(cnf, args, pwd->pw_name);
587		pwd->pw_shell = pw_shellpolicy(cnf, args, NULL);
588		lc = login_getpwclass(pwd);
589		if (lc == NULL || login_setcryptfmt(lc, "md5", NULL) == NULL)
590			warn("setting crypt(3) format");
591		login_close(lc);
592		pwd->pw_passwd = pw_password(cnf, args, pwd->pw_name);
593		edited = 1;
594
595		if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
596			warnx("WARNING: new account `%s' has a uid of 0 (superuser access!)", pwd->pw_name);
597	}
598
599	/*
600	 * Shared add/edit code
601	 */
602	if ((arg = getarg(args, 'c')) != NULL) {
603		char	*gecos = pw_checkname((u_char *)arg->val, 1);
604		if (strcmp(pwd->pw_gecos, gecos) != 0) {
605			pwd->pw_gecos = gecos;
606			edited = 1;
607		}
608	}
609
610	if ((arg = getarg(args, 'h')) != NULL ||
611	    (arg = getarg(args, 'H')) != NULL) {
612		if (strcmp(arg->val, "-") == 0) {
613			if (!pwd->pw_passwd || *pwd->pw_passwd != '*') {
614				pwd->pw_passwd = "*";	/* No access */
615				edited = 1;
616			}
617		} else {
618			int             fd = atoi(arg->val);
619			int		precrypt = (arg->ch == 'H');
620			int             b;
621			int             istty = isatty(fd);
622			struct termios  t;
623			login_cap_t	*lc;
624
625			if (istty) {
626				if (tcgetattr(fd, &t) == -1)
627					istty = 0;
628				else {
629					struct termios  n = t;
630
631					/* Disable echo */
632					n.c_lflag &= ~(ECHO);
633					tcsetattr(fd, TCSANOW, &n);
634					printf("%s%spassword for user %s:",
635					     (mode == M_UPDATE) ? "new " : "",
636					     precrypt ? "encrypted " : "",
637					     pwd->pw_name);
638					fflush(stdout);
639				}
640			}
641			b = read(fd, line, sizeof(line) - 1);
642			if (istty) {	/* Restore state */
643				tcsetattr(fd, TCSANOW, &t);
644				fputc('\n', stdout);
645				fflush(stdout);
646			}
647			if (b < 0) {
648				warn("-%c file descriptor", precrypt ? 'H' :
649				    'h');
650				return EX_IOERR;
651			}
652			line[b] = '\0';
653			if ((p = strpbrk(line, "\r\n")) != NULL)
654				*p = '\0';
655			if (!*line)
656				errx(EX_DATAERR, "empty password read on file descriptor %d", fd);
657			if (precrypt) {
658				if (strchr(line, ':') != NULL)
659					return EX_DATAERR;
660				pwd->pw_passwd = line;
661			} else {
662				lc = login_getpwclass(pwd);
663				if (lc == NULL ||
664				    login_setcryptfmt(lc, "md5", NULL) == NULL)
665					warn("setting crypt(3) format");
666				login_close(lc);
667				pwd->pw_passwd = pw_pwcrypt(line);
668			}
669			edited = 1;
670		}
671	}
672
673	/*
674	 * Special case: -N only displays & exits
675	 */
676	if (getarg(args, 'N') != NULL)
677		return print_user(pwd,
678				  getarg(args, 'P') != NULL,
679				  getarg(args, '7') != NULL);
680
681	if (mode == M_ADD) {
682		edited = 1;	/* Always */
683		rc = addpwent(pwd);
684		if (rc == -1) {
685			warnx("user '%s' already exists", pwd->pw_name);
686			return EX_IOERR;
687		} else if (rc != 0) {
688			warn("passwd file update");
689			return EX_IOERR;
690		}
691		if (cnf->nispasswd && *cnf->nispasswd=='/') {
692			rc = addnispwent(cnf->nispasswd, pwd);
693			if (rc == -1)
694				warnx("User '%s' already exists in NIS passwd", pwd->pw_name);
695			else
696				warn("NIS passwd update");
697			/* NOTE: we treat NIS-only update errors as non-fatal */
698		}
699	} else if (mode == M_UPDATE || mode == M_LOCK || mode == M_UNLOCK) {
700		if (edited) {	/* Only updated this if required */
701			rc = chgpwent(a_name->val, pwd);
702			if (rc == -1) {
703				warnx("user '%s' does not exist (NIS?)", pwd->pw_name);
704				return EX_IOERR;
705			} else if (rc != 0) {
706				warn("passwd file update");
707				return EX_IOERR;
708			}
709			if ( cnf->nispasswd && *cnf->nispasswd=='/') {
710				rc = chgnispwent(cnf->nispasswd, a_name->val, pwd);
711				if (rc == -1)
712					warn("User '%s' not found in NIS passwd", pwd->pw_name);
713				else
714					warn("NIS passwd update");
715				/* NOTE: NIS-only update errors are not fatal */
716			}
717		}
718	}
719
720	/*
721	 * Ok, user is created or changed - now edit group file
722	 */
723
724	if (mode == M_ADD || getarg(args, 'G') != NULL)
725		editgroups(pwd->pw_name, cnf->groups);
726
727	/* go get a current version of pwd */
728	pwd = GETPWNAM(a_name->val);
729	if (pwd == NULL) {
730		/* This will fail when we rename, so special case that */
731		if (mode == M_UPDATE && (arg = getarg(args, 'l')) != NULL) {
732			a_name->val = arg->val;		/* update new name */
733			pwd = GETPWNAM(a_name->val);	/* refetch renamed rec */
734		}
735	}
736	if (pwd == NULL)	/* can't go on without this */
737		errx(EX_NOUSER, "user '%s' disappeared during update", a_name->val);
738
739	grp = GETGRGID(pwd->pw_gid);
740	pw_log(cnf, mode, W_USER, "%s(%ld):%s(%ld):%s:%s:%s",
741	       pwd->pw_name, (long) pwd->pw_uid,
742	    grp ? grp->gr_name : "unknown", (long) (grp ? grp->gr_gid : -1),
743	       pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell);
744
745	/*
746	 * If adding, let's touch and chown the user's mail file. This is not
747	 * strictly necessary under BSD with a 0755 maildir but it also
748	 * doesn't hurt anything to create the empty mailfile
749	 */
750	if (mode == M_ADD) {
751		if (!PWALTDIR()) {
752			sprintf(line, "%s/%s", _PATH_MAILDIR, pwd->pw_name);
753			close(open(line, O_RDWR | O_CREAT, 0600));	/* Preserve contents &
754									 * mtime */
755			chown(line, pwd->pw_uid, pwd->pw_gid);
756		}
757	}
758
759	/*
760	 * Let's create and populate the user's home directory. Note
761	 * that this also `works' for editing users if -m is used, but
762	 * existing files will *not* be overwritten.
763	 */
764	if (!PWALTDIR() && getarg(args, 'm') != NULL && pwd->pw_dir && *pwd->pw_dir == '/' && pwd->pw_dir[1]) {
765		copymkdir(pwd->pw_dir, cnf->dotdir, cnf->homemode, pwd->pw_uid, pwd->pw_gid);
766		pw_log(cnf, mode, W_USER, "%s(%ld) home %s made",
767		       pwd->pw_name, (long) pwd->pw_uid, pwd->pw_dir);
768	}
769
770
771	/*
772	 * Finally, send mail to the new user as well, if we are asked to
773	 */
774	if (mode == M_ADD && !PWALTDIR() && cnf->newmail && *cnf->newmail && (fp = fopen(cnf->newmail, "r")) != NULL) {
775		FILE           *pfp = popen(_PATH_SENDMAIL " -t", "w");
776
777		if (pfp == NULL)
778			warn("sendmail");
779		else {
780			fprintf(pfp, "From: root\n" "To: %s\n" "Subject: Welcome!\n\n", pwd->pw_name);
781			while (fgets(line, sizeof(line), fp) != NULL) {
782				/* Do substitutions? */
783				fputs(line, pfp);
784			}
785			pclose(pfp);
786			pw_log(cnf, mode, W_USER, "%s(%ld) new user mail sent",
787			    pwd->pw_name, (long) pwd->pw_uid);
788		}
789		fclose(fp);
790	}
791
792	return EXIT_SUCCESS;
793}
794
795
796static          uid_t
797pw_uidpolicy(struct userconf * cnf, struct cargs * args)
798{
799	struct passwd  *pwd;
800	uid_t           uid = (uid_t) - 1;
801	struct carg    *a_uid = getarg(args, 'u');
802
803	/*
804	 * Check the given uid, if any
805	 */
806	if (a_uid != NULL) {
807		uid = (uid_t) atol(a_uid->val);
808
809		if ((pwd = GETPWUID(uid)) != NULL && getarg(args, 'o') == NULL)
810			errx(EX_DATAERR, "uid `%ld' has already been allocated", (long) pwd->pw_uid);
811	} else {
812		struct bitmap   bm;
813
814		/*
815		 * We need to allocate the next available uid under one of
816		 * two policies a) Grab the first unused uid b) Grab the
817		 * highest possible unused uid
818		 */
819		if (cnf->min_uid >= cnf->max_uid) {	/* Sanity
820							 * claus^H^H^H^Hheck */
821			cnf->min_uid = 1000;
822			cnf->max_uid = 32000;
823		}
824		bm = bm_alloc(cnf->max_uid - cnf->min_uid + 1);
825
826		/*
827		 * Now, let's fill the bitmap from the password file
828		 */
829		SETPWENT();
830		while ((pwd = GETPWENT()) != NULL)
831			if (pwd->pw_uid >= (uid_t) cnf->min_uid && pwd->pw_uid <= (uid_t) cnf->max_uid)
832				bm_setbit(&bm, pwd->pw_uid - cnf->min_uid);
833		ENDPWENT();
834
835		/*
836		 * Then apply the policy, with fallback to reuse if necessary
837		 */
838		if (cnf->reuse_uids || (uid = (uid_t) (bm_lastset(&bm) + cnf->min_uid + 1)) > cnf->max_uid)
839			uid = (uid_t) (bm_firstunset(&bm) + cnf->min_uid);
840
841		/*
842		 * Another sanity check
843		 */
844		if (uid < cnf->min_uid || uid > cnf->max_uid)
845			errx(EX_SOFTWARE, "unable to allocate a new uid - range fully used");
846		bm_dealloc(&bm);
847	}
848	return uid;
849}
850
851
852static          uid_t
853pw_gidpolicy(struct userconf * cnf, struct cargs * args, char *nam, gid_t prefer)
854{
855	struct group   *grp;
856	gid_t           gid = (uid_t) - 1;
857	struct carg    *a_gid = getarg(args, 'g');
858
859	/*
860	 * If no arg given, see if default can help out
861	 */
862	if (a_gid == NULL && cnf->default_group && *cnf->default_group)
863		a_gid = addarg(args, 'g', cnf->default_group);
864
865	/*
866	 * Check the given gid, if any
867	 */
868	SETGRENT();
869	if (a_gid != NULL) {
870		if ((grp = GETGRNAM(a_gid->val)) == NULL) {
871			gid = (gid_t) atol(a_gid->val);
872			if ((gid == 0 && !isdigit((unsigned char)*a_gid->val)) || (grp = GETGRGID(gid)) == NULL)
873				errx(EX_NOUSER, "group `%s' is not defined", a_gid->val);
874		}
875		gid = grp->gr_gid;
876	} else if ((grp = GETGRNAM(nam)) != NULL && grp->gr_mem[0] == NULL) {
877		gid = grp->gr_gid;  /* Already created? Use it anyway... */
878	} else {
879		struct cargs    grpargs;
880		char            tmp[32];
881
882		LIST_INIT(&grpargs);
883		addarg(&grpargs, 'n', nam);
884
885		/*
886		 * We need to auto-create a group with the user's name. We
887		 * can send all the appropriate output to our sister routine
888		 * bit first see if we can create a group with gid==uid so we
889		 * can keep the user and group ids in sync. We purposely do
890		 * NOT check the gid range if we can force the sync. If the
891		 * user's name dups an existing group, then the group add
892		 * function will happily handle that case for us and exit.
893		 */
894		if (GETGRGID(prefer) == NULL) {
895			sprintf(tmp, "%lu", (unsigned long) prefer);
896			addarg(&grpargs, 'g', tmp);
897		}
898		if (getarg(args, 'N'))
899		{
900			addarg(&grpargs, 'N', NULL);
901			addarg(&grpargs, 'q', NULL);
902			gid = pw_group(cnf, M_NEXT, &grpargs);
903		}
904		else
905		{
906			pw_group(cnf, M_ADD, &grpargs);
907			if ((grp = GETGRNAM(nam)) != NULL)
908				gid = grp->gr_gid;
909		}
910		a_gid = LIST_FIRST(&grpargs);
911		while (a_gid != NULL) {
912			struct carg    *t = LIST_NEXT(a_gid, list);
913			LIST_REMOVE(a_gid, list);
914			a_gid = t;
915		}
916	}
917	ENDGRENT();
918	return gid;
919}
920
921
922static          time_t
923pw_pwdpolicy(struct userconf * cnf, struct cargs * args)
924{
925	time_t          result = 0;
926	time_t          now = time(NULL);
927	struct carg    *arg = getarg(args, 'p');
928
929	if (arg != NULL) {
930		if ((result = parse_date(now, arg->val)) == now)
931			errx(EX_DATAERR, "invalid date/time `%s'", arg->val);
932	} else if (cnf->password_days > 0)
933		result = now + ((long) cnf->password_days * 86400L);
934	return result;
935}
936
937
938static          time_t
939pw_exppolicy(struct userconf * cnf, struct cargs * args)
940{
941	time_t          result = 0;
942	time_t          now = time(NULL);
943	struct carg    *arg = getarg(args, 'e');
944
945	if (arg != NULL) {
946		if ((result = parse_date(now, arg->val)) == now)
947			errx(EX_DATAERR, "invalid date/time `%s'", arg->val);
948	} else if (cnf->expire_days > 0)
949		result = now + ((long) cnf->expire_days * 86400L);
950	return result;
951}
952
953
954static char    *
955pw_homepolicy(struct userconf * cnf, struct cargs * args, char const * user)
956{
957	struct carg    *arg = getarg(args, 'd');
958
959	if (arg)
960		return arg->val;
961	else {
962		static char     home[128];
963
964		if (cnf->home == NULL || *cnf->home == '\0')
965			errx(EX_CONFIG, "no base home directory set");
966		sprintf(home, "%s/%s", cnf->home, user);
967		return home;
968	}
969}
970
971static char    *
972shell_path(char const * path, char *shells[], char *sh)
973{
974	if (sh != NULL && (*sh == '/' || *sh == '\0'))
975		return sh;	/* specified full path or forced none */
976	else {
977		char           *p;
978		char            paths[_UC_MAXLINE];
979
980		/*
981		 * We need to search paths
982		 */
983		strlcpy(paths, path, sizeof(paths));
984		for (p = strtok(paths, ": \t\r\n"); p != NULL; p = strtok(NULL, ": \t\r\n")) {
985			int             i;
986			static char     shellpath[256];
987
988			if (sh != NULL) {
989				sprintf(shellpath, "%s/%s", p, sh);
990				if (access(shellpath, X_OK) == 0)
991					return shellpath;
992			} else
993				for (i = 0; i < _UC_MAXSHELLS && shells[i] != NULL; i++) {
994					sprintf(shellpath, "%s/%s", p, shells[i]);
995					if (access(shellpath, X_OK) == 0)
996						return shellpath;
997				}
998		}
999		if (sh == NULL)
1000			errx(EX_OSFILE, "can't find shell `%s' in shell paths", sh);
1001		errx(EX_CONFIG, "no default shell available or defined");
1002		return NULL;
1003	}
1004}
1005
1006
1007static char    *
1008pw_shellpolicy(struct userconf * cnf, struct cargs * args, char *newshell)
1009{
1010	char           *sh = newshell;
1011	struct carg    *arg = getarg(args, 's');
1012
1013	if (newshell == NULL && arg != NULL)
1014		sh = arg->val;
1015	return shell_path(cnf->shelldir, cnf->shells, sh ? sh : cnf->shell_default);
1016}
1017
1018#define	SALTSIZE	32
1019
1020static char const chars[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ./";
1021
1022char           *
1023pw_pwcrypt(char *password)
1024{
1025	int             i;
1026	char            salt[SALTSIZE + 1];
1027
1028	static char     buf[256];
1029
1030	/*
1031	 * Calculate a salt value
1032	 */
1033	for (i = 0; i < SALTSIZE; i++)
1034		salt[i] = chars[arc4random_uniform(sizeof(chars) - 1)];
1035	salt[SALTSIZE] = '\0';
1036
1037	return strcpy(buf, crypt(password, salt));
1038}
1039
1040
1041static char    *
1042pw_password(struct userconf * cnf, struct cargs * args, char const * user)
1043{
1044	int             i, l;
1045	char            pwbuf[32];
1046
1047	switch (cnf->default_password) {
1048	case -1:		/* Random password */
1049		l = (arc4random() % 8 + 8);	/* 8 - 16 chars */
1050		for (i = 0; i < l; i++)
1051			pwbuf[i] = chars[arc4random_uniform(sizeof(chars)-1)];
1052		pwbuf[i] = '\0';
1053
1054		/*
1055		 * We give this information back to the user
1056		 */
1057		if (getarg(args, 'h') == NULL && getarg(args, 'H') == NULL &&
1058		    getarg(args, 'N') == NULL) {
1059			if (isatty(STDOUT_FILENO))
1060				printf("Password for '%s' is: ", user);
1061			printf("%s\n", pwbuf);
1062			fflush(stdout);
1063		}
1064		break;
1065
1066	case -2:		/* No password at all! */
1067		return "";
1068
1069	case 0:		/* No login - default */
1070	default:
1071		return "*";
1072
1073	case 1:		/* user's name */
1074		strlcpy(pwbuf, user, sizeof(pwbuf));
1075		break;
1076	}
1077	return pw_pwcrypt(pwbuf);
1078}
1079
1080
1081static int
1082print_user(struct passwd * pwd, int pretty, int v7)
1083{
1084	if (!pretty) {
1085		char            buf[_UC_MAXLINE];
1086
1087		fmtpwentry(buf, pwd, v7 ? PWF_PASSWD : PWF_STANDARD);
1088		fputs(buf, stdout);
1089	} else {
1090		int		j;
1091		char           *p;
1092		struct group   *grp = GETGRGID(pwd->pw_gid);
1093		char            uname[60] = "User &", office[60] = "[None]",
1094		                wphone[60] = "[None]", hphone[60] = "[None]";
1095		char		acexpire[32] = "[None]", pwexpire[32] = "[None]";
1096		struct tm *    tptr;
1097
1098		if ((p = strtok(pwd->pw_gecos, ",")) != NULL) {
1099			strlcpy(uname, p, sizeof(uname));
1100			if ((p = strtok(NULL, ",")) != NULL) {
1101				strlcpy(office, p, sizeof(office));
1102				if ((p = strtok(NULL, ",")) != NULL) {
1103					strlcpy(wphone, p, sizeof(wphone));
1104					if ((p = strtok(NULL, "")) != NULL) {
1105						strlcpy(hphone, p,
1106						    sizeof(hphone));
1107					}
1108				}
1109			}
1110		}
1111		/*
1112		 * Handle '&' in gecos field
1113		 */
1114		if ((p = strchr(uname, '&')) != NULL) {
1115			int             l = strlen(pwd->pw_name);
1116			int             m = strlen(p);
1117
1118			memmove(p + l, p + 1, m);
1119			memmove(p, pwd->pw_name, l);
1120			*p = (char) toupper((unsigned char)*p);
1121		}
1122		if (pwd->pw_expire > (time_t)0 && (tptr = localtime(&pwd->pw_expire)) != NULL)
1123			strftime(acexpire, sizeof acexpire, "%c", tptr);
1124		if (pwd->pw_change > (time_t)0 && (tptr = localtime(&pwd->pw_change)) != NULL)
1125			strftime(pwexpire, sizeof pwexpire, "%c", tptr);
1126		printf("Login Name: %-15s   #%-12ld Group: %-15s   #%ld\n"
1127		       " Full Name: %s\n"
1128		       "      Home: %-26.26s      Class: %s\n"
1129		       "     Shell: %-26.26s     Office: %s\n"
1130		       "Work Phone: %-26.26s Home Phone: %s\n"
1131		       "Acc Expire: %-26.26s Pwd Expire: %s\n",
1132		       pwd->pw_name, (long) pwd->pw_uid,
1133		       grp ? grp->gr_name : "(invalid)", (long) pwd->pw_gid,
1134		       uname, pwd->pw_dir, pwd->pw_class,
1135		       pwd->pw_shell, office, wphone, hphone,
1136		       acexpire, pwexpire);
1137	        SETGRENT();
1138		j = 0;
1139		while ((grp=GETGRENT()) != NULL)
1140		{
1141			int     i = 0;
1142			while (grp->gr_mem[i] != NULL)
1143			{
1144				if (strcmp(grp->gr_mem[i], pwd->pw_name)==0)
1145				{
1146					printf(j++ == 0 ? "    Groups: %s" : ",%s", grp->gr_name);
1147					break;
1148				}
1149				++i;
1150			}
1151		}
1152		ENDGRENT();
1153		printf("%s", j ? "\n" : "");
1154	}
1155	return EXIT_SUCCESS;
1156}
1157
1158char    *
1159pw_checkname(u_char *name, int gecos)
1160{
1161	char showch[8];
1162	u_char const *badchars, *ch, *showtype;
1163	int reject;
1164
1165	ch = name;
1166	reject = 0;
1167	if (gecos) {
1168		/* See if the name is valid as a gecos (comment) field. */
1169		badchars = ":!@";
1170		showtype = "gecos field";
1171	} else {
1172		/* See if the name is valid as a userid or group. */
1173		badchars = " ,\t:+&#%$^()!@~*?<>=|\\/\"";
1174		showtype = "userid/group name";
1175		/* Userids and groups can not have a leading '-'. */
1176		if (*ch == '-')
1177			reject = 1;
1178	}
1179	if (!reject) {
1180		while (*ch) {
1181			if (strchr(badchars, *ch) != NULL || *ch < ' ' ||
1182			    *ch == 127) {
1183				reject = 1;
1184				break;
1185			}
1186			/* 8-bit characters are only allowed in GECOS fields */
1187			if (!gecos && (*ch & 0x80)) {
1188				reject = 1;
1189				break;
1190			}
1191			ch++;
1192		}
1193	}
1194	/*
1195	 * A `$' is allowed as the final character for userids and groups,
1196	 * mainly for the benefit of samba.
1197	 */
1198	if (reject && !gecos) {
1199		if (*ch == '$' && *(ch + 1) == '\0') {
1200			reject = 0;
1201			ch++;
1202		}
1203	}
1204	if (reject) {
1205		snprintf(showch, sizeof(showch), (*ch >= ' ' && *ch < 127)
1206		    ? "`%c'" : "0x%02x", *ch);
1207		errx(EX_DATAERR, "invalid character %s at position %td in %s",
1208		    showch, (ch - name), showtype);
1209	}
1210	if (!gecos && (ch - name) > LOGNAMESIZE)
1211		errx(EX_DATAERR, "name too long `%s' (max is %d)", name,
1212		    LOGNAMESIZE);
1213	return (char *)name;
1214}
1215
1216
1217static void
1218rmat(uid_t uid)
1219{
1220	DIR            *d = opendir("/var/at/jobs");
1221
1222	if (d != NULL) {
1223		struct dirent  *e;
1224
1225		while ((e = readdir(d)) != NULL) {
1226			struct stat     st;
1227
1228			if (strncmp(e->d_name, ".lock", 5) != 0 &&
1229			    stat(e->d_name, &st) == 0 &&
1230			    !S_ISDIR(st.st_mode) &&
1231			    st.st_uid == uid) {
1232				char            tmp[MAXPATHLEN];
1233
1234				sprintf(tmp, "/usr/bin/atrm %s", e->d_name);
1235				system(tmp);
1236			}
1237		}
1238		closedir(d);
1239	}
1240}
1241
1242static void
1243rmopie(char const * name)
1244{
1245	static const char etcopie[] = "/etc/opiekeys";
1246	FILE   *fp = fopen(etcopie, "r+");
1247
1248	if (fp != NULL) {
1249		char	tmp[1024];
1250		off_t	atofs = 0;
1251		int	length = strlen(name);
1252
1253		while (fgets(tmp, sizeof tmp, fp) != NULL) {
1254			if (strncmp(name, tmp, length) == 0 && tmp[length]==' ') {
1255				if (fseek(fp, atofs, SEEK_SET) == 0) {
1256					fwrite("#", 1, 1, fp);	/* Comment username out */
1257				}
1258				break;
1259			}
1260			atofs = ftell(fp);
1261		}
1262		/*
1263		 * If we got an error of any sort, don't update!
1264		 */
1265		fclose(fp);
1266	}
1267}
1268
1269