1 /*
2  * SPDX-License-Identifier: ISC
3  *
4  * Copyright (c) 1993-1996,1998-2005, 2007-2018
5  *	Todd C. Miller <Todd.Miller@sudo.ws>
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  *
19  * Sponsored in part by the Defense Advanced Research Projects
20  * Agency (DARPA) and Air Force Research Laboratory, Air Force
21  * Materiel Command, USAF, under agreement number F39502-99-1-0512.
22  */
23 
24 /*
25  * This is an open source non-commercial project. Dear PVS-Studio, please check it.
26  * PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
27  */
28 
29 #include <config.h>
30 
31 #include <sys/types.h>			/* for ssize_t */
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <fcntl.h>
37 #include <time.h>
38 #include <errno.h>
39 #include <pwd.h>
40 #include <grp.h>
41 
42 #include "sudoers.h"
43 #include "check.h"
44 
45 static bool display_lecture(int);
46 static struct passwd *get_authpw(int);
47 
48 struct getpass_closure {
49     int tstat;
50     void *cookie;
51     struct passwd *auth_pw;
52 };
53 
54 /*
55  * Called when getpass is suspended so we can drop the lock.
56  */
57 static int
getpass_suspend(int signo,void * vclosure)58 getpass_suspend(int signo, void *vclosure)
59 {
60     struct getpass_closure *closure = vclosure;
61 
62     timestamp_close(closure->cookie);
63     closure->cookie = NULL;
64     return 0;
65 }
66 
67 /*
68  * Called when getpass is resumed so we can reacquire the lock.
69  */
70 static int
getpass_resume(int signo,void * vclosure)71 getpass_resume(int signo, void *vclosure)
72 {
73     struct getpass_closure *closure = vclosure;
74 
75     closure->cookie = timestamp_open(user_name, user_sid);
76     if (closure->cookie == NULL)
77 	return -1;
78     if (!timestamp_lock(closure->cookie, closure->auth_pw))
79 	return -1;
80     return 0;
81 }
82 
83 /*
84  * Returns true if the user successfully authenticates, false if not
85  * or -1 on fatal error.
86  */
87 static int
check_user_interactive(int validated,int mode,struct getpass_closure * closure)88 check_user_interactive(int validated, int mode, struct getpass_closure *closure)
89 {
90     struct sudo_conv_callback cb, *callback = NULL;
91     int ret = -1;
92     char *prompt;
93     bool lectured;
94     debug_decl(check_user_interactive, SUDOERS_DEBUG_AUTH);
95 
96     /* Open, lock and read time stamp file if we are using it. */
97     if (!ISSET(mode, MODE_IGNORE_TICKET)) {
98 	/* Open time stamp file and check its status. */
99 	closure->cookie = timestamp_open(user_name, user_sid);
100 	if (timestamp_lock(closure->cookie, closure->auth_pw))
101 	    closure->tstat = timestamp_status(closure->cookie, closure->auth_pw);
102 
103 	/* Construct callback for getpass function. */
104 	memset(&cb, 0, sizeof(cb));
105 	cb.version = SUDO_CONV_CALLBACK_VERSION;
106 	cb.closure = closure;
107 	cb.on_suspend = getpass_suspend;
108 	cb.on_resume = getpass_resume;
109 	callback = &cb;
110     }
111 
112     switch (closure->tstat) {
113     case TS_FATAL:
114 	/* Fatal error (usually setuid failure), unsafe to proceed. */
115 	goto done;
116 
117     case TS_CURRENT:
118 	/* Time stamp file is valid and current. */
119 	if (!ISSET(validated, FLAG_CHECK_USER)) {
120 	    ret = true;
121 	    break;
122 	}
123 	sudo_debug_printf(SUDO_DEBUG_INFO,
124 	    "%s: check user flag overrides time stamp", __func__);
125 	FALLTHROUGH;
126 
127     default:
128 	/* Bail out if we are non-interactive and a password is required */
129 	if (ISSET(mode, MODE_NONINTERACTIVE)) {
130 	    validated |= FLAG_NON_INTERACTIVE;
131 	    log_auth_failure(validated, 0);
132 	    goto done;
133 	}
134 
135 	/* XXX - should not lecture if askpass helper is being used. */
136 	lectured = display_lecture(closure->tstat);
137 
138 	/* Expand any escapes in the prompt. */
139 	prompt = expand_prompt(user_prompt ? user_prompt : def_passprompt,
140 	    closure->auth_pw->pw_name);
141 	if (prompt == NULL)
142 	    goto done;
143 
144 	ret = verify_user(closure->auth_pw, prompt, validated, callback);
145 	if (ret == true && lectured)
146 	    (void)set_lectured();	/* lecture error not fatal */
147 	free(prompt);
148 	break;
149     }
150 
151 done:
152     debug_return_int(ret);
153 }
154 
155 /*
156  * Returns true if the user successfully authenticates, false if not
157  * or -1 on error.
158  */
159 int
check_user(int validated,int mode)160 check_user(int validated, int mode)
161 {
162     struct getpass_closure closure = { TS_ERROR };
163     int ret = -1;
164     bool exempt = false;
165     debug_decl(check_user, SUDOERS_DEBUG_AUTH);
166 
167     /*
168      * Init authentication system regardless of whether we need a password.
169      * Required for proper PAM session support.
170      */
171     if ((closure.auth_pw = get_authpw(mode)) == NULL)
172 	goto done;
173     if (sudo_auth_init(closure.auth_pw) == -1)
174 	goto done;
175 
176     /*
177      * Don't prompt for the root passwd or if the user is exempt.
178      * If the user is not changing uid/gid, no need for a password.
179      */
180     if (!def_authenticate || user_is_exempt()) {
181 	sudo_debug_printf(SUDO_DEBUG_INFO, "%s: %s", __func__,
182 	    !def_authenticate ? "authentication disabled" :
183 	    "user exempt from authentication");
184 	exempt = true;
185 	ret = true;
186 	goto done;
187     }
188     if (user_uid == 0 || (user_uid == runas_pw->pw_uid &&
189 	(!runas_gr || user_in_group(sudo_user.pw, runas_gr->gr_name)))) {
190 #ifdef HAVE_SELINUX
191 	if (user_role == NULL && user_type == NULL)
192 #endif
193 #ifdef HAVE_PRIV_SET
194 	if (runas_privs == NULL && runas_limitprivs == NULL)
195 #endif
196 	{
197 	    sudo_debug_printf(SUDO_DEBUG_INFO,
198 		"%s: user running command as self", __func__);
199 	    ret = true;
200 	    goto done;
201 	}
202     }
203 
204     ret = check_user_interactive(validated, mode, &closure);
205 
206 done:
207     if (ret == true) {
208 	/* The approval function may disallow a user post-authentication. */
209 	ret = sudo_auth_approval(closure.auth_pw, validated, exempt);
210 
211 	/*
212 	 * Only update time stamp if user validated and was approved.
213 	 * Failure to update the time stamp is not a fatal error.
214 	 */
215 	if (ret == true && closure.tstat != TS_ERROR) {
216 	    if (ISSET(validated, VALIDATE_SUCCESS))
217 		(void)timestamp_update(closure.cookie, closure.auth_pw);
218 	}
219     }
220     timestamp_close(closure.cookie);
221     sudo_auth_cleanup(closure.auth_pw, !ISSET(validated, VALIDATE_SUCCESS));
222     if (closure.auth_pw != NULL)
223 	sudo_pw_delref(closure.auth_pw);
224 
225     debug_return_int(ret);
226 }
227 
228 /*
229  * Display sudo lecture (standard or custom).
230  * Returns true if the user was lectured, else false.
231  */
232 static bool
display_lecture(int status)233 display_lecture(int status)
234 {
235     struct sudo_conv_message msg;
236     struct sudo_conv_reply repl;
237     char buf[BUFSIZ];
238     struct stat sb;
239     ssize_t nread;
240     int fd;
241     debug_decl(lecture, SUDOERS_DEBUG_AUTH);
242 
243     if (def_lecture == never ||
244 	(def_lecture == once && already_lectured(status)))
245 	debug_return_bool(false);
246 
247     memset(&msg, 0, sizeof(msg));
248     memset(&repl, 0, sizeof(repl));
249 
250     if (def_lecture_file) {
251 	fd = open(def_lecture_file, O_RDONLY|O_NONBLOCK);
252 	if (fd != -1 && fstat(fd, &sb) == 0) {
253 	    if (S_ISREG(sb.st_mode)) {
254 		(void) fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) & ~O_NONBLOCK);
255 		while ((nread = read(fd, buf, sizeof(buf) - 1)) > 0) {
256 		    buf[nread] = '\0';
257 		    msg.msg_type = SUDO_CONV_ERROR_MSG|SUDO_CONV_PREFER_TTY;
258 		    msg.msg = buf;
259 		    sudo_conv(1, &msg, &repl, NULL);
260 		}
261 		close(fd);
262 		if (nread == -1) {
263 		    log_warning(SLOG_RAW_MSG,
264 			N_("error reading lecture file %s"), def_lecture_file);
265 		    debug_return_bool(false);
266 		}
267 		debug_return_bool(true);
268 	    } else {
269 		log_warningx(SLOG_RAW_MSG,
270 		    N_("ignoring lecture file %s: not a regular file"),
271 		    def_lecture_file);
272 	    }
273 	} else {
274 	    log_warning(SLOG_RAW_MSG|SLOG_NO_STDERR, N_("unable to open %s"),
275 		def_lecture_file);
276 	}
277 	if (fd != -1)
278 	    close(fd);
279     }
280 
281     /* Default sudo lecture. */
282     msg.msg_type = SUDO_CONV_ERROR_MSG|SUDO_CONV_PREFER_TTY;
283     msg.msg = _("\n"
284 	"We trust you have received the usual lecture from the local System\n"
285 	"Administrator. It usually boils down to these three things:\n\n"
286 	"    #1) Respect the privacy of others.\n"
287 	"    #2) Think before you type.\n"
288 	"    #3) With great power comes great responsibility.\n\n");
289     sudo_conv(1, &msg, &repl, NULL);
290     debug_return_bool(true);
291 }
292 
293 /*
294  * Checks if the user is exempt from supplying a password.
295  */
296 bool
user_is_exempt(void)297 user_is_exempt(void)
298 {
299     bool ret = false;
300     debug_decl(user_is_exempt, SUDOERS_DEBUG_AUTH);
301 
302     if (ISSET(sudo_mode, MODE_POLICY_INTERCEPTED)) {
303 	if (!def_intercept_authenticate)
304 	    ret = true;
305     }
306     if (def_exempt_group) {
307 	if (user_in_group(sudo_user.pw, def_exempt_group))
308 	    ret = true;
309     }
310     debug_return_bool(ret);
311 }
312 
313 /*
314  * Get passwd entry for the user we are going to authenticate as.
315  * By default, this is the user invoking sudo.  In the most common
316  * case, this matches sudo_user.pw or runas_pw.
317  */
318 static struct passwd *
get_authpw(int mode)319 get_authpw(int mode)
320 {
321     struct passwd *pw = NULL;
322     debug_decl(get_authpw, SUDOERS_DEBUG_AUTH);
323 
324     if (ISSET(mode, (MODE_CHECK|MODE_LIST))) {
325 	/* In list mode we always prompt for the user's password. */
326 	sudo_pw_addref(sudo_user.pw);
327 	pw = sudo_user.pw;
328     } else {
329 	if (def_rootpw) {
330 	    if ((pw = sudo_getpwuid(ROOT_UID)) == NULL) {
331 		log_warningx(SLOG_SEND_MAIL, N_("unknown uid %u"), ROOT_UID);
332 	    }
333 	} else if (def_runaspw) {
334 	    if ((pw = sudo_getpwnam(def_runas_default)) == NULL) {
335 		log_warningx(SLOG_SEND_MAIL,
336 		    N_("unknown user %s"), def_runas_default);
337 	    }
338 	} else if (def_targetpw) {
339 	    if (runas_pw->pw_name == NULL) {
340 		/* This should never be NULL as we fake up the passwd struct */
341 		log_warningx(SLOG_RAW_MSG, N_("unknown uid %u"),
342 		    (unsigned int) runas_pw->pw_uid);
343 	    } else {
344 		sudo_pw_addref(runas_pw);
345 		pw = runas_pw;
346 	    }
347 	} else {
348 	    sudo_pw_addref(sudo_user.pw);
349 	    pw = sudo_user.pw;
350 	}
351     }
352 
353     debug_return_ptr(pw);
354 }
355 
356 /*
357  * Returns true if the specified shell is allowed by /etc/shells, else false.
358  */
359 bool
check_user_shell(const struct passwd * pw)360 check_user_shell(const struct passwd *pw)
361 {
362     const char *shell;
363     debug_decl(check_user_shell, SUDOERS_DEBUG_AUTH);
364 
365     if (!def_runas_check_shell)
366 	debug_return_bool(true);
367 
368     sudo_debug_printf(SUDO_DEBUG_INFO,
369 	"%s: checking /etc/shells for %s", __func__, pw->pw_shell);
370 
371     setusershell();
372     while ((shell = getusershell()) != NULL) {
373 	if (strcmp(shell, pw->pw_shell) == 0)
374 	    debug_return_bool(true);
375     }
376     endusershell();
377 
378     debug_return_bool(false);
379 }
380