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