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