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);
122 if (user_uid == 0 || user_uid == runas_pw->pw_uid || user_is_exempt())
126 build_timestamp(×tampdir, ×tampfile);
127 status = timestamp_status(timestampdir, timestampfile, user_name,
130 if (status != TS_CURRENT || ISSET(validated, FLAG_CHECK_USER)) {
131 /* Bail out if we are non-interactive and a password is required */
132 if (ISSET(mode, MODE_NONINTERACTIVE))
133 errorx(1, "sorry, a password is required to run %s", getprogname());
135 /* If user specified -A, make sure we have an askpass helper. */
136 if (ISSET(tgetpass_flags, TGP_ASKPASS)) {
137 if (user_askpass == NULL)
139 "no askpass program specified, try setting SUDO_ASKPASS");
140 } else if (!ISSET(tgetpass_flags, TGP_STDIN)) {
141 /* If no tty but DISPLAY is set, use askpass if we have it. */
142 if (!user_ttypath && !tty_present()) {
143 if (user_askpass && user_display && *user_display != '\0') {
144 SET(tgetpass_flags, TGP_ASKPASS);
145 } else if (!def_visiblepw) {
147 "no tty present and no askpass program specified");
152 if (!ISSET(tgetpass_flags, TGP_ASKPASS))
155 /* Expand any escapes in the prompt. */
156 prompt = expand_prompt(user_prompt ? user_prompt : def_passprompt,
157 user_name, user_shost);
159 verify_user(auth_pw, prompt);
161 /* Only update timestamp if user was validated. */
162 if (ISSET(validated, VALIDATE_OK) && !ISSET(mode, MODE_INVALIDATE) && status != TS_ERROR)
163 update_timestamp(timestampdir, timestampfile);
165 efree(timestampfile);
169 * Standard sudo lecture.
179 if (def_lecture == never ||
180 (def_lecture == once && status != TS_MISSING && status != TS_ERROR))
183 if (def_lecture_file && (fp = fopen(def_lecture_file, "r")) != NULL) {
184 while ((nread = fread(buf, sizeof(char), sizeof(buf), fp)) != 0)
185 fwrite(buf, nread, 1, stderr);
189 We trust you have received the usual lecture from the local System\n\
190 Administrator. It usually boils down to these three things:\n\
192 #1) Respect the privacy of others.\n\
193 #2) Think before you type.\n\
194 #3) With great power comes great responsibility.\n\n",
200 * Update the time on the timestamp file/dir or create it if necessary.
203 update_timestamp(timestampdir, timestampfile)
207 /* If using tty timestamps but we have no tty there is nothing to do. */
208 if (timestampfile && !user_ttypath)
211 if (timestamp_uid != 0)
212 set_perms(PERM_TIMESTAMP);
215 * Store tty info in timestamp file
217 int fd = open(timestampfile, O_WRONLY|O_CREAT, 0600);
219 log_error(NO_EXIT|USE_ERRNO, "Can't open %s", timestampfile);
221 lock_file(fd, SUDO_LOCK);
222 write(fd, &tty_info, sizeof(tty_info));
226 if (touch(-1, timestampdir, NULL) == -1) {
227 if (mkdir(timestampdir, 0700) == -1)
228 log_error(NO_EXIT|USE_ERRNO, "Can't mkdir %s", timestampdir);
231 if (timestamp_uid != 0)
232 set_perms(PERM_ROOT);
236 * Expand %h and %u escapes in the prompt and pass back the dynamically
237 * allocated result. Returns the same string if there are no escapes.
240 expand_prompt(old_prompt, user, host)
247 char *p, *np, *new_prompt, *endp;
249 /* How much space do we need to malloc for the prompt? */
251 for (p = old_prompt, len = strlen(old_prompt); *p; p++) {
256 len += strlen(user_shost) - 2;
261 len += strlen(user_host) - 2;
268 else if (def_targetpw || def_runaspw)
269 len += strlen(runas_pw->pw_name) - 2;
271 len += strlen(user_name) - 2;
276 len += strlen(user_name) - 2;
281 len += strlen(runas_pw->pw_name) - 2;
296 new_prompt = (char *) emalloc(++len);
297 endp = new_prompt + len;
298 for (p = old_prompt, np = new_prompt; *p; p++) {
303 n = strlcpy(np, user_shost, np - endp);
310 n = strlcpy(np, user_host, np - endp);
318 n = strlcpy(np, "root", np - endp);
319 else if (def_targetpw || def_runaspw)
320 n = strlcpy(np, runas_pw->pw_name, np - endp);
322 n = strlcpy(np, user_name, np - endp);
329 n = strlcpy(np, user_name, np - endp);
336 n = strlcpy(np, runas_pw->pw_name, np - endp);
342 /* convert %% -> % */
356 new_prompt = old_prompt;
361 /* We pre-allocate enough space, so this should never happen. */
362 errorx(1, "internal error, expand_prompt() overflow");
366 * Checks if the user is exempt from supplying a password.
371 if (!def_exempt_group)
373 return(user_in_group(sudo_user.pw, def_exempt_group));
377 * Fills in timestampdir as well as timestampfile if using tty tickets.
380 build_timestamp(timestampdir, timestampfile)
382 char **timestampfile;
387 dirparent = def_timestampdir;
388 len = easprintf(timestampdir, "%s/%s", dirparent, user_name);
390 log_error(0, "timestamp path too long: %s", *timestampdir);
393 * Timestamp file may be a file in the directory or NUL to use
394 * the directory as the timestamp.
396 if (def_tty_tickets) {
399 if ((p = strrchr(user_tty, '/')))
404 len = easprintf(timestampfile, "%s/%s/%s:%s", dirparent, user_name,
405 p, runas_pw->pw_name);
407 len = easprintf(timestampfile, "%s/%s/%s", dirparent, user_name, p);
409 log_error(0, "timestamp path too long: %s", *timestampfile);
410 } else if (def_targetpw) {
411 len = easprintf(timestampfile, "%s/%s/%s", dirparent, user_name,
414 log_error(0, "timestamp path too long: %s", *timestampfile);
416 *timestampfile = NULL;
420 * Check the timestamp file and directory and return their status.
423 timestamp_status(timestampdir, timestampfile, user, flags)
430 struct timeval boottime, mtime;
432 char *dirparent = def_timestampdir;
433 int status = TS_ERROR; /* assume the worst */
435 if (timestamp_uid != 0)
436 set_perms(PERM_TIMESTAMP);
439 * Sanity check dirparent and make it if it doesn't already exist.
440 * We start out assuming the worst (that the dir is not sane) and
441 * if it is ok upgrade the status to ``no timestamp file''.
442 * Note that we don't check the parent(s) of dirparent for
443 * sanity since the sudo dir is often just located in /tmp.
445 if (lstat(dirparent, &sb) == 0) {
446 if (!S_ISDIR(sb.st_mode))
447 log_error(NO_EXIT, "%s exists but is not a directory (0%o)",
448 dirparent, (unsigned int) sb.st_mode);
449 else if (sb.st_uid != timestamp_uid)
450 log_error(NO_EXIT, "%s owned by uid %lu, should be uid %lu",
451 dirparent, (unsigned long) sb.st_uid,
452 (unsigned long) timestamp_uid);
453 else if ((sb.st_mode & 0000022))
455 "%s writable by non-owner (0%o), should be mode 0700",
456 dirparent, (unsigned int) sb.st_mode);
458 if ((sb.st_mode & 0000777) != 0700)
459 (void) chmod(dirparent, 0700);
462 } else if (errno != ENOENT) {
463 log_error(NO_EXIT|USE_ERRNO, "can't stat %s", dirparent);
465 /* No dirparent, try to make one. */
466 if (ISSET(flags, TS_MAKE_DIRS)) {
467 if (mkdir(dirparent, S_IRWXU))
468 log_error(NO_EXIT|USE_ERRNO, "can't mkdir %s",
474 if (status == TS_ERROR) {
475 if (timestamp_uid != 0)
476 set_perms(PERM_ROOT);
481 * Sanity check the user's ticket dir. We start by downgrading
482 * the status to TS_ERROR. If the ticket dir exists and is sane
483 * this will be upgraded to TS_OLD. If the dir does not exist,
484 * it will be upgraded to TS_MISSING.
486 status = TS_ERROR; /* downgrade status again */
487 if (lstat(timestampdir, &sb) == 0) {
488 if (!S_ISDIR(sb.st_mode)) {
489 if (S_ISREG(sb.st_mode)) {
490 /* convert from old style */
491 if (unlink(timestampdir) == 0)
494 log_error(NO_EXIT, "%s exists but is not a directory (0%o)",
495 timestampdir, (unsigned int) sb.st_mode);
496 } else if (sb.st_uid != timestamp_uid)
497 log_error(NO_EXIT, "%s owned by uid %lu, should be uid %lu",
498 timestampdir, (unsigned long) sb.st_uid,
499 (unsigned long) timestamp_uid);
500 else if ((sb.st_mode & 0000022))
502 "%s writable by non-owner (0%o), should be mode 0700",
503 timestampdir, (unsigned int) sb.st_mode);
505 if ((sb.st_mode & 0000777) != 0700)
506 (void) chmod(timestampdir, 0700);
507 status = TS_OLD; /* do date check later */
509 } else if (errno != ENOENT) {
510 log_error(NO_EXIT|USE_ERRNO, "can't stat %s", timestampdir);
515 * If there is no user ticket dir, AND we are in tty ticket mode,
516 * AND the TS_MAKE_DIRS flag is set, create the user ticket dir.
518 if (status == TS_MISSING && timestampfile && ISSET(flags, TS_MAKE_DIRS)) {
519 if (mkdir(timestampdir, S_IRWXU) == -1) {
521 log_error(NO_EXIT|USE_ERRNO, "can't mkdir %s", timestampdir);
526 * Sanity check the tty ticket file if it exists.
528 if (timestampfile && status != TS_ERROR) {
529 if (status != TS_MISSING)
530 status = TS_NOFILE; /* dir there, file missing */
532 goto done; /* no tty, always prompt */
533 if (lstat(timestampfile, &sb) == 0) {
534 if (!S_ISREG(sb.st_mode)) {
536 log_error(NO_EXIT, "%s exists but is not a regular file (0%o)",
537 timestampfile, (unsigned int) sb.st_mode);
539 /* If bad uid or file mode, complain and kill the bogus file. */
540 if (sb.st_uid != timestamp_uid) {
542 "%s owned by uid %lu, should be uid %lu",
543 timestampfile, (unsigned long) sb.st_uid,
544 (unsigned long) timestamp_uid);
545 (void) unlink(timestampfile);
546 } else if ((sb.st_mode & 0000022)) {
548 "%s writable by non-owner (0%o), should be mode 0600",
549 timestampfile, (unsigned int) sb.st_mode);
550 (void) unlink(timestampfile);
552 /* If not mode 0600, fix it. */
553 if ((sb.st_mode & 0000777) != 0600)
554 (void) chmod(timestampfile, 0600);
557 * Check for stored tty info. If the file is zero-sized
558 * it is an old-style timestamp with no tty info in it.
559 * If removing, we don't care about the contents.
560 * The actual mtime check is done later.
562 if (ISSET(flags, TS_REMOVE)) {
564 } else if (sb.st_size != 0) {
565 struct tty_info info;
566 int fd = open(timestampfile, O_RDONLY, 0644);
568 if (read(fd, &info, sizeof(info)) == sizeof(info) &&
569 memcmp(&info, &tty_info, sizeof(info)) == 0) {
577 } else if (errno != ENOENT) {
578 log_error(NO_EXIT|USE_ERRNO, "can't stat %s", timestampfile);
584 * If the file/dir exists and we are not removing it, check its mtime.
586 if (status == TS_OLD && !ISSET(flags, TS_REMOVE)) {
587 mtim_get(&sb, &mtime);
588 /* Negative timeouts only expire manually (sudo -k). */
589 if (def_timestamp_timeout < 0 && mtime.tv_sec != 0)
593 if (def_timestamp_timeout &&
594 now - mtime.tv_sec < 60 * def_timestamp_timeout) {
596 * Check for bogus time on the stampfile. The clock may
597 * have been set back or someone could be trying to spoof us.
599 if (mtime.tv_sec > now + 60 * def_timestamp_timeout * 2) {
600 time_t tv_sec = (time_t)mtime.tv_sec;
602 "timestamp too far in the future: %20.20s",
605 (void) unlink(timestampfile);
607 (void) rmdir(timestampdir);
609 } else if (get_boottime(&boottime) && timevalcmp(&mtime, &boottime, <)) {
619 if (timestamp_uid != 0)
620 set_perms(PERM_ROOT);
625 * Remove the timestamp ticket file/dir.
628 remove_timestamp(remove)
632 char *timestampdir, *timestampfile, *path;
635 build_timestamp(×tampdir, ×tampfile);
636 status = timestamp_status(timestampdir, timestampfile, user_name,
638 if (status == TS_OLD || status == TS_CURRENT) {
639 path = timestampfile ? timestampfile : timestampdir;
642 status = unlink(timestampfile);
644 status = rmdir(timestampdir);
645 if (status == -1 && errno != ENOENT) {
646 log_error(NO_EXIT, "can't remove %s (%s), will reset to Epoch",
647 path, strerror(errno));
652 if (touch(-1, path, &tv) == -1 && errno != ENOENT)
653 error(1, "can't reset %s to Epoch", path);
658 efree(timestampfile);
662 * Returns TRUE if tty lives on a devpts or /devices filesystem, else FALSE.
663 * Unlike most filesystems, the ctime of devpts nodes is not updated when
664 * the device node is written to, only when the inode's status changes,
665 * typically via the chmod, chown, link, rename, or utimes system calls.
666 * Since the ctime is "stable" in this case, we can stash it the tty ticket
667 * file and use it to determine whether the tty ticket file is stale.
677 #ifndef DEVPTS_SUPER_MAGIC
678 # define DEVPTS_SUPER_MAGIC 0x1cd1
681 if (statfs(tty, &sfs) == 0) {
682 if (sfs.f_type == DEVPTS_SUPER_MAGIC)
685 #elif defined(__sun) && defined(__SVR4)
688 if (statvfs(tty, &sfs) == 0) {
689 if (strcmp(sfs.f_fstr, "devices") == 0)
692 #endif /* __linux__ */