]> git.cameronkatri.com Git - pw-darwin.git/blob - pw/pw_user.c
Revert "Set chpass to 755 too"
[pw-darwin.git] / pw / pw_user.c
1 /*-
2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
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 <crypt.h>
40 #include <ctype.h>
41 #include <dirent.h>
42 #include <err.h>
43 #include <errno.h>
44 #include <fcntl.h>
45 #include <grp.h>
46 #include <pwd.h>
47 #include <libutil.h>
48 #include <login_cap.h>
49 #include <paths.h>
50 #include <string.h>
51 #include <sysexits.h>
52 #include <termios.h>
53 #include <unistd.h>
54
55 #include "pw.h"
56 #include "bitmap.h"
57 #include "psdate.h"
58
59 #define LOGNAMESIZE (MAXLOGNAME-1)
60
61 static char locked_str[] = "*LOCKED*";
62
63 static struct passwd fakeuser = {
64 "nouser",
65 "*",
66 -1,
67 -1,
68 0,
69 "",
70 "User &",
71 "/nonexistent",
72 "/bin/sh",
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
486 static char const chars[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ./";
487
488 char *
489 pw_pwcrypt(char *password)
490 {
491 char *cryptpw;
492 static char buf[256];
493 size_t pwlen;
494
495 cryptpw = crypt(password, crypt_gensalt("$6$", 0, chars, strlen(chars)));
496 if (cryptpw == NULL)
497 errx(EX_CONFIG, "crypt(3) failure");
498 pwlen = strlcpy(buf, cryptpw, sizeof(buf));
499 assert(pwlen < sizeof(buf));
500 return (buf);
501 }
502
503 static char *
504 pw_password(struct userconf * cnf, char const * user, bool dryrun)
505 {
506 int i, l;
507 char pwbuf[32];
508
509 switch (cnf->default_password) {
510 case P_NONE: /* No password at all! */
511 return "";
512 case P_RANDOM: /* Random password */
513 l = (arc4random() % 8 + 8); /* 8 - 16 chars */
514 for (i = 0; i < l; i++)
515 pwbuf[i] = chars[arc4random_uniform(sizeof(chars)-1)];
516 pwbuf[i] = '\0';
517
518 /*
519 * We give this information back to the user
520 */
521 if (conf.fd == -1 && !dryrun) {
522 if (isatty(STDOUT_FILENO))
523 printf("Password for '%s' is: ", user);
524 printf("%s\n", pwbuf);
525 fflush(stdout);
526 }
527 break;
528 case P_YES: /* user's name */
529 strlcpy(pwbuf, user, sizeof(pwbuf));
530 break;
531 case P_NO: /* No login - default */
532 /* FALLTHROUGH */
533 default:
534 return "*";
535 }
536 return pw_pwcrypt(pwbuf);
537 }
538
539 static int
540 print_user(struct passwd * pwd, bool pretty, bool v7)
541 {
542 int j;
543 char *p;
544 struct group *grp = GETGRGID(pwd->pw_gid);
545 char uname[60] = "User &", office[60] = "[None]",
546 wphone[60] = "[None]", hphone[60] = "[None]";
547 char acexpire[32] = "[None]", pwexpire[32] = "[None]";
548 struct tm * tptr;
549
550 if (!pretty) {
551 p = v7 ? pw_make_v7(pwd) : pw_make(pwd);
552 printf("%s\n", p);
553 free(p);
554 return (EXIT_SUCCESS);
555 }
556
557 if ((p = strtok(pwd->pw_gecos, ",")) != NULL) {
558 strlcpy(uname, p, sizeof(uname));
559 if ((p = strtok(NULL, ",")) != NULL) {
560 strlcpy(office, p, sizeof(office));
561 if ((p = strtok(NULL, ",")) != NULL) {
562 strlcpy(wphone, p, sizeof(wphone));
563 if ((p = strtok(NULL, "")) != NULL) {
564 strlcpy(hphone, p, sizeof(hphone));
565 }
566 }
567 }
568 }
569 /*
570 * Handle '&' in gecos field
571 */
572 if ((p = strchr(uname, '&')) != NULL) {
573 int l = strlen(pwd->pw_name);
574 int m = strlen(p);
575
576 memmove(p + l, p + 1, m);
577 memmove(p, pwd->pw_name, l);
578 *p = (char) toupper((unsigned char)*p);
579 }
580 if (pwd->pw_expire > (time_t)0 && (tptr = localtime(&pwd->pw_expire)) != NULL)
581 strftime(acexpire, sizeof acexpire, "%c", tptr);
582 if (pwd->pw_change > (time_t)0 && (tptr = localtime(&pwd->pw_change)) != NULL)
583 strftime(pwexpire, sizeof pwexpire, "%c", tptr);
584 printf("Login Name: %-15s #%-12ju Group: %-15s #%ju\n"
585 " Full Name: %s\n"
586 " Home: %-26.26s Class: %s\n"
587 " Shell: %-26.26s Office: %s\n"
588 "Work Phone: %-26.26s Home Phone: %s\n"
589 "Acc Expire: %-26.26s Pwd Expire: %s\n",
590 pwd->pw_name, (uintmax_t)pwd->pw_uid,
591 grp ? grp->gr_name : "(invalid)", (uintmax_t)pwd->pw_gid,
592 uname, pwd->pw_dir, pwd->pw_class,
593 pwd->pw_shell, office, wphone, hphone,
594 acexpire, pwexpire);
595 SETGRENT();
596 j = 0;
597 while ((grp=GETGRENT()) != NULL) {
598 int i = 0;
599 if (grp->gr_mem != NULL) {
600 while (grp->gr_mem[i] != NULL) {
601 if (strcmp(grp->gr_mem[i], pwd->pw_name)==0) {
602 printf(j++ == 0 ? " Groups: %s" : ",%s", grp->gr_name);
603 break;
604 }
605 ++i;
606 }
607 }
608 }
609 ENDGRENT();
610 printf("%s", j ? "\n" : "");
611 return (EXIT_SUCCESS);
612 }
613
614 char *
615 pw_checkname(char *name, int gecos)
616 {
617 char showch[8];
618 const char *badchars, *ch, *showtype;
619 int reject;
620
621 ch = name;
622 reject = 0;
623 if (gecos) {
624 /* See if the name is valid as a gecos (comment) field. */
625 badchars = ":";
626 showtype = "gecos field";
627 } else {
628 /* See if the name is valid as a userid or group. */
629 badchars = " ,\t:+&#%$^()!@~*?<>=|\\/\"";
630 showtype = "userid/group name";
631 /* Userids and groups can not have a leading '-'. */
632 if (*ch == '-')
633 reject = 1;
634 }
635 if (!reject) {
636 while (*ch) {
637 if (strchr(badchars, *ch) != NULL ||
638 (!gecos && *ch < ' ') ||
639 *ch == 127) {
640 reject = 1;
641 break;
642 }
643 /* 8-bit characters are only allowed in GECOS fields */
644 if (!gecos && (*ch & 0x80)) {
645 reject = 1;
646 break;
647 }
648 ch++;
649 }
650 }
651 /*
652 * A `$' is allowed as the final character for userids and groups,
653 * mainly for the benefit of samba.
654 */
655 if (reject && !gecos) {
656 if (*ch == '$' && *(ch + 1) == '\0') {
657 reject = 0;
658 ch++;
659 }
660 }
661 if (reject) {
662 snprintf(showch, sizeof(showch), (*ch >= ' ' && *ch < 127)
663 ? "`%c'" : "0x%02x", *ch);
664 errx(EX_DATAERR, "invalid character %s at position %td in %s",
665 showch, (ch - name), showtype);
666 }
667 if (!gecos && (ch - name) > LOGNAMESIZE)
668 errx(EX_USAGE, "name too long `%s' (max is %d)", name,
669 LOGNAMESIZE);
670
671 return (name);
672 }
673
674 static void
675 rmat(uid_t uid)
676 {
677 DIR *d = opendir("/var/at/jobs");
678
679 if (d != NULL) {
680 struct dirent *e;
681
682 while ((e = readdir(d)) != NULL) {
683 struct stat st;
684
685 if (strncmp(e->d_name, ".lock", 5) != 0 &&
686 stat(e->d_name, &st) == 0 &&
687 !S_ISDIR(st.st_mode) &&
688 st.st_uid == uid) {
689 char tmp[MAXPATHLEN];
690
691 snprintf(tmp, sizeof(tmp), "/usr/bin/atrm %s",
692 e->d_name);
693 system(tmp);
694 }
695 }
696 closedir(d);
697 }
698 }
699
700 static void
701 rmopie(char const * name)
702 {
703 char tmp[1014];
704 FILE *fp;
705 size_t len;
706 long atofs;
707 int fd;
708
709 if ((fd = openat(conf.rootfd, "etc/opiekeys", O_RDWR)) == -1)
710 return;
711
712 fp = fdopen(fd, "r+");
713 len = strlen(name);
714
715 for (atofs = 0; fgets(tmp, sizeof(tmp), fp) != NULL && atofs >= 0;
716 atofs = ftell(fp)) {
717 if (strncmp(name, tmp, len) == 0 && tmp[len]==' ') {
718 /* Comment username out */
719 if (fseek(fp, atofs, SEEK_SET) == 0)
720 fwrite("#", 1, 1, fp);
721 break;
722 }
723 }
724 /*
725 * If we got an error of any sort, don't update!
726 */
727 fclose(fp);
728 }
729
730 int
731 pw_user_next(int argc, char **argv, char *name __unused)
732 {
733 struct userconf *cnf = NULL;
734 const char *cfg = NULL;
735 int ch;
736 bool quiet = false;
737 uid_t next;
738
739 while ((ch = getopt(argc, argv, "C:q")) != -1) {
740 switch (ch) {
741 case 'C':
742 cfg = optarg;
743 break;
744 case 'q':
745 quiet = true;
746 break;
747 }
748 }
749
750 if (quiet)
751 freopen(_PATH_DEVNULL, "w", stderr);
752
753 cnf = get_userconfig(cfg);
754
755 next = pw_uidpolicy(cnf, -1);
756
757 printf("%ju:", (uintmax_t)next);
758 pw_groupnext(cnf, quiet);
759
760 return (EXIT_SUCCESS);
761 }
762
763 int
764 pw_user_show(int argc, char **argv, char *arg1)
765 {
766 struct passwd *pwd = NULL;
767 char *name = NULL;
768 intmax_t id = -1;
769 int ch;
770 bool all = false;
771 bool pretty = false;
772 bool force = false;
773 bool v7 = false;
774 bool quiet = false;
775
776 if (arg1 != NULL) {
777 if (arg1[strspn(arg1, "0123456789")] == '\0')
778 id = pw_checkid(arg1, UID_MAX);
779 else
780 name = arg1;
781 }
782
783 while ((ch = getopt(argc, argv, "C:qn:u:FPa7")) != -1) {
784 switch (ch) {
785 case 'C':
786 /* ignore compatibility */
787 break;
788 case 'q':
789 quiet = true;
790 break;
791 case 'n':
792 name = optarg;
793 break;
794 case 'u':
795 id = pw_checkid(optarg, UID_MAX);
796 break;
797 case 'F':
798 force = true;
799 break;
800 case 'P':
801 pretty = true;
802 break;
803 case 'a':
804 all = true;
805 break;
806 case '7':
807 v7 = true;
808 break;
809 }
810 }
811
812 if (quiet)
813 freopen(_PATH_DEVNULL, "w", stderr);
814
815 if (all) {
816 SETPWENT();
817 while ((pwd = GETPWENT()) != NULL)
818 print_user(pwd, pretty, v7);
819 ENDPWENT();
820 return (EXIT_SUCCESS);
821 }
822
823 if (id < 0 && name == NULL)
824 errx(EX_DATAERR, "username or id required");
825
826 pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
827 if (pwd == NULL) {
828 if (force) {
829 pwd = &fakeuser;
830 } else {
831 if (name == NULL)
832 errx(EX_NOUSER, "no such uid `%ju'",
833 (uintmax_t) id);
834 errx(EX_NOUSER, "no such user `%s'", name);
835 }
836 }
837
838 return (print_user(pwd, pretty, v7));
839 }
840
841 int
842 pw_user_del(int argc, char **argv, char *arg1)
843 {
844 struct userconf *cnf = NULL;
845 struct passwd *pwd = NULL;
846 struct group *gr, *grp;
847 char *name = NULL;
848 char grname[MAXLOGNAME];
849 char *nispasswd = NULL;
850 char file[MAXPATHLEN];
851 char home[MAXPATHLEN];
852 const char *cfg = NULL;
853 struct stat st;
854 intmax_t id = -1;
855 int ch, rc;
856 bool nis = false;
857 bool deletehome = false;
858 bool quiet = false;
859
860 if (arg1 != NULL) {
861 if (arg1[strspn(arg1, "0123456789")] == '\0')
862 id = pw_checkid(arg1, UID_MAX);
863 else
864 name = arg1;
865 }
866
867 while ((ch = getopt(argc, argv, "C:qn:u:rYy:")) != -1) {
868 switch (ch) {
869 case 'C':
870 cfg = optarg;
871 break;
872 case 'q':
873 quiet = true;
874 break;
875 case 'n':
876 name = optarg;
877 break;
878 case 'u':
879 id = pw_checkid(optarg, UID_MAX);
880 break;
881 case 'r':
882 deletehome = true;
883 break;
884 case 'y':
885 nispasswd = optarg;
886 break;
887 case 'Y':
888 nis = true;
889 break;
890 }
891 }
892
893 if (quiet)
894 freopen(_PATH_DEVNULL, "w", stderr);
895
896 if (id < 0 && name == NULL)
897 errx(EX_DATAERR, "username or id required");
898
899 cnf = get_userconfig(cfg);
900
901 if (nispasswd == NULL)
902 nispasswd = cnf->nispasswd;
903
904 pwd = (name != NULL) ? GETPWNAM(pw_checkname(name, 0)) : GETPWUID(id);
905 if (pwd == NULL) {
906 if (name == NULL)
907 errx(EX_NOUSER, "no such uid `%ju'", (uintmax_t) id);
908 errx(EX_NOUSER, "no such user `%s'", name);
909 }
910
911 id = pwd->pw_uid;
912 if (name == NULL)
913 name = pwd->pw_name;
914
915 char *system_users[30] = {"nobody", "root", "mobile", "daemon", "_ftp", "_networkd", "_wireless", "_installd", "_neagent", "_ifccd", "_securityd", "_mdnsresponder", "_sshd", "_unknown", "_distnote", "_astris", "_ondemand", "_findmydevice", "_datadetectors", "_captiveagent", "_analyticsd", "_timed", "_gpsd", "_reportmemoryexception", "_diskimagesiod", "_logd", "_iconservices", "_fud", "_knowledgegraphd", "_coreml"};
916 for (int i = 0; i < 30; i++) {
917 if (strcmp(pwd->pw_name, system_users[i]) == 0)
918 errx(EX_DATAERR, "cannot remove user '%s'", system_users[i]);
919 }
920
921 /* Remove opie record from /etc/opiekeys */
922 if (PWALTDIR() != PWF_ALT)
923 rmopie(pwd->pw_name);
924
925 if (!PWALTDIR()) {
926 /* Remove crontabs */
927 snprintf(file, sizeof(file), "/var/cron/tabs/%s", pwd->pw_name);
928 if (access(file, F_OK) == 0) {
929 snprintf(file, sizeof(file), "crontab -u %s -r",
930 pwd->pw_name);
931 system(file);
932 }
933 }
934
935 /*
936 * Save these for later, since contents of pwd may be
937 * invalidated by deletion
938 */
939 snprintf(file, sizeof(file), "%s/%s", _PATH_MAILDIR, pwd->pw_name);
940 strlcpy(home, pwd->pw_dir, sizeof(home));
941 gr = GETGRGID(pwd->pw_gid);
942 if (gr != NULL)
943 strlcpy(grname, gr->gr_name, LOGNAMESIZE);
944 else
945 grname[0] = '\0';
946
947 rc = delpwent(pwd);
948 if (rc == -1)
949 err(EX_IOERR, "user '%s' does not exist", pwd->pw_name);
950 else if (rc != 0)
951 err(EX_IOERR, "passwd update");
952
953 if (nis && nispasswd && *nispasswd=='/') {
954 rc = delnispwent(nispasswd, name);
955 if (rc == -1)
956 warnx("WARNING: user '%s' does not exist in NIS passwd",
957 pwd->pw_name);
958 else if (rc != 0)
959 warn("WARNING: NIS passwd update");
960 }
961
962 grp = GETGRNAM(name);
963 if (grp != NULL &&
964 (grp->gr_mem == NULL || *grp->gr_mem == NULL) &&
965 strcmp(name, grname) == 0)
966 delgrent(GETGRNAM(name));
967 SETGRENT();
968 while ((grp = GETGRENT()) != NULL) {
969 int i, j;
970 char group[MAXLOGNAME];
971 if (grp->gr_mem == NULL)
972 continue;
973
974 for (i = 0; grp->gr_mem[i] != NULL; i++) {
975 if (strcmp(grp->gr_mem[i], name) != 0)
976 continue;
977
978 for (j = i; grp->gr_mem[j] != NULL; j++)
979 grp->gr_mem[j] = grp->gr_mem[j+1];
980 strlcpy(group, grp->gr_name, MAXLOGNAME);
981 chggrent(group, grp);
982 }
983 }
984 ENDGRENT();
985
986 pw_log(cnf, M_DELETE, W_USER, "%s(%ju) account removed", name,
987 (uintmax_t)id);
988
989 /* Remove mail file */
990 if (PWALTDIR() != PWF_ALT)
991 unlinkat(conf.rootfd, file + 1, 0);
992
993 /* Remove at jobs */
994 if (!PWALTDIR() && getpwuid(id) == NULL)
995 rmat(id);
996
997 /* Remove home directory and contents */
998 if (PWALTDIR() != PWF_ALT && deletehome && *home == '/' &&
999 fstatat(conf.rootfd, home + 1, &st, 0) != -1) {
1000 rm_r(conf.rootfd, home, id);
1001 pw_log(cnf, M_DELETE, W_USER, "%s(%ju) home '%s' %s"
1002 "removed", name, (uintmax_t)id, home,
1003 fstatat(conf.rootfd, home + 1, &st, 0) == -1 ? "" : "not "
1004 "completely ");
1005 }
1006
1007 return (EXIT_SUCCESS);
1008 }
1009
1010 int
1011 pw_user_lock(int argc, char **argv, char *arg1)
1012 {
1013 int ch;
1014
1015 while ((ch = getopt(argc, argv, "Cq")) != -1) {
1016 switch (ch) {
1017 case 'C':
1018 case 'q':
1019 /* compatibility */
1020 break;
1021 }
1022 }
1023
1024 return (pw_userlock(arg1, M_LOCK));
1025 }
1026
1027 int
1028 pw_user_unlock(int argc, char **argv, char *arg1)
1029 {
1030 int ch;
1031
1032 while ((ch = getopt(argc, argv, "Cq")) != -1) {
1033 switch (ch) {
1034 case 'C':
1035 case 'q':
1036 /* compatibility */
1037 break;
1038 }
1039 }
1040
1041 return (pw_userlock(arg1, M_UNLOCK));
1042 }
1043
1044 static struct group *
1045 group_from_name_or_id(char *name)
1046 {
1047 const char *errstr = NULL;
1048 struct group *grp;
1049 uintmax_t id;
1050
1051 if ((grp = GETGRNAM(name)) == NULL) {
1052 id = strtounum(name, 0, GID_MAX, &errstr);
1053 if (errstr)
1054 errx(EX_NOUSER, "group `%s' does not exist", name);
1055 grp = GETGRGID(id);
1056 if (grp == NULL)
1057 errx(EX_NOUSER, "group `%s' does not exist", name);
1058 }
1059
1060 return (grp);
1061 }
1062
1063 static void
1064 split_groups(StringList **groups, char *groupsstr)
1065 {
1066 struct group *grp;
1067 char *p;
1068 char tok[] = ", \t";
1069
1070 if (*groups == NULL)
1071 *groups = sl_init();
1072 for (p = strtok(groupsstr, tok); p != NULL; p = strtok(NULL, tok)) {
1073 grp = group_from_name_or_id(p);
1074 sl_add(*groups, newstr(grp->gr_name));
1075 }
1076 }
1077
1078 static void
1079 validate_grname(struct userconf *cnf, char *group)
1080 {
1081 struct group *grp;
1082
1083 if (group == NULL || *group == '\0') {
1084 cnf->default_group = "";
1085 return;
1086 }
1087 grp = group_from_name_or_id(group);
1088 cnf->default_group = newstr(grp->gr_name);
1089 }
1090
1091 static mode_t
1092 validate_mode(char *mode)
1093 {
1094 mode_t m;
1095 void *set;
1096
1097 if ((set = setmode(mode)) == NULL)
1098 errx(EX_DATAERR, "invalid directory creation mode '%s'", mode);
1099
1100 m = getmode(set, _DEF_DIRMODE);
1101 free(set);
1102 return (m);
1103 }
1104
1105 static long
1106 validate_expire(char *str, int opt)
1107 {
1108 if (!numerics(str))
1109 errx(EX_DATAERR, "-%c argument must be numeric "
1110 "when setting defaults: %s", (char)opt, str);
1111 return strtol(str, NULL, 0);
1112 }
1113
1114 static void
1115 mix_config(struct userconf *cmdcnf, struct userconf *cfg)
1116 {
1117
1118 if (cmdcnf->default_password < 0)
1119 cmdcnf->default_password = cfg->default_password;
1120 if (cmdcnf->reuse_uids == 0)
1121 cmdcnf->reuse_uids = cfg->reuse_uids;
1122 if (cmdcnf->reuse_gids == 0)
1123 cmdcnf->reuse_gids = cfg->reuse_gids;
1124 if (cmdcnf->nispasswd == NULL)
1125 cmdcnf->nispasswd = cfg->nispasswd;
1126 if (cmdcnf->dotdir == NULL)
1127 cmdcnf->dotdir = cfg->dotdir;
1128 if (cmdcnf->newmail == NULL)
1129 cmdcnf->newmail = cfg->newmail;
1130 if (cmdcnf->logfile == NULL)
1131 cmdcnf->logfile = cfg->logfile;
1132 if (cmdcnf->home == NULL)
1133 cmdcnf->home = cfg->home;
1134 if (cmdcnf->homemode == 0)
1135 cmdcnf->homemode = cfg->homemode;
1136 if (cmdcnf->shelldir == NULL)
1137 cmdcnf->shelldir = cfg->shelldir;
1138 if (cmdcnf->shells == NULL)
1139 cmdcnf->shells = cfg->shells;
1140 if (cmdcnf->shell_default == NULL)
1141 cmdcnf->shell_default = cfg->shell_default;
1142 if (cmdcnf->default_group == NULL)
1143 cmdcnf->default_group = cfg->default_group;
1144 if (cmdcnf->groups == NULL)
1145 cmdcnf->groups = cfg->groups;
1146 if (cmdcnf->default_class == NULL)
1147 cmdcnf->default_class = cfg->default_class;
1148 if (cmdcnf->min_uid == 0)
1149 cmdcnf->min_uid = cfg->min_uid;
1150 if (cmdcnf->max_uid == 0)
1151 cmdcnf->max_uid = cfg->max_uid;
1152 if (cmdcnf->min_gid == 0)
1153 cmdcnf->min_gid = cfg->min_gid;
1154 if (cmdcnf->max_gid == 0)
1155 cmdcnf->max_gid = cfg->max_gid;
1156 if (cmdcnf->expire_days < 0)
1157 cmdcnf->expire_days = cfg->expire_days;
1158 if (cmdcnf->password_days < 0)
1159 cmdcnf->password_days = cfg->password_days;
1160 }
1161
1162 int
1163 pw_user_add(int argc, char **argv, char *arg1)
1164 {
1165 struct userconf *cnf, *cmdcnf;
1166 struct passwd *pwd;
1167 struct group *grp;
1168 struct stat st;
1169 char args[] = "C:qn:u:c:d:e:p:g:G:mM:k:s:oL:i:w:h:H:Db:NPy:Y";
1170 char line[_PASSWORD_LEN+1], path[MAXPATHLEN];
1171 char *gecos, *homedir, *skel, *walk, *userid, *groupid, *grname;
1172 char *default_passwd, *name, *p;
1173 const char *cfg = NULL;
1174 login_cap_t *lc;
1175 FILE *pfp, *fp;
1176 intmax_t id = -1;
1177 time_t now;
1178 int rc, ch, fd = -1;
1179 size_t i;
1180 bool dryrun, nis, pretty, quiet, createhome, precrypted, genconf;
1181
1182 dryrun = nis = pretty = quiet = createhome = precrypted = false;
1183 genconf = false;
1184 gecos = homedir = skel = userid = groupid = default_passwd = NULL;
1185 grname = name = NULL;
1186
1187 if ((cmdcnf = calloc(1, sizeof(struct userconf))) == NULL)
1188 err(EXIT_FAILURE, "calloc()");
1189
1190 cmdcnf->default_password = cmdcnf->expire_days = cmdcnf->password_days = -1;
1191 now = time(NULL);
1192
1193 if (arg1 != NULL) {
1194 if (arg1[strspn(arg1, "0123456789")] == '\0')
1195 id = pw_checkid(arg1, UID_MAX);
1196 else
1197 name = pw_checkname(arg1, 0);
1198 }
1199
1200 while ((ch = getopt(argc, argv, args)) != -1) {
1201 switch (ch) {
1202 case 'C':
1203 cfg = optarg;
1204 break;
1205 case 'q':
1206 quiet = true;
1207 break;
1208 case 'n':
1209 name = pw_checkname(optarg, 0);
1210 break;
1211 case 'u':
1212 userid = optarg;
1213 break;
1214 case 'c':
1215 gecos = pw_checkname(optarg, 1);
1216 break;
1217 case 'd':
1218 homedir = optarg;
1219 break;
1220 case 'e':
1221 if (genconf)
1222 cmdcnf->expire_days = validate_expire(optarg, ch);
1223 else
1224 cmdcnf->expire_days = parse_date(now, optarg);
1225 break;
1226 case 'p':
1227 if (genconf)
1228 cmdcnf->password_days = validate_expire(optarg, ch);
1229 else
1230 cmdcnf->password_days = parse_date(now, optarg);
1231 break;
1232 case 'g':
1233 validate_grname(cmdcnf, optarg);
1234 grname = optarg;
1235 break;
1236 case 'G':
1237 split_groups(&cmdcnf->groups, optarg);
1238 break;
1239 case 'm':
1240 createhome = true;
1241 break;
1242 case 'M':
1243 cmdcnf->homemode = validate_mode(optarg);
1244 break;
1245 case 'k':
1246 walk = skel = optarg;
1247 if (*walk == '/')
1248 walk++;
1249 if (fstatat(conf.rootfd, walk, &st, 0) == -1)
1250 errx(EX_OSFILE, "skeleton `%s' does not "
1251 "exists", skel);
1252 if (!S_ISDIR(st.st_mode))
1253 errx(EX_OSFILE, "skeleton `%s' is not a "
1254 "directory", skel);
1255 cmdcnf->dotdir = skel;
1256 break;
1257 case 's':
1258 cmdcnf->shell_default = optarg;
1259 break;
1260 case 'o':
1261 conf.checkduplicate = false;
1262 break;
1263 case 'L':
1264 cmdcnf->default_class = pw_checkname(optarg, 0);
1265 break;
1266 case 'i':
1267 groupid = optarg;
1268 break;
1269 case 'w':
1270 default_passwd = optarg;
1271 break;
1272 case 'H':
1273 if (fd != -1)
1274 errx(EX_USAGE, "'-h' and '-H' are mutually "
1275 "exclusive options");
1276 fd = pw_checkfd(optarg);
1277 precrypted = true;
1278 if (fd == '-')
1279 errx(EX_USAGE, "-H expects a file descriptor");
1280 break;
1281 case 'h':
1282 if (fd != -1)
1283 errx(EX_USAGE, "'-h' and '-H' are mutually "
1284 "exclusive options");
1285 fd = pw_checkfd(optarg);
1286 break;
1287 case 'D':
1288 genconf = true;
1289 break;
1290 case 'b':
1291 cmdcnf->home = optarg;
1292 break;
1293 case 'N':
1294 dryrun = true;
1295 break;
1296 case 'P':
1297 pretty = true;
1298 break;
1299 case 'y':
1300 cmdcnf->nispasswd = optarg;
1301 break;
1302 case 'Y':
1303 nis = true;
1304 break;
1305 }
1306 }
1307
1308 if (geteuid() != 0 && ! dryrun)
1309 errx(EX_NOPERM, "you must be root");
1310
1311 if (quiet)
1312 freopen(_PATH_DEVNULL, "w", stderr);
1313
1314 cnf = get_userconfig(cfg);
1315
1316 mix_config(cmdcnf, cnf);
1317 if (default_passwd)
1318 cmdcnf->default_password = passwd_val(default_passwd,
1319 cnf->default_password);
1320 if (genconf) {
1321 if (name != NULL)
1322 errx(EX_DATAERR, "can't combine `-D' with `-n name'");
1323 if (userid != NULL) {
1324 if ((p = strtok(userid, ", \t")) != NULL)
1325 cmdcnf->min_uid = pw_checkid(p, UID_MAX);
1326 if (cmdcnf->min_uid == 0)
1327 cmdcnf->min_uid = 1000;
1328 if ((p = strtok(NULL, " ,\t")) != NULL)
1329 cmdcnf->max_uid = pw_checkid(p, UID_MAX);
1330 if (cmdcnf->max_uid == 0)
1331 cmdcnf->max_uid = 32000;
1332 }
1333 if (groupid != NULL) {
1334 if ((p = strtok(groupid, ", \t")) != NULL)
1335 cmdcnf->min_gid = pw_checkid(p, GID_MAX);
1336 if (cmdcnf->min_gid == 0)
1337 cmdcnf->min_gid = 1000;
1338 if ((p = strtok(NULL, " ,\t")) != NULL)
1339 cmdcnf->max_gid = pw_checkid(p, GID_MAX);
1340 if (cmdcnf->max_gid == 0)
1341 cmdcnf->max_gid = 32000;
1342 }
1343 if (write_userconfig(cmdcnf, cfg))
1344 return (EXIT_SUCCESS);
1345 err(EX_IOERR, "config update");
1346 }
1347
1348 if (userid)
1349 id = pw_checkid(userid, UID_MAX);
1350 if (id < 0 && name == NULL)
1351 errx(EX_DATAERR, "user name or id required");
1352
1353 if (name == NULL)
1354 errx(EX_DATAERR, "login name required");
1355
1356 if (GETPWNAM(name) != NULL)
1357 errx(EX_DATAERR, "login name `%s' already exists", name);
1358
1359 if (!grname)
1360 grname = cmdcnf->default_group;
1361
1362 pwd = &fakeuser;
1363 pwd->pw_name = name;
1364 pwd->pw_class = cmdcnf->default_class ? cmdcnf->default_class : "";
1365 pwd->pw_uid = pw_uidpolicy(cmdcnf, id);
1366 pwd->pw_gid = pw_gidpolicy(cnf, grname, pwd->pw_name,
1367 (gid_t) pwd->pw_uid, dryrun);
1368
1369 split_groups(&cmdcnf->groups, grname);
1370
1371 /* cmdcnf->password_days and cmdcnf->expire_days hold unixtime here */
1372 if (cmdcnf->password_days > 0)
1373 pwd->pw_change = cmdcnf->password_days;
1374 if (cmdcnf->expire_days > 0)
1375 pwd->pw_expire = cmdcnf->expire_days;
1376
1377 pwd->pw_dir = pw_homepolicy(cmdcnf, homedir, pwd->pw_name);
1378 pwd->pw_shell = pw_shellpolicy(cmdcnf);
1379 lc = login_getpwclass(pwd);
1380 if (lc == NULL || login_setcryptfmt(lc, "sha512", NULL) == NULL)
1381 warn("setting crypt(3) format");
1382 login_close(lc);
1383 pwd->pw_passwd = pw_password(cmdcnf, pwd->pw_name, dryrun);
1384 if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
1385 warnx("WARNING: new account `%s' has a uid of 0 "
1386 "(superuser access!)", pwd->pw_name);
1387 if (gecos)
1388 pwd->pw_gecos = gecos;
1389
1390 if (fd != -1)
1391 pw_set_passwd(pwd, fd, precrypted, false);
1392
1393 if (dryrun)
1394 return (print_user(pwd, pretty, false));
1395
1396 if ((rc = addpwent(pwd)) != 0) {
1397 if (rc == -1)
1398 errx(EX_IOERR, "user '%s' already exists",
1399 pwd->pw_name);
1400 else if (rc != 0)
1401 err(EX_IOERR, "passwd file update");
1402 }
1403 if (nis && cmdcnf->nispasswd && *cmdcnf->nispasswd == '/') {
1404 printf("%s\n", cmdcnf->nispasswd);
1405 rc = addnispwent(cmdcnf->nispasswd, pwd);
1406 if (rc == -1)
1407 warnx("User '%s' already exists in NIS passwd",
1408 pwd->pw_name);
1409 else if (rc != 0)
1410 warn("NIS passwd update");
1411 /* NOTE: we treat NIS-only update errors as non-fatal */
1412 }
1413
1414 if (cmdcnf->groups != NULL) {
1415 for (i = 0; i < cmdcnf->groups->sl_cur; i++) {
1416 grp = GETGRNAM(cmdcnf->groups->sl_str[i]);
1417 grp = gr_add(grp, pwd->pw_name);
1418 /*
1419 * grp can only be NULL in 2 cases:
1420 * - the new member is already a member
1421 * - a problem with memory occurs
1422 * in both cases we want to skip now.
1423 */
1424 if (grp == NULL)
1425 continue;
1426 chggrent(grp->gr_name, grp);
1427 free(grp);
1428 }
1429 }
1430
1431 pwd = GETPWNAM(name);
1432 if (pwd == NULL)
1433 errx(EX_NOUSER, "user '%s' disappeared during update", name);
1434
1435 grp = GETGRGID(pwd->pw_gid);
1436 pw_log(cnf, M_ADD, W_USER, "%s(%ju):%s(%ju):%s:%s:%s",
1437 pwd->pw_name, (uintmax_t)pwd->pw_uid,
1438 grp ? grp->gr_name : "unknown",
1439 (uintmax_t)(grp ? grp->gr_gid : (uid_t)-1),
1440 pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell);
1441
1442 /*
1443 * let's touch and chown the user's mail file. This is not
1444 * strictly necessary under BSD with a 0755 maildir but it also
1445 * doesn't hurt anything to create the empty mailfile
1446 */
1447 if (PWALTDIR() != PWF_ALT) {
1448 snprintf(path, sizeof(path), "%s/%s", _PATH_MAILDIR,
1449 pwd->pw_name);
1450 /* Preserve contents & mtime */
1451 close(openat(conf.rootfd, path +1, O_RDWR | O_CREAT, 0600));
1452 fchownat(conf.rootfd, path + 1, pwd->pw_uid, pwd->pw_gid,
1453 AT_SYMLINK_NOFOLLOW);
1454 }
1455
1456 /*
1457 * Let's create and populate the user's home directory. Note
1458 * that this also `works' for editing users if -m is used, but
1459 * existing files will *not* be overwritten.
1460 */
1461 if (PWALTDIR() != PWF_ALT && createhome && pwd->pw_dir &&
1462 *pwd->pw_dir == '/' && pwd->pw_dir[1])
1463 create_and_populate_homedir(cmdcnf, pwd, cmdcnf->dotdir,
1464 cmdcnf->homemode, false);
1465
1466 if (!PWALTDIR() && cmdcnf->newmail && *cmdcnf->newmail &&
1467 (fp = fopen(cnf->newmail, "r")) != NULL) {
1468 if ((pfp = popen(_PATH_SENDMAIL " -t", "w")) == NULL)
1469 warn("sendmail");
1470 else {
1471 fprintf(pfp, "From: root\n" "To: %s\n"
1472 "Subject: Welcome!\n\n", pwd->pw_name);
1473 while (fgets(line, sizeof(line), fp) != NULL) {
1474 /* Do substitutions? */
1475 fputs(line, pfp);
1476 }
1477 pclose(pfp);
1478 pw_log(cnf, M_ADD, W_USER, "%s(%ju) new user mail sent",
1479 pwd->pw_name, (uintmax_t)pwd->pw_uid);
1480 }
1481 fclose(fp);
1482 }
1483
1484 if (nis && nis_update() == 0)
1485 pw_log(cnf, M_ADD, W_USER, "NIS maps updated");
1486
1487 return (EXIT_SUCCESS);
1488 }
1489
1490 int
1491 pw_user_mod(int argc, char **argv, char *arg1)
1492 {
1493 struct userconf *cnf;
1494 struct passwd *pwd;
1495 struct group *grp;
1496 StringList *groups = NULL;
1497 char args[] = "C:qn:u:c:d:e:p:g:G:mM:l:k:s:w:L:h:H:NPYy:";
1498 const char *cfg = NULL;
1499 char *gecos, *homedir, *grname, *name, *newname, *walk, *skel, *shell;
1500 char *passwd, *class, *nispasswd;
1501 login_cap_t *lc;
1502 struct stat st;
1503 intmax_t id = -1;
1504 int ch, fd = -1;
1505 size_t i, j;
1506 bool quiet, createhome, pretty, dryrun, nis, edited;
1507 bool precrypted;
1508 mode_t homemode = 0;
1509 time_t expire_time, password_time, now;
1510
1511 expire_time = password_time = -1;
1512 gecos = homedir = grname = name = newname = skel = shell =NULL;
1513 passwd = NULL;
1514 class = nispasswd = NULL;
1515 quiet = createhome = pretty = dryrun = nis = precrypted = false;
1516 edited = false;
1517 now = time(NULL);
1518
1519 if (arg1 != NULL) {
1520 if (arg1[strspn(arg1, "0123456789")] == '\0')
1521 id = pw_checkid(arg1, UID_MAX);
1522 else
1523 name = arg1;
1524 }
1525
1526 while ((ch = getopt(argc, argv, args)) != -1) {
1527 switch (ch) {
1528 case 'C':
1529 cfg = optarg;
1530 break;
1531 case 'q':
1532 quiet = true;
1533 break;
1534 case 'n':
1535 name = optarg;
1536 break;
1537 case 'u':
1538 id = pw_checkid(optarg, UID_MAX);
1539 break;
1540 case 'c':
1541 gecos = pw_checkname(optarg, 1);
1542 break;
1543 case 'd':
1544 homedir = optarg;
1545 break;
1546 case 'e':
1547 expire_time = parse_date(now, optarg);
1548 break;
1549 case 'p':
1550 password_time = 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 (newname) {
1644 if (strcmp(pwd->pw_name, "root") == 0)
1645 errx(EX_DATAERR, "can't rename `root' account");
1646 if (strcmp(pwd->pw_name, newname) != 0) {
1647 pwd->pw_name = pw_checkname(newname, 0);
1648 edited = true;
1649 }
1650 }
1651
1652 if (id >= 0 && pwd->pw_uid != id) {
1653 pwd->pw_uid = id;
1654 edited = true;
1655 if (pwd->pw_uid != 0 && strcmp(pwd->pw_name, "root") == 0)
1656 errx(EX_DATAERR, "can't change uid of `root' account");
1657 if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
1658 warnx("WARNING: account `%s' will have a uid of 0 "
1659 "(superuser access!)", pwd->pw_name);
1660 }
1661
1662 if (grname && pwd->pw_uid != 0) {
1663 grp = GETGRNAM(grname);
1664 if (grp == NULL)
1665 grp = GETGRGID(pw_checkid(grname, GID_MAX));
1666 if (grp->gr_gid != pwd->pw_gid) {
1667 pwd->pw_gid = grp->gr_gid;
1668 edited = true;
1669 }
1670 }
1671
1672
1673 if (password_time >= 0 && pwd->pw_change != password_time) {
1674 pwd->pw_change = password_time;
1675 edited = true;
1676 }
1677
1678 if (expire_time >= 0 && pwd->pw_expire != expire_time) {
1679 pwd->pw_expire = expire_time;
1680 edited = true;
1681 }
1682
1683 if (shell) {
1684 shell = shell_path(cnf->shelldir, cnf->shells, shell);
1685 if (shell == NULL)
1686 shell = "";
1687 if (strcmp(shell, pwd->pw_shell) != 0) {
1688 pwd->pw_shell = shell;
1689 edited = true;
1690 }
1691 }
1692
1693 if (class && strcmp(pwd->pw_class, class) != 0) {
1694 pwd->pw_class = class;
1695 edited = true;
1696 }
1697
1698 if (homedir && strcmp(pwd->pw_dir, homedir) != 0) {
1699 pwd->pw_dir = homedir;
1700 edited = true;
1701 if (fstatat(conf.rootfd, pwd->pw_dir, &st, 0) == -1) {
1702 if (!createhome)
1703 warnx("WARNING: home `%s' does not exist",
1704 pwd->pw_dir);
1705 } else if (!S_ISDIR(st.st_mode)) {
1706 warnx("WARNING: home `%s' is not a directory",
1707 pwd->pw_dir);
1708 }
1709 }
1710
1711 if (passwd && conf.fd == -1) {
1712 lc = login_getpwclass(pwd);
1713 if (lc == NULL || login_setcryptfmt(lc, "sha512", NULL) == NULL)
1714 warn("setting crypt(3) format");
1715 login_close(lc);
1716 cnf->default_password = passwd_val(passwd,
1717 cnf->default_password);
1718 pwd->pw_passwd = pw_password(cnf, pwd->pw_name, dryrun);
1719 edited = true;
1720 }
1721
1722 if (gecos && strcmp(pwd->pw_gecos, gecos) != 0) {
1723 pwd->pw_gecos = gecos;
1724 edited = true;
1725 }
1726
1727 if (fd != -1)
1728 edited = pw_set_passwd(pwd, fd, precrypted, true);
1729
1730 if (dryrun)
1731 return (print_user(pwd, pretty, false));
1732
1733 if (edited) /* Only updated this if required */
1734 perform_chgpwent(name, pwd, nis ? nispasswd : NULL);
1735 /* Now perform the needed changes concern groups */
1736 if (groups != NULL) {
1737 /* Delete User from groups using old name */
1738 SETGRENT();
1739 while ((grp = GETGRENT()) != NULL) {
1740 if (grp->gr_mem == NULL)
1741 continue;
1742 for (i = 0; grp->gr_mem[i] != NULL; i++) {
1743 if (strcmp(grp->gr_mem[i] , name) != 0)
1744 continue;
1745 for (j = i; grp->gr_mem[j] != NULL ; j++)
1746 grp->gr_mem[j] = grp->gr_mem[j+1];
1747 chggrent(grp->gr_name, grp);
1748 break;
1749 }
1750 }
1751 ENDGRENT();
1752 /* Add the user to the needed groups */
1753 for (i = 0; i < groups->sl_cur; i++) {
1754 grp = GETGRNAM(groups->sl_str[i]);
1755 grp = gr_add(grp, pwd->pw_name);
1756 if (grp == NULL)
1757 continue;
1758 chggrent(grp->gr_name, grp);
1759 free(grp);
1760 }
1761 }
1762 /* In case of rename we need to walk over the different groups */
1763 if (newname) {
1764 SETGRENT();
1765 while ((grp = GETGRENT()) != NULL) {
1766 if (grp->gr_mem == NULL)
1767 continue;
1768 for (i = 0; grp->gr_mem[i] != NULL; i++) {
1769 if (strcmp(grp->gr_mem[i], name) != 0)
1770 continue;
1771 grp->gr_mem[i] = newname;
1772 chggrent(grp->gr_name, grp);
1773 break;
1774 }
1775 }
1776 }
1777
1778 /* go get a current version of pwd */
1779 if (newname)
1780 name = newname;
1781 pwd = GETPWNAM(name);
1782 if (pwd == NULL)
1783 errx(EX_NOUSER, "user '%s' disappeared during update", name);
1784 grp = GETGRGID(pwd->pw_gid);
1785 pw_log(cnf, M_UPDATE, W_USER, "%s(%ju):%s(%ju):%s:%s:%s",
1786 pwd->pw_name, (uintmax_t)pwd->pw_uid,
1787 grp ? grp->gr_name : "unknown",
1788 (uintmax_t)(grp ? grp->gr_gid : (uid_t)-1),
1789 pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell);
1790
1791 /*
1792 * Let's create and populate the user's home directory. Note
1793 * that this also `works' for editing users if -m is used, but
1794 * existing files will *not* be overwritten.
1795 */
1796 if (PWALTDIR() != PWF_ALT && createhome && pwd->pw_dir &&
1797 *pwd->pw_dir == '/' && pwd->pw_dir[1]) {
1798 if (!skel)
1799 skel = cnf->dotdir;
1800 if (homemode == 0)
1801 homemode = cnf->homemode;
1802 create_and_populate_homedir(cnf, pwd, skel, homemode, true);
1803 }
1804
1805 if (nis && nis_update() == 0)
1806 pw_log(cnf, M_UPDATE, W_USER, "NIS maps updated");
1807
1808 return (EXIT_SUCCESS);
1809 }