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