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