]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - usr.sbin/pw/pw_user.c
MFC r290174:
[FreeBSD/stable/10.git] / usr.sbin / pw / pw_user.c
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
29 static const char rcsid[] =
30   "$FreeBSD$";
31 #endif /* not lint */
32
33 #include <sys/param.h>
34 #include <sys/resource.h>
35 #include <sys/time.h>
36 #include <sys/types.h>
37
38 #include <ctype.h>
39 #include <dirent.h>
40 #include <err.h>
41 #include <errno.h>
42 #include <fcntl.h>
43 #include <grp.h>
44 #include <pwd.h>
45 #include <libutil.h>
46 #include <login_cap.h>
47 #include <paths.h>
48 #include <string.h>
49 #include <sysexits.h>
50 #include <termios.h>
51 #include <unistd.h>
52
53 #include "pw.h"
54 #include "bitmap.h"
55 #include "psdate.h"
56
57 #define LOGNAMESIZE (MAXLOGNAME-1)
58
59 static          char locked_str[] = "*LOCKED*";
60
61 static struct passwd fakeuser = {
62         "nouser",
63         "*",
64         -1,
65         -1,
66         0,
67         "",
68         "User &",
69         "/nonexistent",
70         "/bin/sh",
71         0,
72         0
73 };
74
75 static int       print_user(struct passwd *pwd, bool pretty, bool v7);
76 static uid_t     pw_uidpolicy(struct userconf *cnf, intmax_t id);
77 static uid_t     pw_gidpolicy(struct userconf *cnf, char *grname, char *nam,
78     gid_t prefer, bool dryrun);
79 static char     *pw_homepolicy(struct userconf * cnf, char *homedir,
80     const char *user);
81 static char     *pw_shellpolicy(struct userconf * cnf);
82 static char     *pw_password(struct userconf * cnf, char const * user,
83     bool dryrun);
84 static char     *shell_path(char const * path, char *shells[], char *sh);
85 static void     rmat(uid_t uid);
86 static void     rmopie(char const * name);
87
88 static void
89 mkdir_home_parents(int dfd, const char *dir)
90 {
91         struct stat st;
92         char *dirs, *tmp;
93
94         if (*dir != '/')
95                 errx(EX_DATAERR, "invalid base directory for home '%s'", dir);
96
97         dir++;
98
99         if (fstatat(dfd, dir, &st, 0) != -1) {
100                 if (S_ISDIR(st.st_mode))
101                         return;
102                 errx(EX_OSFILE, "root home `/%s' is not a directory", dir);
103         }
104
105         dirs = strdup(dir);
106         if (dirs == NULL)
107                 errx(EX_UNAVAILABLE, "out of memory");
108
109         tmp = strrchr(dirs, '/');
110         if (tmp == NULL)
111                 return;
112         tmp[0] = '\0';
113
114         /*
115          * This is a kludge especially for Joerg :)
116          * If the home directory would be created in the root partition, then
117          * we really create it under /usr which is likely to have more space.
118          * But we create a symlink from cnf->home -> "/usr" -> cnf->home
119          */
120         if (strchr(dirs, '/') == NULL) {
121                 asprintf(&tmp, "usr/%s", dirs);
122                 if (tmp == NULL)
123                         errx(EX_UNAVAILABLE, "out of memory");
124                 if (mkdirat(dfd, tmp, _DEF_DIRMODE) != -1 || errno == EEXIST) {
125                         fchownat(dfd, tmp, 0, 0, 0);
126                         symlinkat(tmp, dfd, dirs);
127                 }
128                 free(tmp);
129         }
130         tmp = dirs;
131         if (fstatat(dfd, dirs, &st, 0) == -1) {
132                 while ((tmp = strchr(tmp + 1, '/')) != NULL) {
133                         *tmp = '\0';
134                         if (fstatat(dfd, dirs, &st, 0) == -1) {
135                                 if (mkdirat(dfd, dirs, _DEF_DIRMODE) == -1)
136                                         err(EX_OSFILE,  "'%s' (root home parent) is not a directory", dirs);
137                         }
138                         *tmp = '/';
139                 }
140         }
141         if (fstatat(dfd, dirs, &st, 0) == -1) {
142                 if (mkdirat(dfd, dirs, _DEF_DIRMODE) == -1)
143                         err(EX_OSFILE,  "'%s' (root home parent) is not a directory", dirs);
144                 fchownat(dfd, dirs, 0, 0, 0);
145         }
146
147         free(dirs);
148 }
149
150 static void
151 create_and_populate_homedir(struct userconf *cnf, struct passwd *pwd,
152     const char *skeldir, mode_t homemode, bool update)
153 {
154         int skelfd = -1;
155
156         /* Create home parents directories */
157         mkdir_home_parents(conf.rootfd, pwd->pw_dir);
158
159         if (skeldir != NULL && *skeldir != '\0') {
160                 if (*skeldir == '/')
161                         skeldir++;
162                 skelfd = openat(conf.rootfd, skeldir, O_DIRECTORY|O_CLOEXEC);
163         }
164
165         copymkdir(conf.rootfd, pwd->pw_dir, skelfd, homemode, pwd->pw_uid,
166             pwd->pw_gid, 0);
167         pw_log(cnf, update ? M_UPDATE : M_ADD, W_USER, "%s(%ju) home %s made",
168             pwd->pw_name, (uintmax_t)pwd->pw_uid, pwd->pw_dir);
169 }
170
171 static int
172 pw_set_passwd(struct passwd *pwd, int fd, bool precrypted, bool update)
173 {
174         int              b, istty;
175         struct termios   t, n;
176         login_cap_t     *lc;
177         char            line[_PASSWORD_LEN+1];
178         char            *p;
179
180         if (fd == '-') {
181                 if (!pwd->pw_passwd || *pwd->pw_passwd != '*') {
182                         pwd->pw_passwd = "*";   /* No access */
183                         return (1);
184                 }
185                 return (0);
186         }
187
188         if ((istty = isatty(fd))) {
189                 if (tcgetattr(fd, &t) == -1)
190                         istty = 0;
191                 else {
192                         n = t;
193                         n.c_lflag &= ~(ECHO);
194                         tcsetattr(fd, TCSANOW, &n);
195                         printf("%s%spassword for user %s:",
196                             update ? "new " : "",
197                             precrypted ? "encrypted " : "",
198                             pwd->pw_name);
199                         fflush(stdout);
200                 }
201         }
202         b = read(fd, line, sizeof(line) - 1);
203         if (istty) {    /* Restore state */
204                 tcsetattr(fd, TCSANOW, &t);
205                 fputc('\n', stdout);
206                 fflush(stdout);
207         }
208
209         if (b < 0)
210                 err(EX_IOERR, "-%c file descriptor",
211                     precrypted ? 'H' : 'h');
212         line[b] = '\0';
213         if ((p = strpbrk(line, "\r\n")) != NULL)
214                 *p = '\0';
215         if (!*line)
216                 errx(EX_DATAERR, "empty password read on file descriptor %d",
217                     fd);
218         if (precrypted) {
219                 if (strchr(line, ':') != NULL)
220                         errx(EX_DATAERR, "bad encrypted password");
221                 pwd->pw_passwd = strdup(line);
222         } else {
223                 lc = login_getpwclass(pwd);
224                 if (lc == NULL ||
225                                 login_setcryptfmt(lc, "sha512", NULL) == NULL)
226                         warn("setting crypt(3) format");
227                 login_close(lc);
228                 pwd->pw_passwd = pw_pwcrypt(line);
229         }
230         return (1);
231 }
232
233 static void
234 perform_chgpwent(const char *name, struct passwd *pwd, char *nispasswd)
235 {
236         int rc;
237         struct passwd *nispwd;
238
239         /* duplicate for nis so that chgpwent is not modifying before NIS */
240         if (nispasswd && *nispasswd == '/')
241                 nispwd = pw_dup(pwd);
242
243         rc = chgpwent(name, pwd);
244         if (rc == -1)
245                 errx(EX_IOERR, "user '%s' does not exist (NIS?)", pwd->pw_name);
246         else if (rc != 0)
247                 err(EX_IOERR, "passwd file update");
248
249         if (nispasswd && *nispasswd == '/') {
250                 rc = chgnispwent(nispasswd, name, nispwd);
251                 if (rc == -1)
252                         warn("User '%s' not found in NIS passwd", pwd->pw_name);
253                 else if (rc != 0)
254                         warn("NIS passwd update");
255                 /* NOTE: NIS-only update errors are not fatal */
256         }
257 }
258
259 /*
260  * The M_LOCK and M_UNLOCK functions simply add or remove
261  * a "*LOCKED*" prefix from in front of the password to
262  * prevent it decoding correctly, and therefore prevents
263  * access. Of course, this only prevents access via
264  * password authentication (not ssh, kerberos or any
265  * other method that does not use the UNIX password) but
266  * that is a known limitation.
267  */
268 static int
269 pw_userlock(char *arg1, int mode)
270 {
271         struct passwd *pwd = NULL;
272         char *passtmp = NULL;
273         char *name;
274         bool locked = false;
275         uid_t id;
276
277         if (geteuid() != 0)
278                 errx(EX_NOPERM, "you must be root");
279
280         if (arg1 == NULL)
281                 errx(EX_DATAERR, "username or id required");
282
283         if (arg1[strspn(arg1, "0123456789")] == '\0') {
284                 id = pw_checkid(arg1, UID_MAX);
285                 name = NULL;
286         } else
287                 name = arg1;
288
289         pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
290         if (pwd == NULL) {
291                 if (name == NULL)
292                         errx(EX_NOUSER, "no such uid `%ju'", (uintmax_t) id);
293                 errx(EX_NOUSER, "no such user `%s'", name);
294         }
295
296         if (name == NULL)
297                 name = pwd->pw_name;
298
299         if (strncmp(pwd->pw_passwd, locked_str, sizeof(locked_str) -1) == 0)
300                 locked = true;
301         if (mode == M_LOCK && locked)
302                 errx(EX_DATAERR, "user '%s' is already locked", pwd->pw_name);
303         if (mode == M_UNLOCK && !locked)
304                 errx(EX_DATAERR, "user '%s' is not locked", pwd->pw_name);
305
306         if (mode == M_LOCK) {
307                 asprintf(&passtmp, "%s%s", locked_str, pwd->pw_passwd);
308                 if (passtmp == NULL)    /* disaster */
309                         errx(EX_UNAVAILABLE, "out of memory");
310                 pwd->pw_passwd = passtmp;
311         } else {
312                 pwd->pw_passwd += sizeof(locked_str)-1;
313         }
314
315         perform_chgpwent(name, pwd, NULL);
316         free(passtmp);
317
318         return (EXIT_SUCCESS);
319 }
320
321 static uid_t
322 pw_uidpolicy(struct userconf * cnf, intmax_t id)
323 {
324         struct passwd  *pwd;
325         struct bitmap   bm;
326         uid_t           uid = (uid_t) - 1;
327
328         /*
329          * Check the given uid, if any
330          */
331         if (id >= 0) {
332                 uid = (uid_t) id;
333
334                 if ((pwd = GETPWUID(uid)) != NULL && conf.checkduplicate)
335                         errx(EX_DATAERR, "uid `%ju' has already been allocated",
336                             (uintmax_t)pwd->pw_uid);
337                 return (uid);
338         }
339         /*
340          * We need to allocate the next available uid under one of
341          * two policies a) Grab the first unused uid b) Grab the
342          * highest possible unused uid
343          */
344         if (cnf->min_uid >= cnf->max_uid) {     /* Sanity
345                                                  * claus^H^H^H^Hheck */
346                 cnf->min_uid = 1000;
347                 cnf->max_uid = 32000;
348         }
349         bm = bm_alloc(cnf->max_uid - cnf->min_uid + 1);
350
351         /*
352          * Now, let's fill the bitmap from the password file
353          */
354         SETPWENT();
355         while ((pwd = GETPWENT()) != NULL)
356                 if (pwd->pw_uid >= (uid_t) cnf->min_uid && pwd->pw_uid <= (uid_t) cnf->max_uid)
357                         bm_setbit(&bm, pwd->pw_uid - cnf->min_uid);
358         ENDPWENT();
359
360         /*
361          * Then apply the policy, with fallback to reuse if necessary
362          */
363         if (cnf->reuse_uids || (uid = (uid_t) (bm_lastset(&bm) + cnf->min_uid + 1)) > cnf->max_uid)
364                 uid = (uid_t) (bm_firstunset(&bm) + cnf->min_uid);
365
366         /*
367          * Another sanity check
368          */
369         if (uid < cnf->min_uid || uid > cnf->max_uid)
370                 errx(EX_SOFTWARE, "unable to allocate a new uid - range fully used");
371         bm_dealloc(&bm);
372         return (uid);
373 }
374
375 static uid_t
376 pw_gidpolicy(struct userconf *cnf, char *grname, char *nam, gid_t prefer, bool dryrun)
377 {
378         struct group   *grp;
379         gid_t           gid = (uid_t) - 1;
380
381         /*
382          * Check the given gid, if any
383          */
384         SETGRENT();
385         if (grname) {
386                 if ((grp = GETGRNAM(grname)) == NULL) {
387                         gid = pw_checkid(grname, GID_MAX);
388                         grp = GETGRGID(gid);
389                 }
390                 gid = grp->gr_gid;
391         } else if ((grp = GETGRNAM(nam)) != NULL &&
392             (grp->gr_mem == NULL || grp->gr_mem[0] == NULL)) {
393                 gid = grp->gr_gid;  /* Already created? Use it anyway... */
394         } else {
395                 intmax_t                grid = -1;
396
397                 /*
398                  * We need to auto-create a group with the user's name. We
399                  * can send all the appropriate output to our sister routine
400                  * bit first see if we can create a group with gid==uid so we
401                  * can keep the user and group ids in sync. We purposely do
402                  * NOT check the gid range if we can force the sync. If the
403                  * user's name dups an existing group, then the group add
404                  * function will happily handle that case for us and exit.
405                  */
406                 if (GETGRGID(prefer) == NULL)
407                         grid = prefer;
408                 if (dryrun) {
409                         gid = pw_groupnext(cnf, true);
410                 } else {
411                         if (grid == -1)
412                                 grid =  pw_groupnext(cnf, true);
413                         groupadd(cnf, nam, grid, NULL, -1, false, false, false);
414                         if ((grp = GETGRNAM(nam)) != NULL)
415                                 gid = grp->gr_gid;
416                 }
417         }
418         ENDGRENT();
419         return (gid);
420 }
421
422 static char *
423 pw_homepolicy(struct userconf * cnf, char *homedir, const char *user)
424 {
425         static char     home[128];
426
427         if (homedir)
428                 return (homedir);
429
430         if (cnf->home == NULL || *cnf->home == '\0')
431                 errx(EX_CONFIG, "no base home directory set");
432         snprintf(home, sizeof(home), "%s/%s", cnf->home, user);
433
434         return (home);
435 }
436
437 static char *
438 shell_path(char const * path, char *shells[], char *sh)
439 {
440         if (sh != NULL && (*sh == '/' || *sh == '\0'))
441                 return sh;      /* specified full path or forced none */
442         else {
443                 char           *p;
444                 char            paths[_UC_MAXLINE];
445
446                 /*
447                  * We need to search paths
448                  */
449                 strlcpy(paths, path, sizeof(paths));
450                 for (p = strtok(paths, ": \t\r\n"); p != NULL; p = strtok(NULL, ": \t\r\n")) {
451                         int             i;
452                         static char     shellpath[256];
453
454                         if (sh != NULL) {
455                                 snprintf(shellpath, sizeof(shellpath), "%s/%s", p, sh);
456                                 if (access(shellpath, X_OK) == 0)
457                                         return shellpath;
458                         } else
459                                 for (i = 0; i < _UC_MAXSHELLS && shells[i] != NULL; i++) {
460                                         snprintf(shellpath, sizeof(shellpath), "%s/%s", p, shells[i]);
461                                         if (access(shellpath, X_OK) == 0)
462                                                 return shellpath;
463                                 }
464                 }
465                 if (sh == NULL)
466                         errx(EX_OSFILE, "can't find shell `%s' in shell paths", sh);
467                 errx(EX_CONFIG, "no default shell available or defined");
468                 return NULL;
469         }
470 }
471
472 static char *
473 pw_shellpolicy(struct userconf * cnf)
474 {
475
476         return shell_path(cnf->shelldir, cnf->shells, cnf->shell_default);
477 }
478
479 #define SALTSIZE        32
480
481 static char const chars[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ./";
482
483 char *
484 pw_pwcrypt(char *password)
485 {
486         int             i;
487         char            salt[SALTSIZE + 1];
488         char            *cryptpw;
489         static char     buf[256];
490
491         /*
492          * Calculate a salt value
493          */
494         for (i = 0; i < SALTSIZE; i++)
495                 salt[i] = chars[arc4random_uniform(sizeof(chars) - 1)];
496         salt[SALTSIZE] = '\0';
497
498         cryptpw = crypt(password, salt);
499         if (cryptpw == NULL)
500                 errx(EX_CONFIG, "crypt(3) failure");
501         return strcpy(buf, cryptpw);
502 }
503
504 static char *
505 pw_password(struct userconf * cnf, char const * user, bool dryrun)
506 {
507         int             i, l;
508         char            pwbuf[32];
509
510         switch (cnf->default_password) {
511         case -1:                /* Random password */
512                 l = (arc4random() % 8 + 8);     /* 8 - 16 chars */
513                 for (i = 0; i < l; i++)
514                         pwbuf[i] = chars[arc4random_uniform(sizeof(chars)-1)];
515                 pwbuf[i] = '\0';
516
517                 /*
518                  * We give this information back to the user
519                  */
520                 if (conf.fd == -1 && !dryrun) {
521                         if (isatty(STDOUT_FILENO))
522                                 printf("Password for '%s' is: ", user);
523                         printf("%s\n", pwbuf);
524                         fflush(stdout);
525                 }
526                 break;
527
528         case -2:                /* No password at all! */
529                 return "";
530
531         case 0:         /* No login - default */
532         default:
533                 return "*";
534
535         case 1:         /* user's name */
536                 strlcpy(pwbuf, user, sizeof(pwbuf));
537                 break;
538         }
539         return pw_pwcrypt(pwbuf);
540 }
541
542 static int
543 print_user(struct passwd * pwd, bool pretty, bool v7)
544 {
545         int             j;
546         char           *p;
547         struct group   *grp = GETGRGID(pwd->pw_gid);
548         char            uname[60] = "User &", office[60] = "[None]",
549                         wphone[60] = "[None]", hphone[60] = "[None]";
550         char            acexpire[32] = "[None]", pwexpire[32] = "[None]";
551         struct tm *    tptr;
552
553         if (!pretty) {
554                 p = v7 ? pw_make_v7(pwd) : pw_make(pwd);
555                 printf("%s\n", p);
556                 free(p);
557                 return (EXIT_SUCCESS);
558         }
559
560         if ((p = strtok(pwd->pw_gecos, ",")) != NULL) {
561                 strlcpy(uname, p, sizeof(uname));
562                 if ((p = strtok(NULL, ",")) != NULL) {
563                         strlcpy(office, p, sizeof(office));
564                         if ((p = strtok(NULL, ",")) != NULL) {
565                                 strlcpy(wphone, p, sizeof(wphone));
566                                 if ((p = strtok(NULL, "")) != NULL) {
567                                         strlcpy(hphone, p, sizeof(hphone));
568                                 }
569                         }
570                 }
571         }
572         /*
573          * Handle '&' in gecos field
574          */
575         if ((p = strchr(uname, '&')) != NULL) {
576                 int             l = strlen(pwd->pw_name);
577                 int             m = strlen(p);
578
579                 memmove(p + l, p + 1, m);
580                 memmove(p, pwd->pw_name, l);
581                 *p = (char) toupper((unsigned char)*p);
582         }
583         if (pwd->pw_expire > (time_t)0 && (tptr = localtime(&pwd->pw_expire)) != NULL)
584                 strftime(acexpire, sizeof acexpire, "%c", tptr);
585                 if (pwd->pw_change > (time_t)0 && (tptr = localtime(&pwd->pw_change)) != NULL)
586                 strftime(pwexpire, sizeof pwexpire, "%c", tptr);
587         printf("Login Name: %-15s   #%-12ju Group: %-15s   #%ju\n"
588                " Full Name: %s\n"
589                "      Home: %-26.26s      Class: %s\n"
590                "     Shell: %-26.26s     Office: %s\n"
591                "Work Phone: %-26.26s Home Phone: %s\n"
592                "Acc Expire: %-26.26s Pwd Expire: %s\n",
593                pwd->pw_name, (uintmax_t)pwd->pw_uid,
594                grp ? grp->gr_name : "(invalid)", (uintmax_t)pwd->pw_gid,
595                uname, pwd->pw_dir, pwd->pw_class,
596                pwd->pw_shell, office, wphone, hphone,
597                acexpire, pwexpire);
598         SETGRENT();
599         j = 0;
600         while ((grp=GETGRENT()) != NULL) {
601                 int     i = 0;
602                 if (grp->gr_mem != NULL) {
603                         while (grp->gr_mem[i] != NULL) {
604                                 if (strcmp(grp->gr_mem[i], pwd->pw_name)==0) {
605                                         printf(j++ == 0 ? "    Groups: %s" : ",%s", grp->gr_name);
606                                         break;
607                                 }
608                                 ++i;
609                         }
610                 }
611         }
612         ENDGRENT();
613         printf("%s", j ? "\n" : "");
614         return (EXIT_SUCCESS);
615 }
616
617 char *
618 pw_checkname(char *name, int gecos)
619 {
620         char showch[8];
621         const char *badchars, *ch, *showtype;
622         int reject;
623
624         ch = name;
625         reject = 0;
626         if (gecos) {
627                 /* See if the name is valid as a gecos (comment) field. */
628                 badchars = ":!@";
629                 showtype = "gecos field";
630         } else {
631                 /* See if the name is valid as a userid or group. */
632                 badchars = " ,\t:+&#%$^()!@~*?<>=|\\/\"";
633                 showtype = "userid/group name";
634                 /* Userids and groups can not have a leading '-'. */
635                 if (*ch == '-')
636                         reject = 1;
637         }
638         if (!reject) {
639                 while (*ch) {
640                         if (strchr(badchars, *ch) != NULL || *ch < ' ' ||
641                             *ch == 127) {
642                                 reject = 1;
643                                 break;
644                         }
645                         /* 8-bit characters are only allowed in GECOS fields */
646                         if (!gecos && (*ch & 0x80)) {
647                                 reject = 1;
648                                 break;
649                         }
650                         ch++;
651                 }
652         }
653         /*
654          * A `$' is allowed as the final character for userids and groups,
655          * mainly for the benefit of samba.
656          */
657         if (reject && !gecos) {
658                 if (*ch == '$' && *(ch + 1) == '\0') {
659                         reject = 0;
660                         ch++;
661                 }
662         }
663         if (reject) {
664                 snprintf(showch, sizeof(showch), (*ch >= ' ' && *ch < 127)
665                     ? "`%c'" : "0x%02x", *ch);
666                 errx(EX_DATAERR, "invalid character %s at position %td in %s",
667                     showch, (ch - name), showtype);
668         }
669         if (!gecos && (ch - name) > LOGNAMESIZE)
670                 errx(EX_USAGE, "name too long `%s' (max is %d)", name,
671                     LOGNAMESIZE);
672
673         return (name);
674 }
675
676 static void
677 rmat(uid_t uid)
678 {
679         DIR            *d = opendir("/var/at/jobs");
680
681         if (d != NULL) {
682                 struct dirent  *e;
683
684                 while ((e = readdir(d)) != NULL) {
685                         struct stat     st;
686
687                         if (strncmp(e->d_name, ".lock", 5) != 0 &&
688                             stat(e->d_name, &st) == 0 &&
689                             !S_ISDIR(st.st_mode) &&
690                             st.st_uid == uid) {
691                                 char            tmp[MAXPATHLEN];
692
693                                 snprintf(tmp, sizeof(tmp), "/usr/bin/atrm %s",
694                                     e->d_name);
695                                 system(tmp);
696                         }
697                 }
698                 closedir(d);
699         }
700 }
701
702 static void
703 rmopie(char const * name)
704 {
705         char tmp[1014];
706         FILE *fp;
707         int fd;
708         size_t len;
709         off_t   atofs = 0;
710         
711         if ((fd = openat(conf.rootfd, "etc/opiekeys", O_RDWR)) == -1)
712                 return;
713
714         fp = fdopen(fd, "r+");
715         len = strlen(name);
716
717         while (fgets(tmp, sizeof(tmp), fp) != NULL) {
718                 if (strncmp(name, tmp, len) == 0 && tmp[len]==' ') {
719                         /* Comment username out */
720                         if (fseek(fp, atofs, SEEK_SET) == 0)
721                                 fwrite("#", 1, 1, fp);
722                         break;
723                 }
724                 atofs = ftell(fp);
725         }
726         /*
727          * If we got an error of any sort, don't update!
728          */
729         fclose(fp);
730 }
731
732 int
733 pw_user_next(int argc, char **argv, char *name __unused)
734 {
735         struct userconf *cnf = NULL;
736         const char *cfg = NULL;
737         int ch;
738         bool quiet = false;
739         uid_t next;
740
741         while ((ch = getopt(argc, argv, "Cq")) != -1) {
742                 switch (ch) {
743                 case 'C':
744                         cfg = optarg;
745                         break;
746                 case 'q':
747                         quiet = true;
748                         break;
749                 }
750         }
751
752         if (quiet)
753                 freopen(_PATH_DEVNULL, "w", stderr);
754
755         cnf = get_userconfig(cfg);
756
757         next = pw_uidpolicy(cnf, -1);
758
759         printf("%ju:", (uintmax_t)next);
760         pw_groupnext(cnf, quiet);
761
762         return (EXIT_SUCCESS);
763 }
764
765 int
766 pw_user_show(int argc, char **argv, char *arg1)
767 {
768         struct passwd *pwd = NULL;
769         char *name = NULL;
770         intmax_t id = -1;
771         int ch;
772         bool all = false;
773         bool pretty = false;
774         bool force = false;
775         bool v7 = false;
776         bool quiet = false;
777
778         if (arg1 != NULL) {
779                 if (arg1[strspn(arg1, "0123456789")] == '\0')
780                         id = pw_checkid(arg1, UID_MAX);
781                 else
782                         name = arg1;
783         }
784
785         while ((ch = getopt(argc, argv, "C:qn:u:FPa7")) != -1) {
786                 switch (ch) {
787                 case 'C':
788                         /* ignore compatibility */
789                         break;
790                 case 'q':
791                         quiet = true;
792                         break;
793                 case 'n':
794                         name = optarg;
795                         break;
796                 case 'u':
797                         id = pw_checkid(optarg, UID_MAX);
798                         break;
799                 case 'F':
800                         force = true;
801                         break;
802                 case 'P':
803                         pretty = true;
804                         break;
805                 case 'a':
806                         all = true;
807                         break;
808                 case 7:
809                         v7 = true;
810                         break;
811                 }
812         }
813
814         if (quiet)
815                 freopen(_PATH_DEVNULL, "w", stderr);
816
817         if (all) {
818                 SETPWENT();
819                 while ((pwd = GETPWENT()) != NULL)
820                         print_user(pwd, pretty, v7);
821                 ENDPWENT();
822                 return (EXIT_SUCCESS);
823         }
824
825         if (id < 0 && name == NULL)
826                 errx(EX_DATAERR, "username or id required");
827
828         pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
829         if (pwd == NULL) {
830                 if (force) {
831                         pwd = &fakeuser;
832                 } else {
833                         if (name == NULL)
834                                 errx(EX_NOUSER, "no such uid `%ju'",
835                                     (uintmax_t) id);
836                         errx(EX_NOUSER, "no such user `%s'", name);
837                 }
838         }
839
840         return (print_user(pwd, pretty, v7));
841 }
842
843 int
844 pw_user_del(int argc, char **argv, char *arg1)
845 {
846         struct userconf *cnf = NULL;
847         struct passwd *pwd = NULL;
848         struct group *gr, *grp;
849         char *name = NULL;
850         char grname[MAXLOGNAME];
851         char *nispasswd = NULL;
852         char file[MAXPATHLEN];
853         char home[MAXPATHLEN];
854         const char *cfg = NULL;
855         struct stat st;
856         intmax_t id = -1;
857         int ch, rc;
858         bool nis = false;
859         bool deletehome = false;
860         bool quiet = false;
861
862         if (arg1 != NULL) {
863                 if (arg1[strspn(arg1, "0123456789")] == '\0')
864                         id = pw_checkid(arg1, UID_MAX);
865                 else
866                         name = arg1;
867         }
868
869         while ((ch = getopt(argc, argv, "C:qn:u:rYy:")) != -1) {
870                 switch (ch) {
871                 case 'C':
872                         cfg = optarg;
873                         break;
874                 case 'q':
875                         quiet = true;
876                         break;
877                 case 'n':
878                         name = optarg;
879                         break;
880                 case 'u':
881                         id = pw_checkid(optarg, UID_MAX);
882                         break;
883                 case 'r':
884                         deletehome = true;
885                         break;
886                 case 'y':
887                         nispasswd = optarg;
888                         break;
889                 case 'Y':
890                         nis = true;
891                         break;
892                 }
893         }
894
895         if (quiet)
896                 freopen(_PATH_DEVNULL, "w", stderr);
897
898         if (id < 0 && name == NULL)
899                 errx(EX_DATAERR, "username or id required");
900
901         cnf = get_userconfig(cfg);
902
903         if (nispasswd == NULL)
904                 nispasswd = cnf->nispasswd;
905
906         pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
907         if (pwd == NULL) {
908                 if (name == NULL)
909                         errx(EX_NOUSER, "no such uid `%ju'", (uintmax_t) id);
910                 errx(EX_NOUSER, "no such user `%s'", name);
911         }
912
913         if (PWF._altdir == PWF_REGULAR &&
914             ((pwd->pw_fields & _PWF_SOURCE) != _PWF_FILES)) {
915                 if ((pwd->pw_fields & _PWF_SOURCE) == _PWF_NIS) {
916                         if (!nis && nispasswd && *nispasswd != '/')
917                                 errx(EX_NOUSER, "Cannot remove NIS user `%s'",
918                                     name);
919                 } else {
920                         errx(EX_NOUSER, "Cannot remove non local user `%s'",
921                             name);
922                 }
923         }
924
925         id = pwd->pw_uid;
926         if (name == NULL)
927                 name = pwd->pw_name;
928
929         if (strcmp(pwd->pw_name, "root") == 0)
930                 errx(EX_DATAERR, "cannot remove user 'root'");
931
932         /* Remove opie record from /etc/opiekeys */
933         if (PWALTDIR() != PWF_ALT)
934                 rmopie(pwd->pw_name);
935
936         if (!PWALTDIR()) {
937                 /* Remove crontabs */
938                 snprintf(file, sizeof(file), "/var/cron/tabs/%s", pwd->pw_name);
939                 if (access(file, F_OK) == 0) {
940                         snprintf(file, sizeof(file), "crontab -u %s -r",
941                             pwd->pw_name);
942                         system(file);
943                 }
944         }
945
946         /*
947          * Save these for later, since contents of pwd may be
948          * invalidated by deletion
949          */
950         snprintf(file, sizeof(file), "%s/%s", _PATH_MAILDIR, pwd->pw_name);
951         strlcpy(home, pwd->pw_dir, sizeof(home));
952         gr = GETGRGID(pwd->pw_gid);
953         if (gr != NULL)
954                 strlcpy(grname, gr->gr_name, LOGNAMESIZE);
955         else
956                 grname[0] = '\0';
957
958         rc = delpwent(pwd);
959         if (rc == -1)
960                 err(EX_IOERR, "user '%s' does not exist", pwd->pw_name);
961         else if (rc != 0)
962                 err(EX_IOERR, "passwd update");
963
964         if (nis && nispasswd && *nispasswd=='/') {
965                 rc = delnispwent(nispasswd, name);
966                 if (rc == -1)
967                         warnx("WARNING: user '%s' does not exist in NIS passwd",
968                             pwd->pw_name);
969                 else if (rc != 0)
970                         warn("WARNING: NIS passwd update");
971         }
972
973         grp = GETGRNAM(name);
974         if (grp != NULL &&
975             (grp->gr_mem == NULL || *grp->gr_mem == NULL) &&
976             strcmp(name, grname) == 0)
977                 delgrent(GETGRNAM(name));
978         SETGRENT();
979         while ((grp = GETGRENT()) != NULL) {
980                 int i, j;
981                 char group[MAXLOGNAME];
982                 if (grp->gr_mem == NULL)
983                         continue;
984
985                 for (i = 0; grp->gr_mem[i] != NULL; i++) {
986                         if (strcmp(grp->gr_mem[i], name) != 0)
987                                 continue;
988
989                         for (j = i; grp->gr_mem[j] != NULL; j++)
990                                 grp->gr_mem[j] = grp->gr_mem[j+1];
991                         strlcpy(group, grp->gr_name, MAXLOGNAME);
992                         chggrent(group, grp);
993                 }
994         }
995         ENDGRENT();
996
997         pw_log(cnf, M_DELETE, W_USER, "%s(%ju) account removed", name,
998             (uintmax_t)id);
999
1000         /* Remove mail file */
1001         if (PWALTDIR() != PWF_ALT)
1002                 unlinkat(conf.rootfd, file + 1, 0);
1003
1004         /* Remove at jobs */
1005         if (!PWALTDIR() && getpwuid(id) == NULL)
1006                 rmat(id);
1007
1008         /* Remove home directory and contents */
1009         if (PWALTDIR() != PWF_ALT && deletehome && *home == '/' &&
1010             GETPWUID(id) == NULL &&
1011             fstatat(conf.rootfd, home + 1, &st, 0) != -1) {
1012                 rm_r(conf.rootfd, home, id);
1013                 pw_log(cnf, M_DELETE, W_USER, "%s(%ju) home '%s' %s"
1014                     "removed", name, (uintmax_t)id, home,
1015                      fstatat(conf.rootfd, home + 1, &st, 0) == -1 ? "" : "not "
1016                      "completely ");
1017         }
1018
1019         return (EXIT_SUCCESS);
1020 }
1021
1022 int
1023 pw_user_lock(int argc, char **argv, char *arg1)
1024 {
1025         int ch;
1026
1027         while ((ch = getopt(argc, argv, "Cq")) != -1) {
1028                 switch (ch) {
1029                 case 'C':
1030                 case 'q':
1031                         /* compatibility */
1032                         break;
1033                 }
1034         }
1035
1036         return (pw_userlock(arg1, M_LOCK));
1037 }
1038
1039 int
1040 pw_user_unlock(int argc, char **argv, char *arg1)
1041 {
1042         int ch;
1043
1044         while ((ch = getopt(argc, argv, "Cq")) != -1) {
1045                 switch (ch) {
1046                 case 'C':
1047                 case 'q':
1048                         /* compatibility */
1049                         break;
1050                 }
1051         }
1052
1053         return (pw_userlock(arg1, M_UNLOCK));
1054 }
1055
1056 static struct group *
1057 group_from_name_or_id(char *name)
1058 {
1059         const char *errstr = NULL;
1060         struct group *grp;
1061         uintmax_t id;
1062
1063         if ((grp = GETGRNAM(name)) == NULL) {
1064                 id = strtounum(name, 0, GID_MAX, &errstr);
1065                 if (errstr)
1066                         errx(EX_NOUSER, "group `%s' does not exist", name);
1067                 grp = GETGRGID(id);
1068                 if (grp == NULL)
1069                         errx(EX_NOUSER, "group `%s' does not exist", name);
1070         }
1071
1072         return (grp);
1073 }
1074
1075 static void
1076 split_groups(StringList **groups, char *groupsstr)
1077 {
1078         struct group *grp;
1079         char *p;
1080         char tok[] = ", \t";
1081
1082         for (p = strtok(groupsstr, tok); p != NULL; p = strtok(NULL, tok)) {
1083                 grp = group_from_name_or_id(p);
1084                 if (*groups == NULL)
1085                         *groups = sl_init();
1086                 sl_add(*groups, newstr(grp->gr_name));
1087         }
1088 }
1089
1090 static void
1091 validate_grname(struct userconf *cnf, char *group)
1092 {
1093         struct group *grp;
1094
1095         if (group == NULL || *group == '\0') {
1096                 cnf->default_group = "";
1097                 return;
1098         }
1099         grp = group_from_name_or_id(group);
1100         cnf->default_group = newstr(grp->gr_name);
1101 }
1102
1103 static mode_t
1104 validate_mode(char *mode)
1105 {
1106         mode_t m;
1107         void *set;
1108
1109         if ((set = setmode(mode)) == NULL)
1110                 errx(EX_DATAERR, "invalid directory creation mode '%s'", mode);
1111
1112         m = getmode(set, _DEF_DIRMODE);
1113         free(set);
1114         return (m);
1115 }
1116
1117 static void
1118 mix_config(struct userconf *cmdcnf, struct userconf *cfg)
1119 {
1120
1121         if (cmdcnf->default_password == 0)
1122                 cmdcnf->default_password = cfg->default_password;
1123         if (cmdcnf->reuse_uids == 0)
1124                 cmdcnf->reuse_uids = cfg->reuse_uids;
1125         if (cmdcnf->reuse_gids == 0)
1126                 cmdcnf->reuse_gids = cfg->reuse_gids;
1127         if (cmdcnf->nispasswd == NULL)
1128                 cmdcnf->nispasswd = cfg->nispasswd;
1129         if (cmdcnf->dotdir == NULL)
1130                 cmdcnf->dotdir = cfg->dotdir;
1131         if (cmdcnf->newmail == NULL)
1132                 cmdcnf->newmail = cfg->newmail;
1133         if (cmdcnf->logfile == NULL)
1134                 cmdcnf->logfile = cfg->logfile;
1135         if (cmdcnf->home == NULL)
1136                 cmdcnf->home = cfg->home;
1137         if (cmdcnf->homemode == 0)
1138                 cmdcnf->homemode = cfg->homemode;
1139         if (cmdcnf->shelldir == NULL)
1140                 cmdcnf->shelldir = cfg->shelldir;
1141         if (cmdcnf->shells == NULL)
1142                 cmdcnf->shells = cfg->shells;
1143         if (cmdcnf->shell_default == NULL)
1144                 cmdcnf->shell_default = cfg->shell_default;
1145         if (cmdcnf->default_group == NULL)
1146                 cmdcnf->default_group = cfg->default_group;
1147         if (cmdcnf->groups == NULL)
1148                 cmdcnf->groups = cfg->groups;
1149         if (cmdcnf->default_class == NULL)
1150                 cmdcnf->default_class = cfg->default_class;
1151         if (cmdcnf->min_uid == 0)
1152                 cmdcnf->min_uid = cfg->min_uid;
1153         if (cmdcnf->max_uid == 0)
1154                 cmdcnf->max_uid = cfg->max_uid;
1155         if (cmdcnf->min_gid == 0)
1156                 cmdcnf->min_gid = cfg->min_gid;
1157         if (cmdcnf->max_gid == 0)
1158                 cmdcnf->max_gid = cfg->max_gid;
1159         if (cmdcnf->expire_days == 0)
1160                 cmdcnf->expire_days = cfg->expire_days;
1161         if (cmdcnf->password_days == 0)
1162                 cmdcnf->password_days = cfg->password_days;
1163 }
1164
1165 int
1166 pw_user_add(int argc, char **argv, char *arg1)
1167 {
1168         struct userconf *cnf, *cmdcnf;
1169         struct passwd *pwd;
1170         struct group *grp;
1171         struct stat st;
1172         char args[] = "C:qn:u:c:d:e:p:g:G:mM:k:s:oL:i:w:h:H:Db:NPy:Y";
1173         char line[_PASSWORD_LEN+1], path[MAXPATHLEN];
1174         char *gecos, *homedir, *skel, *walk, *userid, *groupid, *grname;
1175         char *default_passwd, *name, *p;
1176         const char *cfg;
1177         login_cap_t *lc;
1178         FILE *pfp, *fp;
1179         intmax_t id = -1;
1180         time_t now;
1181         int rc, ch, fd = -1;
1182         size_t i;
1183         bool dryrun, nis, pretty, quiet, createhome, precrypted, genconf;
1184
1185         dryrun = nis = pretty = quiet = createhome = precrypted = false;
1186         genconf = false;
1187         gecos = homedir = skel = userid = groupid = default_passwd = NULL;
1188         grname = name = NULL;
1189
1190         if ((cmdcnf = calloc(1, sizeof(struct userconf))) == NULL)
1191                 err(EXIT_FAILURE, "calloc()");
1192
1193         if (arg1 != NULL) {
1194                 if (arg1[strspn(arg1, "0123456789")] == '\0')
1195                         id = pw_checkid(arg1, UID_MAX);
1196                 else
1197                         name = arg1;
1198         }
1199
1200         while ((ch = getopt(argc, argv, args)) != -1) {
1201                 switch (ch) {
1202                 case 'C':
1203                         cfg = optarg;
1204                         break;
1205                 case 'q':
1206                         quiet = true;
1207                         break;
1208                 case 'n':
1209                         name = optarg;
1210                         break;
1211                 case 'u':
1212                         userid = optarg;
1213                         break;
1214                 case 'c':
1215                         gecos = pw_checkname(optarg, 1);
1216                         break;
1217                 case 'd':
1218                         homedir = optarg;
1219                         break;
1220                 case 'e':
1221                         now = time(NULL);
1222                         cmdcnf->expire_days = parse_date(now, optarg);
1223                         break;
1224                 case 'p':
1225                         now = time(NULL);
1226                         cmdcnf->password_days = parse_date(now, optarg);
1227                         break;
1228                 case 'g':
1229                         validate_grname(cmdcnf, optarg);
1230                         grname = optarg;
1231                         break;
1232                 case 'G':
1233                         split_groups(&cmdcnf->groups, optarg);
1234                         break;
1235                 case 'm':
1236                         createhome = true;
1237                         break;
1238                 case 'M':
1239                         cmdcnf->homemode = validate_mode(optarg);
1240                         break;
1241                 case 'k':
1242                         walk = skel = optarg;
1243                         if (*walk == '/')
1244                                 walk++;
1245                         if (fstatat(conf.rootfd, walk, &st, 0) == -1)
1246                                 errx(EX_OSFILE, "skeleton `%s' does not "
1247                                     "exists", skel);
1248                         if (!S_ISDIR(st.st_mode))
1249                                 errx(EX_OSFILE, "skeleton `%s' is not a "
1250                                     "directory", skel);
1251                         cmdcnf->dotdir = skel;
1252                         break;
1253                 case 's':
1254                         cmdcnf->shell_default = optarg;
1255                         break;
1256                 case 'o':
1257                         conf.checkduplicate = false;
1258                         break;
1259                 case 'L':
1260                         cmdcnf->default_class = pw_checkname(optarg, 0);
1261                         break;
1262                 case 'i':
1263                         groupid = optarg;
1264                         break;
1265                 case 'w':
1266                         default_passwd = optarg;
1267                         break;
1268                 case 'H':
1269                         if (fd != -1)
1270                                 errx(EX_USAGE, "'-h' and '-H' are mutually "
1271                                     "exclusive options");
1272                         fd = pw_checkfd(optarg);
1273                         precrypted = true;
1274                         if (fd == '-')
1275                                 errx(EX_USAGE, "-H expects a file descriptor");
1276                         break;
1277                 case 'h':
1278                         if (fd != -1)
1279                                 errx(EX_USAGE, "'-h' and '-H' are mutually "
1280                                     "exclusive options");
1281                         fd = pw_checkfd(optarg);
1282                         break;
1283                 case 'D':
1284                         genconf = true;
1285                         break;
1286                 case 'b':
1287                         cmdcnf->home = optarg;
1288                         break;
1289                 case 'N':
1290                         dryrun = true;
1291                         break;
1292                 case 'P':
1293                         pretty = true;
1294                         break;
1295                 case 'y':
1296                         cmdcnf->nispasswd = optarg;
1297                         break;
1298                 case 'Y':
1299                         nis = true;
1300                         break;
1301                 }
1302         }
1303
1304         if (geteuid() != 0 && ! dryrun)
1305                 errx(EX_NOPERM, "you must be root");
1306
1307         if (quiet)
1308                 freopen(_PATH_DEVNULL, "w", stderr);
1309
1310         cnf = get_userconfig(cfg);
1311
1312         mix_config(cmdcnf, cnf);
1313         if (default_passwd)
1314                 cmdcnf->default_password = boolean_val(default_passwd,
1315                     cnf->default_password);
1316         if (genconf) {
1317                 if (name != NULL)
1318                         errx(EX_DATAERR, "can't combine `-D' with `-n name'");
1319                 if (userid != NULL) {
1320                         if ((p = strtok(userid, ", \t")) != NULL)
1321                                 cmdcnf->min_uid = pw_checkid(p, UID_MAX);
1322                         if (cmdcnf->min_uid == 0)
1323                                 cmdcnf->min_uid = 1000;
1324                         if ((p = strtok(NULL, " ,\t")) != NULL)
1325                                 cmdcnf->max_uid = pw_checkid(p, UID_MAX);
1326                         if (cmdcnf->max_uid == 0)
1327                                 cmdcnf->max_uid = 32000;
1328                 }
1329                 if (groupid != NULL) {
1330                         if ((p = strtok(groupid, ", \t")) != NULL)
1331                                 cmdcnf->min_gid = pw_checkid(p, GID_MAX);
1332                         if (cmdcnf->min_gid == 0)
1333                                 cmdcnf->min_gid = 1000;
1334                         if ((p = strtok(NULL, " ,\t")) != NULL)
1335                                 cmdcnf->max_gid = pw_checkid(p, GID_MAX);
1336                         if (cmdcnf->max_gid == 0)
1337                                 cmdcnf->max_gid = 32000;
1338                 }
1339                 if (write_userconfig(cmdcnf, cfg))
1340                         return (EXIT_SUCCESS);
1341                 err(EX_IOERR, "config update");
1342         }
1343
1344         if (userid)
1345                 id = pw_checkid(userid, UID_MAX);
1346         if (id < 0 && name == NULL)
1347                 errx(EX_DATAERR, "user name or id required");
1348
1349         if (name == NULL)
1350                 errx(EX_DATAERR, "login name required");
1351
1352         if (GETPWNAM(name) != NULL)
1353                 errx(EX_DATAERR, "login name `%s' already exists", name);
1354
1355         pwd = &fakeuser;
1356         pwd->pw_name = name;
1357         pwd->pw_class = cmdcnf->default_class ? cmdcnf->default_class : "";
1358         pwd->pw_uid = pw_uidpolicy(cmdcnf, id);
1359         pwd->pw_gid = pw_gidpolicy(cnf, grname, pwd->pw_name,
1360             (gid_t) pwd->pw_uid, dryrun);
1361         pwd->pw_change = cmdcnf->password_days;
1362         pwd->pw_expire = cmdcnf->expire_days;
1363         pwd->pw_dir = pw_homepolicy(cmdcnf, homedir, pwd->pw_name);
1364         pwd->pw_shell = pw_shellpolicy(cmdcnf);
1365         lc = login_getpwclass(pwd);
1366         if (lc == NULL || login_setcryptfmt(lc, "sha512", NULL) == NULL)
1367                 warn("setting crypt(3) format");
1368         login_close(lc);
1369         pwd->pw_passwd = pw_password(cmdcnf, pwd->pw_name, dryrun);
1370         if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
1371                 warnx("WARNING: new account `%s' has a uid of 0 "
1372                     "(superuser access!)", pwd->pw_name);
1373         if (gecos)
1374                 pwd->pw_gecos = gecos;
1375
1376         if (fd != -1)
1377                 pw_set_passwd(pwd, fd, precrypted, false);
1378
1379         if (dryrun)
1380                 return (print_user(pwd, pretty, false));
1381
1382         if ((rc = addpwent(pwd)) != 0) {
1383                 if (rc == -1)
1384                         errx(EX_IOERR, "user '%s' already exists",
1385                             pwd->pw_name);
1386                 else if (rc != 0)
1387                         err(EX_IOERR, "passwd file update");
1388         }
1389         if (nis && cmdcnf->nispasswd && *cmdcnf->nispasswd == '/') {
1390                 printf("%s\n", cmdcnf->nispasswd);
1391                 rc = addnispwent(cmdcnf->nispasswd, pwd);
1392                 if (rc == -1)
1393                         warnx("User '%s' already exists in NIS passwd",
1394                             pwd->pw_name);
1395                 else if (rc != 0)
1396                         warn("NIS passwd update");
1397                 /* NOTE: we treat NIS-only update errors as non-fatal */
1398         }
1399
1400         if (cmdcnf->groups != NULL) {
1401                 for (i = 0; i < cmdcnf->groups->sl_cur; i++) {
1402                         grp = GETGRNAM(cmdcnf->groups->sl_str[i]);
1403                         grp = gr_add(grp, pwd->pw_name);
1404                         /*
1405                          * grp can only be NULL in 2 cases:
1406                          * - the new member is already a member
1407                          * - a problem with memory occurs
1408                          * in both cases we want to skip now.
1409                          */
1410                         if (grp == NULL)
1411                                 continue;
1412                         chggrent(grp->gr_name, grp);
1413                         free(grp);
1414                 }
1415         }
1416
1417         pwd = GETPWNAM(name);
1418         if (pwd == NULL)
1419                 errx(EX_NOUSER, "user '%s' disappeared during update", name);
1420
1421         grp = GETGRGID(pwd->pw_gid);
1422         pw_log(cnf, M_ADD, W_USER, "%s(%ju):%s(%ju):%s:%s:%s",
1423                pwd->pw_name, (uintmax_t)pwd->pw_uid,
1424             grp ? grp->gr_name : "unknown",
1425                (uintmax_t)(grp ? grp->gr_gid : (uid_t)-1),
1426                pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell);
1427
1428         /*
1429          * let's touch and chown the user's mail file. This is not
1430          * strictly necessary under BSD with a 0755 maildir but it also
1431          * doesn't hurt anything to create the empty mailfile
1432          */
1433         if (PWALTDIR() != PWF_ALT) {
1434                 snprintf(path, sizeof(path), "%s/%s", _PATH_MAILDIR,
1435                     pwd->pw_name);
1436                 /* Preserve contents & mtime */
1437                 close(openat(conf.rootfd, path +1, O_RDWR | O_CREAT, 0600));
1438                 fchownat(conf.rootfd, path + 1, pwd->pw_uid, pwd->pw_gid,
1439                     AT_SYMLINK_NOFOLLOW);
1440         }
1441
1442         /*
1443          * Let's create and populate the user's home directory. Note
1444          * that this also `works' for editing users if -m is used, but
1445          * existing files will *not* be overwritten.
1446          */
1447         if (PWALTDIR() != PWF_ALT && createhome && pwd->pw_dir &&
1448             *pwd->pw_dir == '/' && pwd->pw_dir[1])
1449                 create_and_populate_homedir(cmdcnf, pwd, cmdcnf->dotdir,
1450                     cmdcnf->homemode, false);
1451
1452         if (!PWALTDIR() && cmdcnf->newmail && *cmdcnf->newmail &&
1453             (fp = fopen(cnf->newmail, "r")) != NULL) {
1454                 if ((pfp = popen(_PATH_SENDMAIL " -t", "w")) == NULL)
1455                         warn("sendmail");
1456                 else {
1457                         fprintf(pfp, "From: root\n" "To: %s\n"
1458                             "Subject: Welcome!\n\n", pwd->pw_name);
1459                         while (fgets(line, sizeof(line), fp) != NULL) {
1460                                 /* Do substitutions? */
1461                                 fputs(line, pfp);
1462                         }
1463                         pclose(pfp);
1464                         pw_log(cnf, M_ADD, W_USER, "%s(%ju) new user mail sent",
1465                             pwd->pw_name, (uintmax_t)pwd->pw_uid);
1466                 }
1467                 fclose(fp);
1468         }
1469
1470         if (nis && nis_update() == 0)
1471                 pw_log(cnf, M_ADD, W_USER, "NIS maps updated");
1472
1473         return (EXIT_SUCCESS);
1474 }
1475
1476 int
1477 pw_user_mod(int argc, char **argv, char *arg1)
1478 {
1479         struct userconf *cnf;
1480         struct passwd *pwd;
1481         struct group *grp;
1482         StringList *groups = NULL;
1483         char args[] = "C:qn:u:c:d:e:p:g:G:mM:l:k:s:w:L:h:H:NPYy:";
1484         const char *cfg;
1485         char *gecos, *homedir, *grname, *name, *newname, *walk, *skel, *shell;
1486         char *passwd, *class, *nispasswd;
1487         login_cap_t *lc;
1488         struct stat st;
1489         intmax_t id = -1;
1490         int ch, fd = -1;
1491         size_t i, j;
1492         bool quiet, createhome, pretty, dryrun, nis, edited, docreatehome;
1493         bool precrypted;
1494         mode_t homemode = 0;
1495         time_t expire_days, password_days, now;
1496
1497         expire_days = password_days = -1;
1498         gecos = homedir = grname = name = newname = skel = shell =NULL;
1499         passwd = NULL;
1500         class = nispasswd = NULL;
1501         quiet = createhome = pretty = dryrun = nis = precrypted = false;
1502         edited = docreatehome = false;
1503
1504         if (arg1 != NULL) {
1505                 if (arg1[strspn(arg1, "0123456789")] == '\0')
1506                         id = pw_checkid(arg1, UID_MAX);
1507                 else
1508                         name = arg1;
1509         }
1510
1511         while ((ch = getopt(argc, argv, args)) != -1) {
1512                 switch (ch) {
1513                 case 'C':
1514                         cfg = optarg;
1515                         break;
1516                 case 'q':
1517                         quiet = true;
1518                         break;
1519                 case 'n':
1520                         name = optarg;
1521                         break;
1522                 case 'u':
1523                         id = pw_checkid(optarg, UID_MAX);
1524                         break;
1525                 case 'c':
1526                         gecos = pw_checkname(optarg, 1);
1527                         break;
1528                 case 'd':
1529                         homedir = optarg;
1530                         break;
1531                 case 'e':
1532                         now = time(NULL);
1533                         expire_days = parse_date(now, optarg);
1534                         break;
1535                 case 'p':
1536                         now = time(NULL);
1537                         password_days = parse_date(now, optarg);
1538                         break;
1539                 case 'g':
1540                         group_from_name_or_id(optarg);
1541                         grname = optarg;
1542                         break;
1543                 case 'G':
1544                         split_groups(&groups, optarg);
1545                         break;
1546                 case 'm':
1547                         createhome = true;
1548                         break;
1549                 case 'M':
1550                         homemode = validate_mode(optarg);
1551                         break;
1552                 case 'l':
1553                         newname = optarg;
1554                         break;
1555                 case 'k':
1556                         walk = skel = optarg;
1557                         if (*walk == '/')
1558                                 walk++;
1559                         if (fstatat(conf.rootfd, walk, &st, 0) == -1)
1560                                 errx(EX_OSFILE, "skeleton `%s' does not "
1561                                     "exists", skel);
1562                         if (!S_ISDIR(st.st_mode))
1563                                 errx(EX_OSFILE, "skeleton `%s' is not a "
1564                                     "directory", skel);
1565                         break;
1566                 case 's':
1567                         shell = optarg;
1568                         break;
1569                 case 'w':
1570                         passwd = optarg;
1571                         break;
1572                 case 'L':
1573                         class = pw_checkname(optarg, 0);
1574                         break;
1575                 case 'H':
1576                         if (fd != -1)
1577                                 errx(EX_USAGE, "'-h' and '-H' are mutually "
1578                                     "exclusive options");
1579                         fd = pw_checkfd(optarg);
1580                         precrypted = true;
1581                         if (fd == '-')
1582                                 errx(EX_USAGE, "-H expects a file descriptor");
1583                         break;
1584                 case 'h':
1585                         if (fd != -1)
1586                                 errx(EX_USAGE, "'-h' and '-H' are mutually "
1587                                     "exclusive options");
1588                         fd = pw_checkfd(optarg);
1589                         break;
1590                 case 'N':
1591                         dryrun = true;
1592                         break;
1593                 case 'P':
1594                         pretty = true;
1595                         break;
1596                 case 'y':
1597                         nispasswd = optarg;
1598                         break;
1599                 case 'Y':
1600                         nis = true;
1601                         break;
1602                 }
1603         }
1604
1605         if (geteuid() != 0 && ! dryrun)
1606                 errx(EX_NOPERM, "you must be root");
1607
1608         if (quiet)
1609                 freopen(_PATH_DEVNULL, "w", stderr);
1610
1611         cnf = get_userconfig(cfg);
1612
1613         if (id < 0 && name == NULL)
1614                 errx(EX_DATAERR, "username or id required");
1615
1616         pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
1617         if (pwd == NULL) {
1618                 if (name == NULL)
1619                         errx(EX_NOUSER, "no such uid `%ju'",
1620                             (uintmax_t) id);
1621                 errx(EX_NOUSER, "no such user `%s'", name);
1622         }
1623
1624         if (name == NULL)
1625                 name = pwd->pw_name;
1626
1627         if (nis && nispasswd == NULL)
1628                 nispasswd = cnf->nispasswd;
1629
1630         if (PWF._altdir == PWF_REGULAR &&
1631             ((pwd->pw_fields & _PWF_SOURCE) != _PWF_FILES)) {
1632                 if ((pwd->pw_fields & _PWF_SOURCE) == _PWF_NIS) {
1633                         if (!nis && nispasswd && *nispasswd != '/')
1634                                 errx(EX_NOUSER, "Cannot modify NIS user `%s'",
1635                                     name);
1636                 } else {
1637                         errx(EX_NOUSER, "Cannot modify non local user `%s'",
1638                             name);
1639                 }
1640         }
1641
1642         if (newname) {
1643                 if (strcmp(pwd->pw_name, "root") == 0)
1644                         errx(EX_DATAERR, "can't rename `root' account");
1645                 if (strcmp(pwd->pw_name, newname) != 0) {
1646                         pwd->pw_name = pw_checkname(newname, 0);
1647                         edited = true;
1648                 }
1649         }
1650
1651         if (id > 0 && pwd->pw_uid != id) {
1652                 pwd->pw_uid = id;
1653                 edited = true;
1654                 if (pwd->pw_uid != 0 && strcmp(pwd->pw_name, "root") == 0)
1655                         errx(EX_DATAERR, "can't change uid of `root' account");
1656                 if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
1657                         warnx("WARNING: account `%s' will have a uid of 0 "
1658                             "(superuser access!)", pwd->pw_name);
1659         }
1660
1661         if (grname && pwd->pw_uid != 0) {
1662                 grp = GETGRNAM(grname);
1663                 if (grp == NULL)
1664                         grp = GETGRGID(pw_checkid(grname, GID_MAX));
1665                 if (grp->gr_gid != pwd->pw_gid) {
1666                         pwd->pw_gid = grp->gr_gid;
1667                         edited = true;
1668                 }
1669         }
1670
1671         if (password_days >= 0 && pwd->pw_change != password_days) {
1672                 pwd->pw_change = password_days;
1673                 edited = true;
1674         }
1675
1676         if (expire_days >= 0 && pwd->pw_expire != expire_days) {
1677                 pwd->pw_expire = expire_days;
1678                 edited = true;
1679         }
1680
1681         if (shell) {
1682                 shell = shell_path(cnf->shelldir, cnf->shells, shell);
1683                 if (shell == NULL)
1684                         shell = "";
1685                 if (strcmp(shell, pwd->pw_shell) != 0) {
1686                         pwd->pw_shell = shell;
1687                         edited = true;
1688                 }
1689         }
1690
1691         if (class && strcmp(pwd->pw_class, class) != 0) {
1692                 pwd->pw_class = class;
1693                 edited = true;
1694         }
1695
1696         if (homedir && strcmp(pwd->pw_dir, homedir) != 0) {
1697                 pwd->pw_dir = homedir;
1698                 edited = true;
1699                 if (fstatat(conf.rootfd, pwd->pw_dir, &st, 0) == -1) {
1700                         if (!createhome)
1701                                 warnx("WARNING: home `%s' does not exist",
1702                                     pwd->pw_dir);
1703                         else
1704                                 docreatehome = true;
1705                 } else if (!S_ISDIR(st.st_mode)) {
1706                         warnx("WARNING: home `%s' is not a directory",
1707                             pwd->pw_dir);
1708                 }
1709         }
1710
1711         if (passwd && conf.fd == -1) {
1712                 lc = login_getpwclass(pwd);
1713                 if (lc == NULL || login_setcryptfmt(lc, "sha512", NULL) == NULL)
1714                         warn("setting crypt(3) format");
1715                 login_close(lc);
1716                 cnf->default_password = boolean_val(passwd,
1717                     cnf->default_password);
1718                 pwd->pw_passwd = pw_password(cnf, pwd->pw_name, dryrun);
1719                 edited = true;
1720         }
1721
1722         if (gecos && strcmp(pwd->pw_gecos, gecos) != 0) {
1723                 pwd->pw_gecos = gecos;
1724                 edited = true;
1725         }
1726
1727         if (fd != -1)
1728                 edited = pw_set_passwd(pwd, fd, precrypted, true);
1729
1730         if (dryrun)
1731                 return (print_user(pwd, pretty, false));
1732
1733         if (edited) /* Only updated this if required */
1734                 perform_chgpwent(name, pwd, nis ? nispasswd : NULL);
1735         /* Now perform the needed changes concern groups */
1736         if (groups != NULL) {
1737                 /* Delete User from groups using old name */
1738                 SETGRENT();
1739                 while ((grp = GETGRENT()) != NULL) {
1740                         if (grp->gr_mem == NULL)
1741                                 continue;
1742                         for (i = 0; grp->gr_mem[i] != NULL; i++) {
1743                                 if (strcmp(grp->gr_mem[i] , name) != 0)
1744                                         continue;
1745                                 for (j = i; grp->gr_mem[j] != NULL ; j++)
1746                                         grp->gr_mem[j] = grp->gr_mem[j+1];
1747                                 chggrent(grp->gr_name, grp);
1748                                 break;
1749                         }
1750                 }
1751                 ENDGRENT();
1752                 /* Add the user to the needed groups */
1753                 for (i = 0; i < groups->sl_cur; i++) {
1754                         grp = GETGRNAM(groups->sl_str[i]);
1755                         grp = gr_add(grp, pwd->pw_name);
1756                         if (grp == NULL)
1757                                 continue;
1758                         chggrent(grp->gr_name, grp);
1759                         free(grp);
1760                 }
1761         }
1762         /* In case of rename we need to walk over the different groups */
1763         if (newname) {
1764                 SETGRENT();
1765                 while ((grp = GETGRENT()) != NULL) {
1766                         if (grp->gr_mem == NULL)
1767                                 continue;
1768                         for (i = 0; grp->gr_mem[i] != NULL; i++) {
1769                                 if (strcmp(grp->gr_mem[i], name) != 0)
1770                                         continue;
1771                                 grp->gr_mem[i] = newname;
1772                                 chggrent(grp->gr_name, grp);
1773                                 break;
1774                         }
1775                 }
1776         }
1777
1778         /* go get a current version of pwd */
1779         if (newname)
1780                 name = newname;
1781         pwd = GETPWNAM(name);
1782         if (pwd == NULL)
1783                 errx(EX_NOUSER, "user '%s' disappeared during update", name);
1784         grp = GETGRGID(pwd->pw_gid);
1785         pw_log(cnf, M_UPDATE, W_USER, "%s(%ju):%s(%ju):%s:%s:%s",
1786             pwd->pw_name, (uintmax_t)pwd->pw_uid,
1787             grp ? grp->gr_name : "unknown",
1788             (uintmax_t)(grp ? grp->gr_gid : (uid_t)-1),
1789             pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell);
1790
1791         /*
1792          * Let's create and populate the user's home directory. Note
1793          * that this also `works' for editing users if -m is used, but
1794          * existing files will *not* be overwritten.
1795          */
1796         if (PWALTDIR() != PWF_ALT && docreatehome && pwd->pw_dir &&
1797             *pwd->pw_dir == '/' && pwd->pw_dir[1]) {
1798                 if (!skel)
1799                         skel = cnf->dotdir;
1800                 if (homemode == 0)
1801                         homemode = cnf->homemode;
1802                 create_and_populate_homedir(cnf, pwd, skel, homemode, true);
1803         }
1804
1805         if (nis && nis_update() == 0)
1806                 pw_log(cnf, M_UPDATE, W_USER, "NIS maps updated");
1807
1808         return (EXIT_SUCCESS);
1809 }