]> git.cameronkatri.com Git - pw-darwin.git/blob - pw/pw_user.c
Clean up error handling in fileupdate(), which now returns 0 on success
[pw-darwin.git] / pw / pw_user.c
1 /*-
2 * Copyright (C) 1996
3 * David L. Nugent. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY DAVID L. NUGENT AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL DAVID L. NUGENT OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24 * SUCH DAMAGE.
25 *
26 */
27
28 #ifndef lint
29 static const char rcsid[] =
30 "$FreeBSD$";
31 #endif /* not lint */
32
33 #include <ctype.h>
34 #include <err.h>
35 #include <fcntl.h>
36 #include <sys/param.h>
37 #include <dirent.h>
38 #include <paths.h>
39 #include <termios.h>
40 #include <sys/types.h>
41 #include <sys/time.h>
42 #include <sys/resource.h>
43 #include <unistd.h>
44 #include <utmp.h>
45 #if defined(USE_MD5RAND)
46 #include <md5.h>
47 #endif
48 #include "pw.h"
49 #include "bitmap.h"
50
51 #if (MAXLOGNAME-1) > UT_NAMESIZE
52 #define LOGNAMESIZE UT_NAMESIZE
53 #else
54 #define LOGNAMESIZE (MAXLOGNAME-1)
55 #endif
56
57 static int randinit;
58
59 static int print_user(struct passwd * pwd, int pretty, int v7);
60 static uid_t pw_uidpolicy(struct userconf * cnf, struct cargs * args);
61 static uid_t pw_gidpolicy(struct userconf * cnf, struct cargs * args, char *nam, gid_t prefer);
62 static time_t pw_pwdpolicy(struct userconf * cnf, struct cargs * args);
63 static time_t pw_exppolicy(struct userconf * cnf, struct cargs * args);
64 static char *pw_homepolicy(struct userconf * cnf, struct cargs * args, char const * user);
65 static char *pw_shellpolicy(struct userconf * cnf, struct cargs * args, char *newshell);
66 static char *pw_password(struct userconf * cnf, struct cargs * args, char const * user);
67 static char *shell_path(char const * path, char *shells[], char *sh);
68 static void rmat(uid_t uid);
69 static void rmskey(char const * name);
70
71 /*-
72 * -C config configuration file
73 * -q quiet operation
74 * -n name login name
75 * -u uid user id
76 * -c comment user name/comment
77 * -d directory home directory
78 * -e date account expiry date
79 * -p date password expiry date
80 * -g grp primary group
81 * -G grp1,grp2 additional groups
82 * -m [ -k dir ] create and set up home
83 * -s shell name of login shell
84 * -o duplicate uid ok
85 * -L class user class
86 * -l name new login name
87 * -h fd password filehandle
88 * -F force print or add
89 * Setting defaults:
90 * -D set user defaults
91 * -b dir default home root dir
92 * -e period default expiry period
93 * -p period default password change period
94 * -g group default group
95 * -G grp1,grp2.. default additional groups
96 * -L class default login class
97 * -k dir default home skeleton
98 * -s shell default shell
99 * -w method default password method
100 */
101
102 int
103 pw_user(struct userconf * cnf, int mode, struct cargs * args)
104 {
105 int rc;
106 char *p = NULL;
107 struct carg *a_name;
108 struct carg *a_uid;
109 struct carg *arg;
110 struct passwd *pwd = NULL;
111 struct group *grp;
112 struct stat st;
113 char line[_PASSWORD_LEN+1];
114
115 static struct passwd fakeuser =
116 {
117 NULL,
118 "*",
119 -1,
120 -1,
121 0,
122 "",
123 "User &",
124 "/bin/sh",
125 0,
126 0,
127 0
128 };
129
130 /*
131 * With M_NEXT, we only need to return the
132 * next uid to stdout
133 */
134 if (mode == M_NEXT)
135 {
136 uid_t next = pw_uidpolicy(cnf, args);
137 if (getarg(args, 'q'))
138 return next;
139 printf("%ld:", (long)next);
140 pw_group(cnf, mode, args);
141 return EXIT_SUCCESS;
142 }
143
144 /*
145 * We can do all of the common legwork here
146 */
147
148 if ((arg = getarg(args, 'b')) != NULL) {
149 cnf->home = arg->val;
150 }
151
152 /*
153 * If we'll need to use it or we're updating it,
154 * then create the base home directory if necessary
155 */
156 if (arg != NULL || getarg(args, 'm') != NULL) {
157 int l = strlen(cnf->home);
158
159 if (l > 1 && cnf->home[l-1] == '/') /* Shave off any trailing path delimiter */
160 cnf->home[--l] = '\0';
161
162 if (l < 2 || *cnf->home != '/') /* Check for absolute path name */
163 errx(EX_DATAERR, "invalid base directory for home '%s'", cnf->home);
164
165 if (stat(cnf->home, &st) == -1) {
166 char dbuf[MAXPATHLEN];
167
168 /*
169 * This is a kludge especially for Joerg :)
170 * If the home directory would be created in the root partition, then
171 * we really create it under /usr which is likely to have more space.
172 * But we create a symlink from cnf->home -> "/usr" -> cnf->home
173 */
174 if (strchr(cnf->home+1, '/') == NULL) {
175 strcpy(dbuf, "/usr");
176 strncat(dbuf, cnf->home, MAXPATHLEN-5);
177 if (mkdir(dbuf, 0755) != -1 || errno == EEXIST) {
178 chown(dbuf, 0, 0);
179 symlink(dbuf, cnf->home);
180 }
181 /* If this falls, fall back to old method */
182 }
183 p = strncpy(dbuf, cnf->home, sizeof dbuf);
184 dbuf[MAXPATHLEN-1] = '\0';
185 if (stat(dbuf, &st) == -1) {
186 while ((p = strchr(++p, '/')) != NULL) {
187 *p = '\0';
188 if (stat(dbuf, &st) == -1) {
189 if (mkdir(dbuf, 0755) == -1)
190 goto direrr;
191 chown(dbuf, 0, 0);
192 } else if (!S_ISDIR(st.st_mode))
193 errx(EX_OSFILE, "'%s' (root home parent) is not a directory", dbuf);
194 *p = '/';
195 }
196 }
197 if (stat(dbuf, &st) == -1) {
198 if (mkdir(dbuf, 0755) == -1) {
199 direrr: err(EX_OSFILE, "mkdir '%s'", dbuf);
200 }
201 chown(dbuf, 0, 0);
202 }
203 } else if (!S_ISDIR(st.st_mode))
204 errx(EX_OSFILE, "root home `%s' is not a directory", cnf->home);
205 }
206
207
208 if ((arg = getarg(args, 'e')) != NULL)
209 cnf->expire_days = atoi(arg->val);
210
211 if ((arg = getarg(args, 'y')) != NULL)
212 cnf->nispasswd = arg->val;
213
214 if ((arg = getarg(args, 'p')) != NULL && arg->val)
215 cnf->password_days = atoi(arg->val);
216
217 if ((arg = getarg(args, 'g')) != NULL) {
218 p = arg->val;
219 if ((grp = GETGRNAM(p)) == NULL) {
220 if (!isdigit(*p) || (grp = GETGRGID((gid_t) atoi(p))) == NULL)
221 errx(EX_NOUSER, "group `%s' does not exist", p);
222 }
223 cnf->default_group = newstr(grp->gr_name);
224 }
225 if ((arg = getarg(args, 'L')) != NULL)
226 cnf->default_class = pw_checkname((u_char *)arg->val, 0);
227
228 if ((arg = getarg(args, 'G')) != NULL && arg->val) {
229 int i = 0;
230
231 for (p = strtok(arg->val, ", \t"); p != NULL; p = strtok(NULL, ", \t")) {
232 if ((grp = GETGRNAM(p)) == NULL) {
233 if (!isdigit(*p) || (grp = GETGRGID((gid_t) atoi(p))) == NULL)
234 errx(EX_NOUSER, "group `%s' does not exist", p);
235 }
236 if (extendarray(&cnf->groups, &cnf->numgroups, i + 2) != -1)
237 cnf->groups[i++] = newstr(grp->gr_name);
238 }
239 while (i < cnf->numgroups)
240 cnf->groups[i++] = NULL;
241 }
242 if ((arg = getarg(args, 'k')) != NULL) {
243 if (stat(cnf->dotdir = arg->val, &st) == -1 || !S_ISDIR(st.st_mode))
244 errx(EX_OSFILE, "skeleton `%s' is not a directory or does not exist", cnf->dotdir);
245 }
246 if ((arg = getarg(args, 's')) != NULL)
247 cnf->shell_default = arg->val;
248
249 if (mode == M_ADD && getarg(args, 'D')) {
250 if (getarg(args, 'n') != NULL)
251 errx(EX_DATAERR, "can't combine `-D' with `-n name'");
252 if ((arg = getarg(args, 'u')) != NULL && (p = strtok(arg->val, ", \t")) != NULL) {
253 if ((cnf->min_uid = (uid_t) atoi(p)) == 0)
254 cnf->min_uid = 1000;
255 if ((p = strtok(NULL, " ,\t")) == NULL || (cnf->max_uid = (uid_t) atoi(p)) < cnf->min_uid)
256 cnf->max_uid = 32000;
257 }
258 if ((arg = getarg(args, 'i')) != NULL && (p = strtok(arg->val, ", \t")) != NULL) {
259 if ((cnf->min_gid = (gid_t) atoi(p)) == 0)
260 cnf->min_gid = 1000;
261 if ((p = strtok(NULL, " ,\t")) == NULL || (cnf->max_gid = (gid_t) atoi(p)) < cnf->min_gid)
262 cnf->max_gid = 32000;
263 }
264 if ((arg = getarg(args, 'w')) != NULL)
265 cnf->default_password = boolean_val(arg->val, cnf->default_password);
266
267 arg = getarg(args, 'C');
268 if (write_userconfig(arg ? arg->val : NULL))
269 return EXIT_SUCCESS;
270 warn("config update");
271 return EX_IOERR;
272 }
273 if (mode == M_PRINT && getarg(args, 'a')) {
274 int pretty = getarg(args, 'P') != NULL;
275 int v7 = getarg(args, '7') != NULL;
276
277 SETPWENT();
278 while ((pwd = GETPWENT()) != NULL)
279 print_user(pwd, pretty, v7);
280 ENDPWENT();
281 return EXIT_SUCCESS;
282 }
283 if ((a_name = getarg(args, 'n')) != NULL)
284 pwd = GETPWNAM(pw_checkname((u_char *)a_name->val, 0));
285 a_uid = getarg(args, 'u');
286
287 if (a_uid == NULL) {
288 if (a_name == NULL)
289 errx(EX_DATAERR, "user name or id required");
290
291 /*
292 * Determine whether 'n' switch is name or uid - we don't
293 * really don't really care which we have, but we need to
294 * know.
295 */
296 if (mode != M_ADD && pwd == NULL
297 && strspn(a_name->val, "0123456789") == strlen(a_name->val)
298 && atoi(a_name->val) > 0) { /* Assume uid */
299 (a_uid = a_name)->ch = 'u';
300 a_name = NULL;
301 }
302 }
303 /*
304 * Update, delete & print require that the user exists
305 */
306 if (mode == M_UPDATE || mode == M_DELETE || mode == M_PRINT) {
307 if (a_name == NULL && pwd == NULL) /* Try harder */
308 pwd = GETPWUID(atoi(a_uid->val));
309
310 if (pwd == NULL) {
311 if (mode == M_PRINT && getarg(args, 'F')) {
312 fakeuser.pw_name = a_name ? a_name->val : "nouser";
313 fakeuser.pw_uid = a_uid ? (uid_t) atol(a_uid->val) : -1;
314 return print_user(&fakeuser,
315 getarg(args, 'P') != NULL,
316 getarg(args, '7') != NULL);
317 }
318 if (a_name == NULL)
319 errx(EX_NOUSER, "no such uid `%s'", a_uid->val);
320 errx(EX_NOUSER, "no such user `%s'", a_name->val);
321 }
322 if (a_name == NULL) /* May be needed later */
323 a_name = addarg(args, 'n', newstr(pwd->pw_name));
324
325 /*
326 * Handle deletions now
327 */
328 if (mode == M_DELETE) {
329 char file[MAXPATHLEN];
330 char home[MAXPATHLEN];
331 uid_t uid = pwd->pw_uid;
332
333 if (strcmp(pwd->pw_name, "root") == 0)
334 errx(EX_DATAERR, "cannot remove user 'root'");
335
336 if (!PWALTDIR()) {
337 /*
338 * Remove skey record from /etc/skeykeys
339 */
340
341 rmskey(pwd->pw_name);
342
343 /*
344 * Remove crontabs
345 */
346 sprintf(file, "/var/cron/tabs/%s", pwd->pw_name);
347 if (access(file, F_OK) == 0) {
348 sprintf(file, "crontab -u %s -r", pwd->pw_name);
349 system(file);
350 }
351 }
352 /*
353 * Save these for later, since contents of pwd may be
354 * invalidated by deletion
355 */
356 sprintf(file, "%s/%s", _PATH_MAILDIR, pwd->pw_name);
357 strncpy(home, pwd->pw_dir, sizeof home);
358 home[sizeof home - 1] = '\0';
359
360 rc = delpwent(pwd);
361 if (rc == -1)
362 err(EX_IOERR, "user '%s' does not exist", pwd->pw_name);
363 else if (rc != 0) {
364 warnc(rc, "passwd update");
365 return EX_IOERR;
366 }
367
368 if (cnf->nispasswd && *cnf->nispasswd=='/') {
369 rc = delnispwent(cnf->nispasswd, a_name->val);
370 if (rc == -1)
371 warnx("WARNING: user '%s' does not exist in NIS passwd", pwd->pw_name);
372 else if (rc != 0)
373 warnc(rc, "WARNING: NIS passwd update");
374 /* non-fatal */
375 }
376
377 editgroups(a_name->val, NULL);
378
379 pw_log(cnf, mode, W_USER, "%s(%ld) account removed", a_name->val, (long) uid);
380
381 if (!PWALTDIR()) {
382 /*
383 * Remove mail file
384 */
385 remove(file);
386
387 /*
388 * Remove at jobs
389 */
390 if (getpwuid(uid) == NULL)
391 rmat(uid);
392
393 /*
394 * Remove home directory and contents
395 */
396 if (getarg(args, 'r') != NULL && *home == '/' && getpwuid(uid) == NULL) {
397 if (stat(home, &st) != -1) {
398 rm_r(home, uid);
399 pw_log(cnf, mode, W_USER, "%s(%ld) home '%s' %sremoved",
400 a_name->val, (long) uid, home,
401 stat(home, &st) == -1 ? "" : "not completely ");
402 }
403 }
404 }
405 return EXIT_SUCCESS;
406 } else if (mode == M_PRINT)
407 return print_user(pwd,
408 getarg(args, 'P') != NULL,
409 getarg(args, '7') != NULL);
410
411 /*
412 * The rest is edit code
413 */
414 if ((arg = getarg(args, 'l')) != NULL) {
415 if (strcmp(pwd->pw_name, "root") == 0)
416 errx(EX_DATAERR, "can't rename `root' account");
417 pwd->pw_name = pw_checkname((u_char *)arg->val, 0);
418 }
419 if ((arg = getarg(args, 'u')) != NULL && isdigit(*arg->val)) {
420 pwd->pw_uid = (uid_t) atol(arg->val);
421 if (pwd->pw_uid != 0 && strcmp(pwd->pw_name, "root") == 0)
422 errx(EX_DATAERR, "can't change uid of `root' account");
423 if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
424 warnx("WARNING: account `%s' will have a uid of 0 (superuser access!)", pwd->pw_name);
425 }
426 if ((arg = getarg(args, 'g')) != NULL && pwd->pw_uid != 0) /* Already checked this */
427 pwd->pw_gid = (gid_t) GETGRNAM(cnf->default_group)->gr_gid;
428
429 if ((arg = getarg(args, 'p')) != NULL) {
430 if (*arg->val == '\0' || strcmp(arg->val, "0") == 0)
431 pwd->pw_change = 0;
432 else {
433 time_t now = time(NULL);
434 time_t expire = parse_date(now, arg->val);
435
436 if (now == expire)
437 errx(EX_DATAERR, "invalid password change date `%s'", arg->val);
438 pwd->pw_change = expire;
439 }
440 }
441 if ((arg = getarg(args, 'e')) != NULL) {
442 if (*arg->val == '\0' || strcmp(arg->val, "0") == 0)
443 pwd->pw_expire = 0;
444 else {
445 time_t now = time(NULL);
446 time_t expire = parse_date(now, arg->val);
447
448 if (now == expire)
449 errx(EX_DATAERR, "invalid account expiry date `%s'", arg->val);
450 pwd->pw_expire = expire;
451 }
452 }
453 if ((arg = getarg(args, 's')) != NULL)
454 pwd->pw_shell = shell_path(cnf->shelldir, cnf->shells, arg->val);
455
456 if (getarg(args, 'L'))
457 pwd->pw_class = cnf->default_class;
458
459 if ((arg = getarg(args, 'd')) != NULL) {
460 if (stat(pwd->pw_dir = arg->val, &st) == -1) {
461 if (getarg(args, 'm') == NULL && strcmp(pwd->pw_dir, "/nonexistent") != 0)
462 warnx("WARNING: home `%s' does not exist", pwd->pw_dir);
463 } else if (!S_ISDIR(st.st_mode))
464 warnx("WARNING: home `%s' is not a directory", pwd->pw_dir);
465 }
466
467 if ((arg = getarg(args, 'w')) != NULL && getarg(args, 'h') == NULL)
468 pwd->pw_passwd = pw_password(cnf, args, pwd->pw_name);
469
470 } else {
471 if (a_name == NULL) /* Required */
472 errx(EX_DATAERR, "login name required");
473 else if ((pwd = GETPWNAM(a_name->val)) != NULL) /* Exists */
474 errx(EX_DATAERR, "login name `%s' already exists", a_name->val);
475
476 /*
477 * Now, set up defaults for a new user
478 */
479 pwd = &fakeuser;
480 pwd->pw_name = a_name->val;
481 pwd->pw_class = cnf->default_class ? cnf->default_class : "";
482 pwd->pw_passwd = pw_password(cnf, args, pwd->pw_name);
483 pwd->pw_uid = pw_uidpolicy(cnf, args);
484 pwd->pw_gid = pw_gidpolicy(cnf, args, pwd->pw_name, (gid_t) pwd->pw_uid);
485 pwd->pw_change = pw_pwdpolicy(cnf, args);
486 pwd->pw_expire = pw_exppolicy(cnf, args);
487 pwd->pw_dir = pw_homepolicy(cnf, args, pwd->pw_name);
488 pwd->pw_shell = pw_shellpolicy(cnf, args, NULL);
489
490 if (pwd->pw_uid == 0 && strcmp(pwd->pw_name, "root") != 0)
491 warnx("WARNING: new account `%s' has a uid of 0 (superuser access!)", pwd->pw_name);
492 }
493
494 /*
495 * Shared add/edit code
496 */
497 if ((arg = getarg(args, 'c')) != NULL)
498 pwd->pw_gecos = pw_checkname((u_char *)arg->val, 1);
499
500 if ((arg = getarg(args, 'h')) != NULL) {
501 if (strcmp(arg->val, "-") == 0)
502 pwd->pw_passwd = "*"; /* No access */
503 else {
504 int fd = atoi(arg->val);
505 int b;
506 int istty = isatty(fd);
507 struct termios t;
508
509 if (istty) {
510 if (tcgetattr(fd, &t) == -1)
511 istty = 0;
512 else {
513 struct termios n = t;
514
515 /* Disable echo */
516 n.c_lflag &= ~(ECHO);
517 tcsetattr(fd, TCSANOW, &n);
518 printf("%sassword for user %s:", (mode == M_UPDATE) ? "New p" : "P", pwd->pw_name);
519 fflush(stdout);
520 }
521 }
522 b = read(fd, line, sizeof(line) - 1);
523 if (istty) { /* Restore state */
524 tcsetattr(fd, TCSANOW, &t);
525 fputc('\n', stdout);
526 fflush(stdout);
527 }
528 if (b < 0) {
529 warn("-h file descriptor");
530 return EX_IOERR;
531 }
532 line[b] = '\0';
533 if ((p = strpbrk(line, " \t\r\n")) != NULL)
534 *p = '\0';
535 if (!*line)
536 errx(EX_DATAERR, "empty password read on file descriptor %d", fd);
537 pwd->pw_passwd = pw_pwcrypt(line);
538 }
539 }
540
541 /*
542 * Special case: -N only displays & exits
543 */
544 if (getarg(args, 'N') != NULL)
545 return print_user(pwd,
546 getarg(args, 'P') != NULL,
547 getarg(args, '7') != NULL);
548
549 if (mode == M_ADD) {
550 rc = addpwent(pwd);
551 if (rc == -1) {
552 warnx("user '%s' already exists", pwd->pw_name);
553 return EX_IOERR;
554 } else if (rc != 0) {
555 warnc(rc, "passwd file update");
556 return EX_IOERR;
557 }
558 if (cnf->nispasswd && *cnf->nispasswd=='/') {
559 rc = addnispwent(cnf->nispasswd, pwd);
560 if (rc == -1)
561 warnx("User '%s' already exists in NIS passwd", pwd->pw_name);
562 else
563 warnc(rc, "NIS passwd update");
564 /* NOTE: we treat NIS-only update errors as non-fatal */
565 }
566 } else if (mode == M_UPDATE) {
567 rc = chgpwent(a_name->val, pwd);
568 if (rc == -1) {
569 warnx("user '%s' does not exist (NIS?)", pwd->pw_name);
570 return EX_IOERR;
571 } else if (rc != 0) {
572 warnc(rc, "passwd file update");
573 return EX_IOERR;
574 }
575 if ( cnf->nispasswd && *cnf->nispasswd=='/') {
576 rc = chgnispwent(cnf->nispasswd, a_name->val, pwd);
577 if (rc == -1)
578 warn("User '%s' not found in NIS passwd", pwd->pw_name);
579 else
580 warnc(rc, "NIS passwd update");
581 /* NOTE: NIS-only update errors are not fatal */
582 }
583 }
584
585 /*
586 * Ok, user is created or changed - now edit group file
587 */
588
589 if (mode == M_ADD || getarg(args, 'G') != NULL)
590 editgroups(pwd->pw_name, cnf->groups);
591
592 /* pwd may have been invalidated */
593 if ((pwd = GETPWNAM(a_name->val)) == NULL)
594 errx(EX_NOUSER, "user '%s' disappeared during update", a_name->val);
595
596 grp = GETGRGID(pwd->pw_gid);
597 pw_log(cnf, mode, W_USER, "%s(%ld):%s(%d):%s:%s:%s",
598 pwd->pw_name, (long) pwd->pw_uid,
599 grp ? grp->gr_name : "unknown", (long) (grp ? grp->gr_gid : -1),
600 pwd->pw_gecos, pwd->pw_dir, pwd->pw_shell);
601
602 /*
603 * If adding, let's touch and chown the user's mail file. This is not
604 * strictly necessary under BSD with a 0755 maildir but it also
605 * doesn't hurt anything to create the empty mailfile
606 */
607 if (mode == M_ADD) {
608 FILE *fp;
609
610 if (!PWALTDIR()) {
611 sprintf(line, "%s/%s", _PATH_MAILDIR, pwd->pw_name);
612 close(open(line, O_RDWR | O_CREAT, 0600)); /* Preserve contents &
613 * mtime */
614 chown(line, pwd->pw_uid, pwd->pw_gid);
615
616 /*
617 * Send mail to the new user as well, if we are asked to
618 */
619 if (cnf->newmail && *cnf->newmail && (fp = fopen(cnf->newmail, "r")) != NULL) {
620 FILE *pfp = popen(_PATH_SENDMAIL " -t", "w");
621
622 if (pfp == NULL)
623 warn("sendmail");
624 else {
625 fprintf(pfp, "From: root\n" "To: %s\n" "Subject: Welcome!\n\n", pwd->pw_name);
626 while (fgets(line, sizeof(line), fp) != NULL) {
627 /* Do substitutions? */
628 fputs(line, pfp);
629 }
630 pclose(pfp);
631 pw_log(cnf, mode, W_USER, "%s(%ld) new user mail sent",
632 pwd->pw_name, (long) pwd->pw_uid);
633 }
634 fclose(fp);
635 }
636 }
637 }
638 /*
639 * Finally, let's create and populate the user's home directory. Note
640 * that this also `works' for editing users if -m is used, but
641 * existing files will *not* be overwritten.
642 */
643 if (!PWALTDIR() && getarg(args, 'm') != NULL && pwd->pw_dir && *pwd->pw_dir == '/' && pwd->pw_dir[1]) {
644 copymkdir(pwd->pw_dir, cnf->dotdir, 0755, pwd->pw_uid, pwd->pw_gid);
645 pw_log(cnf, mode, W_USER, "%s(%ld) home %s made",
646 pwd->pw_name, (long) pwd->pw_uid, pwd->pw_dir);
647 }
648 return EXIT_SUCCESS;
649 }
650
651
652 static uid_t
653 pw_uidpolicy(struct userconf * cnf, struct cargs * args)
654 {
655 struct passwd *pwd;
656 uid_t uid = (uid_t) - 1;
657 struct carg *a_uid = getarg(args, 'u');
658
659 /*
660 * Check the given uid, if any
661 */
662 if (a_uid != NULL) {
663 uid = (uid_t) atol(a_uid->val);
664
665 if ((pwd = GETPWUID(uid)) != NULL && getarg(args, 'o') == NULL)
666 errx(EX_DATAERR, "uid `%ld' has already been allocated", (long) pwd->pw_uid);
667 } else {
668 struct bitmap bm;
669
670 /*
671 * We need to allocate the next available uid under one of
672 * two policies a) Grab the first unused uid b) Grab the
673 * highest possible unused uid
674 */
675 if (cnf->min_uid >= cnf->max_uid) { /* Sanity
676 * claus^H^H^H^Hheck */
677 cnf->min_uid = 1000;
678 cnf->max_uid = 32000;
679 }
680 bm = bm_alloc(cnf->max_uid - cnf->min_uid + 1);
681
682 /*
683 * Now, let's fill the bitmap from the password file
684 */
685 SETPWENT();
686 while ((pwd = GETPWENT()) != NULL)
687 if (pwd->pw_uid >= (uid_t) cnf->min_uid && pwd->pw_uid <= (uid_t) cnf->max_uid)
688 bm_setbit(&bm, pwd->pw_uid - cnf->min_uid);
689 ENDPWENT();
690
691 /*
692 * Then apply the policy, with fallback to reuse if necessary
693 */
694 if (cnf->reuse_uids || (uid = (uid_t) (bm_lastset(&bm) + cnf->min_uid + 1)) > cnf->max_uid)
695 uid = (uid_t) (bm_firstunset(&bm) + cnf->min_uid);
696
697 /*
698 * Another sanity check
699 */
700 if (uid < cnf->min_uid || uid > cnf->max_uid)
701 errx(EX_SOFTWARE, "unable to allocate a new uid - range fully used");
702 bm_dealloc(&bm);
703 }
704 return uid;
705 }
706
707
708 static uid_t
709 pw_gidpolicy(struct userconf * cnf, struct cargs * args, char *nam, gid_t prefer)
710 {
711 struct group *grp;
712 gid_t gid = (uid_t) - 1;
713 struct carg *a_gid = getarg(args, 'g');
714
715 /*
716 * If no arg given, see if default can help out
717 */
718 if (a_gid == NULL && cnf->default_group && *cnf->default_group)
719 a_gid = addarg(args, 'g', cnf->default_group);
720
721 /*
722 * Check the given gid, if any
723 */
724 SETGRENT();
725 if (a_gid != NULL) {
726 if ((grp = GETGRNAM(a_gid->val)) == NULL) {
727 gid = (gid_t) atol(a_gid->val);
728 if ((gid == 0 && !isdigit(*a_gid->val)) || (grp = GETGRGID(gid)) == NULL)
729 errx(EX_NOUSER, "group `%s' is not defined", a_gid->val);
730 }
731 gid = grp->gr_gid;
732 } else if ((grp = GETGRNAM(nam)) != NULL && grp->gr_mem[0] == NULL) {
733 gid = grp->gr_gid; /* Already created? Use it anyway... */
734 } else {
735 struct cargs grpargs;
736 char tmp[32];
737
738 LIST_INIT(&grpargs);
739 addarg(&grpargs, 'n', nam);
740
741 /*
742 * We need to auto-create a group with the user's name. We
743 * can send all the appropriate output to our sister routine
744 * bit first see if we can create a group with gid==uid so we
745 * can keep the user and group ids in sync. We purposely do
746 * NOT check the gid range if we can force the sync. If the
747 * user's name dups an existing group, then the group add
748 * function will happily handle that case for us and exit.
749 */
750 if (GETGRGID(prefer) == NULL) {
751 sprintf(tmp, "%lu", (unsigned long) prefer);
752 addarg(&grpargs, 'g', tmp);
753 }
754 if (getarg(args, 'N'))
755 {
756 addarg(&grpargs, 'N', NULL);
757 addarg(&grpargs, 'q', NULL);
758 gid = pw_group(cnf, M_NEXT, &grpargs);
759 }
760 else
761 {
762 pw_group(cnf, M_ADD, &grpargs);
763 if ((grp = GETGRNAM(nam)) != NULL)
764 gid = grp->gr_gid;
765 }
766 a_gid = grpargs.lh_first;
767 while (a_gid != NULL) {
768 struct carg *t = a_gid->list.le_next;
769 LIST_REMOVE(a_gid, list);
770 a_gid = t;
771 }
772 }
773 ENDGRENT();
774 return gid;
775 }
776
777
778 static time_t
779 pw_pwdpolicy(struct userconf * cnf, struct cargs * args)
780 {
781 time_t result = 0;
782 time_t now = time(NULL);
783 struct carg *arg = getarg(args, 'p');
784
785 if (arg != NULL) {
786 if ((result = parse_date(now, arg->val)) == now)
787 errx(EX_DATAERR, "invalid date/time `%s'", arg->val);
788 } else if (cnf->password_days > 0)
789 result = now + ((long) cnf->password_days * 86400L);
790 return result;
791 }
792
793
794 static time_t
795 pw_exppolicy(struct userconf * cnf, struct cargs * args)
796 {
797 time_t result = 0;
798 time_t now = time(NULL);
799 struct carg *arg = getarg(args, 'e');
800
801 if (arg != NULL) {
802 if ((result = parse_date(now, arg->val)) == now)
803 errx(EX_DATAERR, "invalid date/time `%s'", arg->val);
804 } else if (cnf->expire_days > 0)
805 result = now + ((long) cnf->expire_days * 86400L);
806 return result;
807 }
808
809
810 static char *
811 pw_homepolicy(struct userconf * cnf, struct cargs * args, char const * user)
812 {
813 struct carg *arg = getarg(args, 'd');
814
815 if (arg)
816 return arg->val;
817 else {
818 static char home[128];
819
820 if (cnf->home == NULL || *cnf->home == '\0')
821 errx(EX_CONFIG, "no base home directory set");
822 sprintf(home, "%s/%s", cnf->home, user);
823 return home;
824 }
825 }
826
827 static char *
828 shell_path(char const * path, char *shells[], char *sh)
829 {
830 if (sh != NULL && (*sh == '/' || *sh == '\0'))
831 return sh; /* specified full path or forced none */
832 else {
833 char *p;
834 char paths[_UC_MAXLINE];
835
836 /*
837 * We need to search paths
838 */
839 strncpy(paths, path, sizeof paths);
840 paths[sizeof paths - 1] = '\0';
841 for (p = strtok(paths, ": \t\r\n"); p != NULL; p = strtok(NULL, ": \t\r\n")) {
842 int i;
843 static char shellpath[256];
844
845 if (sh != NULL) {
846 sprintf(shellpath, "%s/%s", p, sh);
847 if (access(shellpath, X_OK) == 0)
848 return shellpath;
849 } else
850 for (i = 0; i < _UC_MAXSHELLS && shells[i] != NULL; i++) {
851 sprintf(shellpath, "%s/%s", p, shells[i]);
852 if (access(shellpath, X_OK) == 0)
853 return shellpath;
854 }
855 }
856 if (sh == NULL)
857 errx(EX_OSFILE, "can't find shell `%s' in shell paths", sh);
858 errx(EX_CONFIG, "no default shell available or defined");
859 return NULL;
860 }
861 }
862
863
864 static char *
865 pw_shellpolicy(struct userconf * cnf, struct cargs * args, char *newshell)
866 {
867 char *sh = newshell;
868 struct carg *arg = getarg(args, 's');
869
870 if (newshell == NULL && arg != NULL)
871 sh = arg->val;
872 return shell_path(cnf->shelldir, cnf->shells, sh ? sh : cnf->shell_default);
873 }
874
875 static char const chars[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.";
876
877 char *
878 pw_pwcrypt(char *password)
879 {
880 int i;
881 char salt[12];
882
883 static char buf[256];
884
885 /*
886 * Calculate a salt value
887 */
888 if (!randinit) {
889 randinit = 1;
890 #ifdef __FreeBSD__
891 srandomdev();
892 #else
893 srandom((unsigned long) (time(NULL) ^ getpid()));
894 #endif
895 }
896 for (i = 0; i < 8; i++)
897 salt[i] = chars[random() % 63];
898 salt[i] = '\0';
899
900 return strcpy(buf, crypt(password, salt));
901 }
902
903 #if defined(USE_MD5RAND)
904 u_char *
905 pw_getrand(u_char *buf, int len) /* cryptographically secure rng */
906 {
907 int i;
908 for (i=0;i<len;i+=16) {
909 u_char ubuf[16];
910
911 MD5_CTX md5_ctx;
912 struct timeval tv, tvo;
913 struct rusage ru;
914 int n=0;
915 int t;
916
917 MD5Init (&md5_ctx);
918 t=getpid();
919 MD5Update (&md5_ctx, (u_char*)&t, sizeof t);
920 t=getppid();
921 MD5Update (&md5_ctx, (u_char*)&t, sizeof t);
922 gettimeofday (&tvo, NULL);
923 do {
924 getrusage (RUSAGE_SELF, &ru);
925 MD5Update (&md5_ctx, (u_char*)&ru, sizeof ru);
926 gettimeofday (&tv, NULL);
927 MD5Update (&md5_ctx, (u_char*)&tv, sizeof tv);
928 } while (n++<20 || tv.tv_usec-tvo.tv_usec<100*1000);
929 MD5Final (ubuf, &md5_ctx);
930 memcpy(buf+i, ubuf, MIN(16, len-n));
931 }
932 return buf;
933 }
934
935 #else /* Portable version */
936
937 static u_char *
938 pw_getrand(u_char *buf, int len)
939 {
940 int i;
941
942 for (i = 0; i < len; i++) {
943 unsigned long val = random();
944 /* Use all bits in the random value */
945 buf[i]=(u_char)((val >> 24) ^ (val >> 16) ^ (val >> 8) ^ val);
946 }
947 return buf;
948 }
949
950 #endif
951
952 static char *
953 pw_password(struct userconf * cnf, struct cargs * args, char const * user)
954 {
955 int i, l;
956 char pwbuf[32];
957 u_char rndbuf[sizeof pwbuf];
958
959 switch (cnf->default_password) {
960 case -1: /* Random password */
961 if (!randinit) {
962 randinit = 1;
963 #ifdef __FreeBSD__
964 srandomdev();
965 #else
966 srandom((unsigned long) (time(NULL) ^ getpid()));
967 #endif
968 }
969 l = (random() % 8 + 8); /* 8 - 16 chars */
970 pw_getrand(rndbuf, l);
971 for (i = 0; i < l; i++)
972 pwbuf[i] = chars[rndbuf[i] % (sizeof(chars)-1)];
973 pwbuf[i] = '\0';
974
975 /*
976 * We give this information back to the user
977 */
978 if (getarg(args, 'h') == NULL && getarg(args, 'N') == NULL) {
979 if (isatty(1))
980 printf("Password for '%s' is: ", user);
981 printf("%s\n", pwbuf);
982 fflush(stdout);
983 }
984 break;
985
986 case -2: /* No password at all! */
987 return "";
988
989 case 0: /* No login - default */
990 default:
991 return "*";
992
993 case 1: /* user's name */
994 strncpy(pwbuf, user, sizeof pwbuf);
995 pwbuf[sizeof pwbuf - 1] = '\0';
996 break;
997 }
998 return pw_pwcrypt(pwbuf);
999 }
1000
1001
1002 static int
1003 print_user(struct passwd * pwd, int pretty, int v7)
1004 {
1005 if (!pretty) {
1006 char buf[_UC_MAXLINE];
1007
1008 fmtpwentry(buf, pwd, v7 ? PWF_PASSWD : PWF_STANDARD);
1009 fputs(buf, stdout);
1010 } else {
1011 int j;
1012 char *p;
1013 struct group *grp = GETGRGID(pwd->pw_gid);
1014 char uname[60] = "User &", office[60] = "[None]",
1015 wphone[60] = "[None]", hphone[60] = "[None]";
1016 char acexpire[32] = "[None]", pwexpire[32] = "[None]";
1017 struct tm * tptr;
1018
1019 if ((p = strtok(pwd->pw_gecos, ",")) != NULL) {
1020 strncpy(uname, p, sizeof uname);
1021 uname[sizeof uname - 1] = '\0';
1022 if ((p = strtok(NULL, ",")) != NULL) {
1023 strncpy(office, p, sizeof office);
1024 office[sizeof office - 1] = '\0';
1025 if ((p = strtok(NULL, ",")) != NULL) {
1026 strncpy(wphone, p, sizeof wphone);
1027 wphone[sizeof wphone - 1] = '\0';
1028 if ((p = strtok(NULL, "")) != NULL) {
1029 strncpy(hphone, p, sizeof hphone);
1030 hphone[sizeof hphone - 1] = '\0';
1031 }
1032 }
1033 }
1034 }
1035 /*
1036 * Handle '&' in gecos field
1037 */
1038 if ((p = strchr(uname, '&')) != NULL) {
1039 int l = strlen(pwd->pw_name);
1040 int m = strlen(p);
1041
1042 memmove(p + l, p + 1, m);
1043 memmove(p, pwd->pw_name, l);
1044 *p = (char) toupper(*p);
1045 }
1046 if (pwd->pw_expire > (time_t)0 && (tptr = localtime(&pwd->pw_expire)) != NULL)
1047 strftime(acexpire, sizeof acexpire, "%c", tptr);
1048 if (pwd->pw_change > (time_t)9 && (tptr = localtime(&pwd->pw_change)) != NULL)
1049 strftime(pwexpire, sizeof pwexpire, "%c", tptr);
1050 printf("Login Name: %-15s #%-12ld Group: %-15s #%ld\n"
1051 " Full Name: %s\n"
1052 " Home: %-26.26s Class: %s\n"
1053 " Shell: %-26.26s Office: %s\n"
1054 "Work Phone: %-26.26s Home Phone: %s\n"
1055 "Acc Expire: %-26.26s Pwd Expire: %s\n",
1056 pwd->pw_name, (long) pwd->pw_uid,
1057 grp ? grp->gr_name : "(invalid)", (long) pwd->pw_gid,
1058 uname, pwd->pw_dir, pwd->pw_class,
1059 pwd->pw_shell, office, wphone, hphone,
1060 acexpire, pwexpire);
1061 SETGRENT();
1062 j = 0;
1063 while ((grp=GETGRENT()) != NULL)
1064 {
1065 int i = 0;
1066 while (grp->gr_mem[i] != NULL)
1067 {
1068 if (strcmp(grp->gr_mem[i], pwd->pw_name)==0)
1069 {
1070 printf(j++ == 0 ? " Groups: %s" : ",%s", grp->gr_name);
1071 break;
1072 }
1073 ++i;
1074 }
1075 }
1076 ENDGRENT();
1077 printf("%s\n", j ? "\n" : "");
1078 }
1079 return EXIT_SUCCESS;
1080 }
1081
1082 char *
1083 pw_checkname(u_char *name, int gecos)
1084 {
1085 int l = 0;
1086 char const *notch = gecos ? ":!@" : " ,\t:+&#%$^()!@~*?<>=|\\/\"";
1087
1088 while (name[l]) {
1089 if (strchr(notch, name[l]) != NULL || name[l] < ' ' || name[l] == 127 ||
1090 (!gecos && l==0 && name[l] == '-') || /* leading '-' */
1091 (!gecos && name[l] & 0x80)) /* 8-bit */
1092 errx(EX_DATAERR, (name[l] >= ' ' && name[l] < 127)
1093 ? "invalid character `%c' in field"
1094 : "invalid character 0x%02x in field",
1095 name[l]);
1096 ++l;
1097 }
1098 if (!gecos && l > LOGNAMESIZE)
1099 errx(EX_DATAERR, "name too long `%s'", name);
1100 return (char *)name;
1101 }
1102
1103
1104 static void
1105 rmat(uid_t uid)
1106 {
1107 DIR *d = opendir("/var/at/jobs");
1108
1109 if (d != NULL) {
1110 struct dirent *e;
1111
1112 while ((e = readdir(d)) != NULL) {
1113 struct stat st;
1114
1115 if (strncmp(e->d_name, ".lock", 5) != 0 &&
1116 stat(e->d_name, &st) == 0 &&
1117 !S_ISDIR(st.st_mode) &&
1118 st.st_uid == uid) {
1119 char tmp[MAXPATHLEN];
1120
1121 sprintf(tmp, "/usr/bin/atrm %s", e->d_name);
1122 system(tmp);
1123 }
1124 }
1125 closedir(d);
1126 }
1127 }
1128
1129 static void
1130 rmskey(char const * name)
1131 {
1132 static const char etcskey[] = "/etc/skeykeys";
1133 FILE *fp = fopen(etcskey, "r+");
1134
1135 if (fp != NULL) {
1136 char tmp[1024];
1137 off_t atofs = 0;
1138 int length = strlen(name);
1139
1140 while (fgets(tmp, sizeof tmp, fp) != NULL) {
1141 if (strncmp(name, tmp, length) == 0 && tmp[length]==' ') {
1142 if (fseek(fp, atofs, SEEK_SET) == 0) {
1143 fwrite("#", 1, 1, fp); /* Comment username out */
1144 }
1145 break;
1146 }
1147 atofs = ftell(fp);
1148 }
1149 /*
1150 * If we got an error of any sort, don't update!
1151 */
1152 fclose(fp);
1153 }
1154 }
1155