2 * Copyright (c) 1993-1996,1998-2005, 2007-2010
3 * Todd C. Miller <Todd.Miller@courtesan.com>
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 * Sponsored in part by the Defense Advanced Research Projects
18 * Agency (DARPA) and Air Force Research Laboratory, Air Force
19 * Materiel Command, USAF, under agreement number F39502-99-1-0512.
24 #include <sys/types.h>
25 #include <sys/param.h>
31 #if defined(__sun) && defined(__SVR4)
32 # include <sys/statvfs.h>
35 # include <sys/file.h>
45 #endif /* STDC_HEADERS */
48 #endif /* HAVE_STRING_H */
51 #endif /* HAVE_STRINGS_H */
54 #endif /* HAVE_UNISTD_H */
55 #if TIME_WITH_SYS_TIME
66 /* Status codes for timestamp_status() */
73 /* Flags for timestamp_status() */
74 #define TS_MAKE_DIRS 1
78 * Info stored in tty ticket from stat(2) to help with tty matching.
80 static struct tty_info {
81 dev_t dev; /* ID of device tty resides on */
82 dev_t rdev; /* tty device ID */
83 ino_t ino; /* tty inode number */
84 struct timeval ctime; /* tty inode change time */
87 static void build_timestamp __P((char **, char **));
88 static int timestamp_status __P((char *, char *, char *, int));
89 static char *expand_prompt __P((char *, char *, char *));
90 static void lecture __P((int));
91 static void update_timestamp __P((char *, char *));
92 static int tty_is_devpts __P((const char *));
95 * This function only returns if the user can successfully
96 * verify who he/she is.
99 check_user(validated, mode)
103 char *timestampdir = NULL;
104 char *timestampfile = NULL;
109 /* Stash the tty's ctime for tty ticket comparison. */
110 if (def_tty_tickets && user_ttypath && stat(user_ttypath, &sb) == 0) {
111 tty_info.dev = sb.st_dev;
112 tty_info.ino = sb.st_ino;
113 tty_info.rdev = sb.st_rdev;
114 if (tty_is_devpts(user_ttypath))
115 ctim_get(&sb, &tty_info.ctime);
118 /* Always prompt for a password when -k was specified with the command. */
119 if (ISSET(mode, MODE_INVALIDATE)) {
120 SET(validated, FLAG_CHECK_USER);
123 * Don't prompt for the root passwd or if the user is exempt.
124 * If the user is not changing uid/gid, no need for a password.
126 if (user_uid == 0 || (user_uid == runas_pw->pw_uid &&
127 (!runas_gr || user_in_group(sudo_user.pw, runas_gr->gr_name))) ||
132 build_timestamp(×tampdir, ×tampfile);
133 status = timestamp_status(timestampdir, timestampfile, user_name,
136 if (status != TS_CURRENT || ISSET(validated, FLAG_CHECK_USER)) {
137 /* Bail out if we are non-interactive and a password is required */
138 if (ISSET(mode, MODE_NONINTERACTIVE))
139 errorx(1, "sorry, a password is required to run %s", getprogname());
141 /* If user specified -A, make sure we have an askpass helper. */
142 if (ISSET(tgetpass_flags, TGP_ASKPASS)) {
143 if (user_askpass == NULL)
145 "no askpass program specified, try setting SUDO_ASKPASS");
146 } else if (!ISSET(tgetpass_flags, TGP_STDIN)) {
147 /* If no tty but DISPLAY is set, use askpass if we have it. */
148 if (!user_ttypath && !tty_present()) {
149 if (user_askpass && user_display && *user_display != '\0') {
150 SET(tgetpass_flags, TGP_ASKPASS);
151 } else if (!def_visiblepw) {
153 "no tty present and no askpass program specified");
158 if (!ISSET(tgetpass_flags, TGP_ASKPASS))
161 /* Expand any escapes in the prompt. */
162 prompt = expand_prompt(user_prompt ? user_prompt : def_passprompt,
163 user_name, user_shost);
165 verify_user(auth_pw, prompt);
167 /* Only update timestamp if user was validated. */
168 if (ISSET(validated, VALIDATE_OK) && !ISSET(mode, MODE_INVALIDATE) && status != TS_ERROR)
169 update_timestamp(timestampdir, timestampfile);
171 efree(timestampfile);
175 * Standard sudo lecture.
185 if (def_lecture == never ||
186 (def_lecture == once && status != TS_MISSING && status != TS_ERROR))
189 if (def_lecture_file && (fp = fopen(def_lecture_file, "r")) != NULL) {
190 while ((nread = fread(buf, sizeof(char), sizeof(buf), fp)) != 0)
191 fwrite(buf, nread, 1, stderr);
195 We trust you have received the usual lecture from the local System\n\
196 Administrator. It usually boils down to these three things:\n\
198 #1) Respect the privacy of others.\n\
199 #2) Think before you type.\n\
200 #3) With great power comes great responsibility.\n\n",
206 * Update the time on the timestamp file/dir or create it if necessary.
209 update_timestamp(timestampdir, timestampfile)
213 /* If using tty timestamps but we have no tty there is nothing to do. */
214 if (def_tty_tickets && !user_ttypath)
217 if (timestamp_uid != 0)
218 set_perms(PERM_TIMESTAMP);
221 * Store tty info in timestamp file
223 int fd = open(timestampfile, O_WRONLY|O_CREAT, 0600);
225 log_error(NO_EXIT|USE_ERRNO, "Can't open %s", timestampfile);
227 lock_file(fd, SUDO_LOCK);
228 write(fd, &tty_info, sizeof(tty_info));
232 if (touch(-1, timestampdir, NULL) == -1) {
233 if (mkdir(timestampdir, 0700) == -1)
234 log_error(NO_EXIT|USE_ERRNO, "Can't mkdir %s", timestampdir);
237 if (timestamp_uid != 0)
238 set_perms(PERM_ROOT);
242 * Expand %h and %u escapes in the prompt and pass back the dynamically
243 * allocated result. Returns the same string if there are no escapes.
246 expand_prompt(old_prompt, user, host)
253 char *p, *np, *new_prompt, *endp;
255 /* How much space do we need to malloc for the prompt? */
257 for (p = old_prompt, len = strlen(old_prompt); *p; p++) {
262 len += strlen(user_shost) - 2;
267 len += strlen(user_host) - 2;
274 else if (def_targetpw || def_runaspw)
275 len += strlen(runas_pw->pw_name) - 2;
277 len += strlen(user_name) - 2;
282 len += strlen(user_name) - 2;
287 len += strlen(runas_pw->pw_name) - 2;
302 new_prompt = (char *) emalloc(++len);
303 endp = new_prompt + len;
304 for (p = old_prompt, np = new_prompt; *p; p++) {
309 n = strlcpy(np, user_shost, np - endp);
316 n = strlcpy(np, user_host, np - endp);
324 n = strlcpy(np, "root", np - endp);
325 else if (def_targetpw || def_runaspw)
326 n = strlcpy(np, runas_pw->pw_name, np - endp);
328 n = strlcpy(np, user_name, np - endp);
335 n = strlcpy(np, user_name, np - endp);
342 n = strlcpy(np, runas_pw->pw_name, np - endp);
348 /* convert %% -> % */
362 new_prompt = old_prompt;
367 /* We pre-allocate enough space, so this should never happen. */
368 errorx(1, "internal error, expand_prompt() overflow");
372 * Checks if the user is exempt from supplying a password.
377 if (!def_exempt_group)
379 return(user_in_group(sudo_user.pw, def_exempt_group));
383 * Fills in timestampdir as well as timestampfile if using tty tickets.
386 build_timestamp(timestampdir, timestampfile)
388 char **timestampfile;
393 dirparent = def_timestampdir;
394 len = easprintf(timestampdir, "%s/%s", dirparent, user_name);
396 log_error(0, "timestamp path too long: %s", *timestampdir);
399 * Timestamp file may be a file in the directory or NUL to use
400 * the directory as the timestamp.
402 if (def_tty_tickets) {
405 if ((p = strrchr(user_tty, '/')))
410 len = easprintf(timestampfile, "%s/%s/%s:%s", dirparent, user_name,
411 p, runas_pw->pw_name);
413 len = easprintf(timestampfile, "%s/%s/%s", dirparent, user_name, p);
415 log_error(0, "timestamp path too long: %s", *timestampfile);
416 } else if (def_targetpw) {
417 len = easprintf(timestampfile, "%s/%s/%s", dirparent, user_name,
420 log_error(0, "timestamp path too long: %s", *timestampfile);
422 *timestampfile = NULL;
426 * Check the timestamp file and directory and return their status.
429 timestamp_status(timestampdir, timestampfile, user, flags)
436 struct timeval boottime, mtime;
438 char *dirparent = def_timestampdir;
439 int status = TS_ERROR; /* assume the worst */
441 if (timestamp_uid != 0)
442 set_perms(PERM_TIMESTAMP);
445 * Sanity check dirparent and make it if it doesn't already exist.
446 * We start out assuming the worst (that the dir is not sane) and
447 * if it is ok upgrade the status to ``no timestamp file''.
448 * Note that we don't check the parent(s) of dirparent for
449 * sanity since the sudo dir is often just located in /tmp.
451 if (lstat(dirparent, &sb) == 0) {
452 if (!S_ISDIR(sb.st_mode))
453 log_error(NO_EXIT, "%s exists but is not a directory (0%o)",
454 dirparent, (unsigned int) sb.st_mode);
455 else if (sb.st_uid != timestamp_uid)
456 log_error(NO_EXIT, "%s owned by uid %lu, should be uid %lu",
457 dirparent, (unsigned long) sb.st_uid,
458 (unsigned long) timestamp_uid);
459 else if ((sb.st_mode & 0000022))
461 "%s writable by non-owner (0%o), should be mode 0700",
462 dirparent, (unsigned int) sb.st_mode);
464 if ((sb.st_mode & 0000777) != 0700)
465 (void) chmod(dirparent, 0700);
468 } else if (errno != ENOENT) {
469 log_error(NO_EXIT|USE_ERRNO, "can't stat %s", dirparent);
471 /* No dirparent, try to make one. */
472 if (ISSET(flags, TS_MAKE_DIRS)) {
473 if (mkdir(dirparent, S_IRWXU))
474 log_error(NO_EXIT|USE_ERRNO, "can't mkdir %s",
480 if (status == TS_ERROR) {
481 if (timestamp_uid != 0)
482 set_perms(PERM_ROOT);
487 * Sanity check the user's ticket dir. We start by downgrading
488 * the status to TS_ERROR. If the ticket dir exists and is sane
489 * this will be upgraded to TS_OLD. If the dir does not exist,
490 * it will be upgraded to TS_MISSING.
492 status = TS_ERROR; /* downgrade status again */
493 if (lstat(timestampdir, &sb) == 0) {
494 if (!S_ISDIR(sb.st_mode)) {
495 if (S_ISREG(sb.st_mode)) {
496 /* convert from old style */
497 if (unlink(timestampdir) == 0)
500 log_error(NO_EXIT, "%s exists but is not a directory (0%o)",
501 timestampdir, (unsigned int) sb.st_mode);
502 } else if (sb.st_uid != timestamp_uid)
503 log_error(NO_EXIT, "%s owned by uid %lu, should be uid %lu",
504 timestampdir, (unsigned long) sb.st_uid,
505 (unsigned long) timestamp_uid);
506 else if ((sb.st_mode & 0000022))
508 "%s writable by non-owner (0%o), should be mode 0700",
509 timestampdir, (unsigned int) sb.st_mode);
511 if ((sb.st_mode & 0000777) != 0700)
512 (void) chmod(timestampdir, 0700);
513 status = TS_OLD; /* do date check later */
515 } else if (errno != ENOENT) {
516 log_error(NO_EXIT|USE_ERRNO, "can't stat %s", timestampdir);
521 * If there is no user ticket dir, AND we are in tty ticket mode,
522 * AND the TS_MAKE_DIRS flag is set, create the user ticket dir.
524 if (status == TS_MISSING && timestampfile && ISSET(flags, TS_MAKE_DIRS)) {
525 if (mkdir(timestampdir, S_IRWXU) == -1) {
527 log_error(NO_EXIT|USE_ERRNO, "can't mkdir %s", timestampdir);
532 * Sanity check the tty ticket file if it exists.
534 if (timestampfile && status != TS_ERROR) {
535 if (status != TS_MISSING)
536 status = TS_NOFILE; /* dir there, file missing */
537 if (def_tty_tickets && !user_ttypath)
538 goto done; /* no tty, always prompt */
539 if (lstat(timestampfile, &sb) == 0) {
540 if (!S_ISREG(sb.st_mode)) {
542 log_error(NO_EXIT, "%s exists but is not a regular file (0%o)",
543 timestampfile, (unsigned int) sb.st_mode);
545 /* If bad uid or file mode, complain and kill the bogus file. */
546 if (sb.st_uid != timestamp_uid) {
548 "%s owned by uid %lu, should be uid %lu",
549 timestampfile, (unsigned long) sb.st_uid,
550 (unsigned long) timestamp_uid);
551 (void) unlink(timestampfile);
552 } else if ((sb.st_mode & 0000022)) {
554 "%s writable by non-owner (0%o), should be mode 0600",
555 timestampfile, (unsigned int) sb.st_mode);
556 (void) unlink(timestampfile);
558 /* If not mode 0600, fix it. */
559 if ((sb.st_mode & 0000777) != 0600)
560 (void) chmod(timestampfile, 0600);
563 * Check for stored tty info. If the file is zero-sized
564 * it is an old-style timestamp with no tty info in it.
565 * If removing, we don't care about the contents.
566 * The actual mtime check is done later.
568 if (ISSET(flags, TS_REMOVE)) {
570 } else if (sb.st_size != 0) {
571 struct tty_info info;
572 int fd = open(timestampfile, O_RDONLY, 0644);
574 if (read(fd, &info, sizeof(info)) == sizeof(info) &&
575 memcmp(&info, &tty_info, sizeof(info)) == 0) {
583 } else if (errno != ENOENT) {
584 log_error(NO_EXIT|USE_ERRNO, "can't stat %s", timestampfile);
590 * If the file/dir exists and we are not removing it, check its mtime.
592 if (status == TS_OLD && !ISSET(flags, TS_REMOVE)) {
593 mtim_get(&sb, &mtime);
594 /* Negative timeouts only expire manually (sudo -k). */
595 if (def_timestamp_timeout < 0 && mtime.tv_sec != 0)
599 if (def_timestamp_timeout &&
600 now - mtime.tv_sec < 60 * def_timestamp_timeout) {
602 * Check for bogus time on the stampfile. The clock may
603 * have been set back or someone could be trying to spoof us.
605 if (mtime.tv_sec > now + 60 * def_timestamp_timeout * 2) {
606 time_t tv_sec = (time_t)mtime.tv_sec;
608 "timestamp too far in the future: %20.20s",
611 (void) unlink(timestampfile);
613 (void) rmdir(timestampdir);
615 } else if (get_boottime(&boottime) && timevalcmp(&mtime, &boottime, <)) {
625 if (timestamp_uid != 0)
626 set_perms(PERM_ROOT);
631 * Remove the timestamp ticket file/dir.
634 remove_timestamp(remove)
638 char *timestampdir, *timestampfile, *path;
641 build_timestamp(×tampdir, ×tampfile);
642 status = timestamp_status(timestampdir, timestampfile, user_name,
644 if (status == TS_OLD || status == TS_CURRENT) {
645 path = timestampfile ? timestampfile : timestampdir;
648 status = unlink(timestampfile);
650 status = rmdir(timestampdir);
651 if (status == -1 && errno != ENOENT) {
652 log_error(NO_EXIT, "can't remove %s (%s), will reset to Epoch",
653 path, strerror(errno));
658 if (touch(-1, path, &tv) == -1 && errno != ENOENT)
659 error(1, "can't reset %s to Epoch", path);
664 efree(timestampfile);
668 * Returns TRUE if tty lives on a devpts or /devices filesystem, else FALSE.
669 * Unlike most filesystems, the ctime of devpts nodes is not updated when
670 * the device node is written to, only when the inode's status changes,
671 * typically via the chmod, chown, link, rename, or utimes system calls.
672 * Since the ctime is "stable" in this case, we can stash it the tty ticket
673 * file and use it to determine whether the tty ticket file is stale.
683 #ifndef DEVPTS_SUPER_MAGIC
684 # define DEVPTS_SUPER_MAGIC 0x1cd1
687 if (statfs(tty, &sfs) == 0) {
688 if (sfs.f_type == DEVPTS_SUPER_MAGIC)
691 #elif defined(__sun) && defined(__SVR4)
694 if (statvfs(tty, &sfs) == 0) {
695 if (strcmp(sfs.f_fstr, "devices") == 0)
698 #endif /* __linux__ */