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