2 * Copyright (c) 1993-1996,1998-2005, 2007-2011
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 int build_timestamp(char **, char **);
88 static int timestamp_status(char *, char *, char *, int);
89 static char *expand_prompt(char *, char *, char *);
90 static void lecture(int);
91 static void update_timestamp(char *, char *);
92 static bool tty_is_devpts(const char *);
93 static struct passwd *get_authpw(void);
96 * Returns true if the user successfully authenticates, else false.
99 check_user(int validated, int mode)
101 struct passwd *auth_pw;
102 char *timestampdir = NULL;
103 char *timestampfile = NULL;
106 int status, rval = true;
107 bool need_pass = def_authenticate;
108 debug_decl(check_user, SUDO_DEBUG_AUTH)
111 * Init authentication system regardless of whether we need a password.
112 * Required for proper PAM session support.
114 auth_pw = get_authpw();
115 if (sudo_auth_init(auth_pw) == -1) {
121 /* Always need a password when -k was specified with the command. */
122 if (ISSET(mode, MODE_IGNORE_TICKET)) {
123 SET(validated, FLAG_CHECK_USER);
126 * Don't prompt for the root passwd or if the user is exempt.
127 * If the user is not changing uid/gid, no need for a password.
129 if (user_uid == 0 || (user_uid == runas_pw->pw_uid &&
130 (!runas_gr || user_in_group(sudo_user.pw, runas_gr->gr_name)))
138 /* Stash the tty's ctime for tty ticket comparison. */
139 if (def_tty_tickets && user_ttypath && stat(user_ttypath, &sb) == 0) {
140 tty_info.dev = sb.st_dev;
141 tty_info.ino = sb.st_ino;
142 tty_info.rdev = sb.st_rdev;
143 if (tty_is_devpts(user_ttypath))
144 ctim_get(&sb, &tty_info.ctime);
147 if (build_timestamp(×tampdir, ×tampfile) == -1) {
152 status = timestamp_status(timestampdir, timestampfile, user_name,
155 if (status != TS_CURRENT || ISSET(validated, FLAG_CHECK_USER)) {
156 /* Bail out if we are non-interactive and a password is required */
157 if (ISSET(mode, MODE_NONINTERACTIVE)) {
158 warningx(_("sorry, a password is required to run %s"), getprogname());
163 /* XXX - should not lecture if askpass helper is being used. */
166 /* Expand any escapes in the prompt. */
167 prompt = expand_prompt(user_prompt ? user_prompt : def_passprompt,
168 user_name, user_shost);
170 rval = verify_user(auth_pw, prompt);
172 /* Only update timestamp if user was validated. */
173 if (rval == true && ISSET(validated, VALIDATE_OK) &&
174 !ISSET(mode, MODE_IGNORE_TICKET) && status != TS_ERROR)
175 update_timestamp(timestampdir, timestampfile);
177 efree(timestampfile);
180 sudo_auth_cleanup(auth_pw);
183 debug_return_bool(rval);
186 #define DEFAULT_LECTURE "\n" \
187 "We trust you have received the usual lecture from the local System\n" \
188 "Administrator. It usually boils down to these three things:\n\n" \
189 " #1) Respect the privacy of others.\n" \
190 " #2) Think before you type.\n" \
191 " #3) With great power comes great responsibility.\n\n"
194 * Standard sudo lecture.
202 struct sudo_conv_message msg;
203 struct sudo_conv_reply repl;
204 debug_decl(lecture, SUDO_DEBUG_AUTH)
206 if (def_lecture == never ||
207 (def_lecture == once && status != TS_MISSING && status != TS_ERROR))
210 memset(&msg, 0, sizeof(msg));
211 memset(&repl, 0, sizeof(repl));
213 if (def_lecture_file && (fp = fopen(def_lecture_file, "r")) != NULL) {
214 while ((nread = fread(buf, sizeof(char), sizeof(buf) - 1, fp)) != 0) {
216 msg.msg_type = SUDO_CONV_ERROR_MSG;
218 sudo_conv(1, &msg, &repl);
222 msg.msg_type = SUDO_CONV_ERROR_MSG;
223 msg.msg = _(DEFAULT_LECTURE);
224 sudo_conv(1, &msg, &repl);
230 * Update the time on the timestamp file/dir or create it if necessary.
233 update_timestamp(char *timestampdir, char *timestampfile)
235 debug_decl(update_timestamp, SUDO_DEBUG_AUTH)
237 /* If using tty timestamps but we have no tty there is nothing to do. */
238 if (def_tty_tickets && !user_ttypath)
241 if (timestamp_uid != 0)
242 set_perms(PERM_TIMESTAMP);
245 * Store tty info in timestamp file
247 int fd = open(timestampfile, O_WRONLY|O_CREAT, 0600);
249 log_error(NO_EXIT|USE_ERRNO, _("unable to open %s"), timestampfile);
251 lock_file(fd, SUDO_LOCK);
252 if (write(fd, &tty_info, sizeof(tty_info)) != sizeof(tty_info)) {
253 log_error(NO_EXIT|USE_ERRNO, _("unable to write to %s"),
259 if (touch(-1, timestampdir, NULL) == -1) {
260 if (mkdir(timestampdir, 0700) == -1) {
261 log_error(NO_EXIT|USE_ERRNO, _("unable to mkdir %s"),
266 if (timestamp_uid != 0)
272 * Expand %h and %u escapes in the prompt and pass back the dynamically
273 * allocated result. Returns the same string if there are no escapes.
276 expand_prompt(char *old_prompt, char *user, char *host)
280 char *p, *np, *new_prompt, *endp;
281 debug_decl(expand_prompt, SUDO_DEBUG_AUTH)
283 /* How much space do we need to malloc for the prompt? */
285 for (p = old_prompt, len = strlen(old_prompt); *p; p++) {
290 len += strlen(user_shost) - 2;
295 len += strlen(user_host) - 2;
302 else if (def_targetpw || def_runaspw)
303 len += strlen(runas_pw->pw_name) - 2;
305 len += strlen(user_name) - 2;
310 len += strlen(user_name) - 2;
315 len += strlen(runas_pw->pw_name) - 2;
330 new_prompt = emalloc(++len);
331 endp = new_prompt + len;
332 for (p = old_prompt, np = new_prompt; *p; p++) {
337 n = strlcpy(np, user_shost, np - endp);
344 n = strlcpy(np, user_host, np - endp);
352 n = strlcpy(np, "root", np - endp);
353 else if (def_targetpw || def_runaspw)
354 n = strlcpy(np, runas_pw->pw_name, np - endp);
356 n = strlcpy(np, user_name, np - endp);
363 n = strlcpy(np, user_name, np - endp);
370 n = strlcpy(np, runas_pw->pw_name, np - endp);
376 /* convert %% -> % */
390 new_prompt = old_prompt;
392 debug_return_str(new_prompt);
395 /* We pre-allocate enough space, so this should never happen. */
396 errorx(1, _("internal error, expand_prompt() overflow"));
400 * Checks if the user is exempt from supplying a password.
406 debug_decl(user_is_exempt, SUDO_DEBUG_AUTH)
408 if (def_exempt_group)
409 rval = user_in_group(sudo_user.pw, def_exempt_group);
410 debug_return_bool(rval);
414 * Fills in timestampdir as well as timestampfile if using tty tickets.
417 build_timestamp(char **timestampdir, char **timestampfile)
421 debug_decl(build_timestamp, SUDO_DEBUG_AUTH)
423 dirparent = def_timestampdir;
424 len = easprintf(timestampdir, "%s/%s", dirparent, user_name);
429 * Timestamp file may be a file in the directory or NUL to use
430 * the directory as the timestamp.
432 if (def_tty_tickets) {
435 if ((p = strrchr(user_tty, '/')))
440 len = easprintf(timestampfile, "%s/%s/%s:%s", dirparent, user_name,
441 p, runas_pw->pw_name);
443 len = easprintf(timestampfile, "%s/%s/%s", dirparent, user_name, p);
446 } else if (def_targetpw) {
447 len = easprintf(timestampfile, "%s/%s/%s", dirparent, user_name,
452 *timestampfile = NULL;
454 debug_return_int(len);
456 log_error(0, _("timestamp path too long: %s"), *timestampfile);
457 debug_return_int(-1);
461 * Check the timestamp file and directory and return their status.
464 timestamp_status(char *timestampdir, char *timestampfile, char *user, int flags)
467 struct timeval boottime, mtime;
469 char *dirparent = def_timestampdir;
470 int status = TS_ERROR; /* assume the worst */
471 debug_decl(timestamp_status, SUDO_DEBUG_AUTH)
473 if (timestamp_uid != 0)
474 set_perms(PERM_TIMESTAMP);
477 * Sanity check dirparent and make it if it doesn't already exist.
478 * We start out assuming the worst (that the dir is not sane) and
479 * if it is ok upgrade the status to ``no timestamp file''.
480 * Note that we don't check the parent(s) of dirparent for
481 * sanity since the sudo dir is often just located in /tmp.
483 if (lstat(dirparent, &sb) == 0) {
484 if (!S_ISDIR(sb.st_mode))
485 log_error(NO_EXIT, _("%s exists but is not a directory (0%o)"),
486 dirparent, (unsigned int) sb.st_mode);
487 else if (sb.st_uid != timestamp_uid)
488 log_error(NO_EXIT, _("%s owned by uid %u, should be uid %u"),
489 dirparent, (unsigned int) sb.st_uid,
490 (unsigned int) timestamp_uid);
491 else if ((sb.st_mode & 0000022))
493 _("%s writable by non-owner (0%o), should be mode 0700"),
494 dirparent, (unsigned int) sb.st_mode);
496 if ((sb.st_mode & 0000777) != 0700)
497 (void) chmod(dirparent, 0700);
500 } else if (errno != ENOENT) {
501 log_error(NO_EXIT|USE_ERRNO, _("unable to stat %s"), dirparent);
503 /* No dirparent, try to make one. */
504 if (ISSET(flags, TS_MAKE_DIRS)) {
505 if (mkdir(dirparent, S_IRWXU))
506 log_error(NO_EXIT|USE_ERRNO, _("unable to mkdir %s"),
512 if (status == TS_ERROR)
516 * Sanity check the user's ticket dir. We start by downgrading
517 * the status to TS_ERROR. If the ticket dir exists and is sane
518 * this will be upgraded to TS_OLD. If the dir does not exist,
519 * it will be upgraded to TS_MISSING.
521 status = TS_ERROR; /* downgrade status again */
522 if (lstat(timestampdir, &sb) == 0) {
523 if (!S_ISDIR(sb.st_mode)) {
524 if (S_ISREG(sb.st_mode)) {
525 /* convert from old style */
526 if (unlink(timestampdir) == 0)
529 log_error(NO_EXIT, _("%s exists but is not a directory (0%o)"),
530 timestampdir, (unsigned int) sb.st_mode);
531 } else if (sb.st_uid != timestamp_uid)
532 log_error(NO_EXIT, _("%s owned by uid %u, should be uid %u"),
533 timestampdir, (unsigned int) sb.st_uid,
534 (unsigned int) timestamp_uid);
535 else if ((sb.st_mode & 0000022))
537 _("%s writable by non-owner (0%o), should be mode 0700"),
538 timestampdir, (unsigned int) sb.st_mode);
540 if ((sb.st_mode & 0000777) != 0700)
541 (void) chmod(timestampdir, 0700);
542 status = TS_OLD; /* do date check later */
544 } else if (errno != ENOENT) {
545 log_error(NO_EXIT|USE_ERRNO, _("unable to stat %s"), timestampdir);
550 * If there is no user ticket dir, AND we are in tty ticket mode,
551 * AND the TS_MAKE_DIRS flag is set, create the user ticket dir.
553 if (status == TS_MISSING && timestampfile && ISSET(flags, TS_MAKE_DIRS)) {
554 if (mkdir(timestampdir, S_IRWXU) == -1) {
556 log_error(NO_EXIT|USE_ERRNO, _("unable to mkdir %s"), timestampdir);
561 * Sanity check the tty ticket file if it exists.
563 if (timestampfile && status != TS_ERROR) {
564 if (status != TS_MISSING)
565 status = TS_NOFILE; /* dir there, file missing */
566 if (def_tty_tickets && !user_ttypath)
567 goto done; /* no tty, always prompt */
568 if (lstat(timestampfile, &sb) == 0) {
569 if (!S_ISREG(sb.st_mode)) {
571 log_error(NO_EXIT, _("%s exists but is not a regular file (0%o)"),
572 timestampfile, (unsigned int) sb.st_mode);
574 /* If bad uid or file mode, complain and kill the bogus file. */
575 if (sb.st_uid != timestamp_uid) {
577 _("%s owned by uid %u, should be uid %u"),
578 timestampfile, (unsigned int) sb.st_uid,
579 (unsigned int) timestamp_uid);
580 (void) unlink(timestampfile);
581 } else if ((sb.st_mode & 0000022)) {
583 _("%s writable by non-owner (0%o), should be mode 0600"),
584 timestampfile, (unsigned int) sb.st_mode);
585 (void) unlink(timestampfile);
587 /* If not mode 0600, fix it. */
588 if ((sb.st_mode & 0000777) != 0600)
589 (void) chmod(timestampfile, 0600);
592 * Check for stored tty info. If the file is zero-sized
593 * it is an old-style timestamp with no tty info in it.
594 * If removing, we don't care about the contents.
595 * The actual mtime check is done later.
597 if (ISSET(flags, TS_REMOVE)) {
599 } else if (sb.st_size != 0) {
600 struct tty_info info;
601 int fd = open(timestampfile, O_RDONLY, 0644);
603 if (read(fd, &info, sizeof(info)) == sizeof(info) &&
604 memcmp(&info, &tty_info, sizeof(info)) == 0) {
612 } else if (errno != ENOENT) {
613 log_error(NO_EXIT|USE_ERRNO, _("unable to stat %s"), timestampfile);
619 * If the file/dir exists and we are not removing it, check its mtime.
621 if (status == TS_OLD && !ISSET(flags, TS_REMOVE)) {
622 mtim_get(&sb, &mtime);
623 /* Negative timeouts only expire manually (sudo -k). */
624 if (def_timestamp_timeout < 0 && mtime.tv_sec != 0)
628 if (def_timestamp_timeout &&
629 now - mtime.tv_sec < 60 * def_timestamp_timeout) {
631 * Check for bogus time on the stampfile. The clock may
632 * have been set back or someone could be trying to spoof us.
634 if (mtime.tv_sec > now + 60 * def_timestamp_timeout * 2) {
635 time_t tv_sec = (time_t)mtime.tv_sec;
637 _("timestamp too far in the future: %20.20s"),
640 (void) unlink(timestampfile);
642 (void) rmdir(timestampdir);
644 } else if (get_boottime(&boottime) && timevalcmp(&mtime, &boottime, <)) {
654 if (timestamp_uid != 0)
656 debug_return_int(status);
660 * Remove the timestamp ticket file/dir.
663 remove_timestamp(bool remove)
666 char *timestampdir, *timestampfile, *path;
668 debug_decl(remove_timestamp, SUDO_DEBUG_AUTH)
670 if (build_timestamp(×tampdir, ×tampfile) == -1)
673 status = timestamp_status(timestampdir, timestampfile, user_name,
675 if (status != TS_MISSING && status != TS_ERROR) {
676 path = timestampfile ? timestampfile : timestampdir;
679 status = unlink(timestampfile);
681 status = rmdir(timestampdir);
682 if (status == -1 && errno != ENOENT) {
684 _("unable to remove %s (%s), will reset to the epoch"),
685 path, strerror(errno));
691 if (touch(-1, path, &tv) == -1 && errno != ENOENT)
692 error(1, _("unable to reset %s to the epoch"), path);
696 efree(timestampfile);
702 * Returns true if tty lives on a devpts or /devices filesystem, else false.
703 * Unlike most filesystems, the ctime of devpts nodes is not updated when
704 * the device node is written to, only when the inode's status changes,
705 * typically via the chmod, chown, link, rename, or utimes system calls.
706 * Since the ctime is "stable" in this case, we can stash it the tty ticket
707 * file and use it to determine whether the tty ticket file is stale.
710 tty_is_devpts(const char *tty)
715 debug_decl(tty_is_devpts, SUDO_DEBUG_PTY)
717 #ifndef DEVPTS_SUPER_MAGIC
718 # define DEVPTS_SUPER_MAGIC 0x1cd1
721 if (statfs(tty, &sfs) == 0) {
722 if (sfs.f_type == DEVPTS_SUPER_MAGIC)
725 #elif defined(__sun) && defined(__SVR4)
727 debug_decl(tty_is_devpts, SUDO_DEBUG_PTY)
729 if (statvfs(tty, &sfs) == 0) {
730 if (strcmp(sfs.f_fstr, "devices") == 0)
734 debug_decl(tty_is_devpts, SUDO_DEBUG_PTY)
735 #endif /* __linux__ */
736 debug_return_bool(retval);
740 * Get passwd entry for the user we are going to authenticate as.
741 * By default, this is the user invoking sudo. In the most common
742 * case, this matches sudo_user.pw or runas_pw.
744 static struct passwd *
748 debug_decl(get_authpw, SUDO_DEBUG_AUTH)
751 if ((pw = sudo_getpwuid(ROOT_UID)) == NULL)
752 log_error(0, _("unknown uid: %u"), ROOT_UID);
753 } else if (def_runaspw) {
754 if ((pw = sudo_getpwnam(def_runas_default)) == NULL)
755 log_error(0, _("unknown user: %s"), def_runas_default);
756 } else if (def_targetpw) {
757 if (runas_pw->pw_name == NULL)
758 log_error(NO_MAIL|MSG_ONLY, _("unknown uid: %u"),
759 (unsigned int) runas_pw->pw_uid);
763 pw_addref(sudo_user.pw);
767 debug_return_ptr(pw);