1 /*
2  * SPDX-License-Identifier: ISC
3  *
4  * Copyright (c) 2015-2021 Todd C. Miller <Todd.Miller@sudo.ws>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 /*
20  * This is an open source non-commercial project. Dear PVS-Studio, please check it.
21  * PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
22  */
23 
24 #include <config.h>
25 
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <unistd.h>
32 #include <errno.h>
33 #include <grp.h>
34 #include <pwd.h>
35 #include <fcntl.h>
36 
37 #include "sudo.h"
38 #include "sudo_edit.h"
39 
40 #if defined(HAVE_SETRESUID) || defined(HAVE_SETREUID) || defined(HAVE_SETEUID)
41 
42 void
switch_user(uid_t euid,gid_t egid,int ngroups,GETGROUPS_T * groups)43 switch_user(uid_t euid, gid_t egid, int ngroups, GETGROUPS_T *groups)
44 {
45     int serrno = errno;
46     debug_decl(switch_user, SUDO_DEBUG_EDIT);
47 
48     sudo_debug_printf(SUDO_DEBUG_INFO|SUDO_DEBUG_LINENO,
49 	"set uid:gid to %u:%u(%u)", (unsigned int)euid, (unsigned int)egid,
50 	ngroups > 0 ? (unsigned int)groups[0] : (unsigned int)egid);
51 
52     /* When restoring root, change euid first; otherwise change it last. */
53     if (euid == ROOT_UID) {
54 	if (seteuid(ROOT_UID) != 0)
55 	    sudo_fatal("seteuid(ROOT_UID)");
56     }
57     if (setegid(egid) != 0)
58 	sudo_fatal("setegid(%d)", (int)egid);
59     if (ngroups != -1) {
60 	if (sudo_setgroups(ngroups, groups) != 0)
61 	    sudo_fatal("setgroups");
62     }
63     if (euid != ROOT_UID) {
64 	if (seteuid(euid) != 0)
65 	    sudo_fatal("seteuid(%u)", (unsigned int)euid);
66     }
67     errno = serrno;
68 
69     debug_return;
70 }
71 
72 #if defined(HAVE_FACCESSAT) && defined(AT_EACCESS)
73 /*
74  * Returns true if the open directory fd is owned or writable by the user.
75  */
76 int
dir_is_writable(int dfd,struct sudo_cred * user_cred,struct sudo_cred * cur_cred)77 dir_is_writable(int dfd, struct sudo_cred *user_cred, struct sudo_cred *cur_cred)
78 {
79     struct stat sb;
80     int rc;
81     debug_decl(dir_is_writable, SUDO_DEBUG_EDIT);
82 
83     if (fstat(dfd, &sb) == -1)
84 	debug_return_int(-1);
85 
86     /* If the user owns the dir we always consider it writable. */
87     if (sb.st_uid == user_cred->uid) {
88 	sudo_debug_printf(SUDO_DEBUG_INFO|SUDO_DEBUG_LINENO,
89 	    "user uid %u matches directory uid %u",
90 	    (unsigned int)user_cred->uid, (unsigned int)sb.st_uid);
91 	debug_return_int(true);
92     }
93 
94     /* Change uid/gid/groups to invoking user, usually needs root perms. */
95     if (cur_cred->euid != ROOT_UID) {
96 	if (seteuid(ROOT_UID) != 0)
97 	    sudo_fatal("seteuid(ROOT_UID)");
98     }
99     switch_user(user_cred->uid, user_cred->gid, user_cred->ngroups,
100 	user_cred->groups);
101 
102     /* Access checks are done using the euid/egid and group vector. */
103     rc = faccessat(dfd, ".", W_OK, AT_EACCESS);
104 
105     /* Restore uid/gid/groups, may need root perms. */
106     if (user_cred->uid != ROOT_UID) {
107 	if (seteuid(ROOT_UID) != 0)
108 	    sudo_fatal("seteuid(ROOT_UID)");
109     }
110     switch_user(cur_cred->euid, cur_cred->egid, cur_cred->ngroups,
111 	cur_cred->groups);
112 
113     if (rc == 0)
114 	debug_return_int(true);
115     if (errno == EACCES || errno == EROFS)
116 	debug_return_int(false);
117     debug_return_int(-1);
118 }
119 #else
120 static bool
group_matches(gid_t target,struct sudo_cred * cred)121 group_matches(gid_t target, struct sudo_cred *cred)
122 {
123     int i;
124     debug_decl(group_matches, SUDO_DEBUG_EDIT);
125 
126     if (target == cred->gid) {
127 	sudo_debug_printf(SUDO_DEBUG_INFO|SUDO_DEBUG_LINENO,
128 	    "user gid %u matches directory gid %u", (unsigned int)cred->gid,
129 	    (unsigned int)target);
130 	debug_return_bool(true);
131     }
132     for (i = 0; i < cred->ngroups; i++) {
133 	if (target == cred->groups[i]) {
134 	    sudo_debug_printf(SUDO_DEBUG_INFO|SUDO_DEBUG_LINENO,
135 		"user gid %u matches directory gid %u",
136 		(unsigned int)cred->groups[i], (unsigned int)target);
137 	    debug_return_bool(true);
138 	}
139     }
140     debug_return_bool(false);
141 }
142 
143 /*
144  * Returns true if the open directory fd is owned or writable by the user.
145  */
146 int
dir_is_writable(int dfd,struct sudo_cred * user_cred,struct sudo_cred * cur_cred)147 dir_is_writable(int dfd, struct sudo_cred *user_cred, struct sudo_cred *cur_cred)
148 {
149     struct stat sb;
150     debug_decl(dir_is_writable, SUDO_DEBUG_EDIT);
151 
152     if (fstat(dfd, &sb) == -1)
153 	debug_return_int(-1);
154 
155     /* If the user owns the dir we always consider it writable. */
156     if (sb.st_uid == user_cred->uid) {
157 	sudo_debug_printf(SUDO_DEBUG_INFO|SUDO_DEBUG_LINENO,
158 	    "user uid %u matches directory uid %u",
159 	    (unsigned int)user_cred->uid, (unsigned int)sb.st_uid);
160 	debug_return_int(true);
161     }
162 
163     /* Other writable? */
164     if (ISSET(sb.st_mode, S_IWOTH)) {
165 	sudo_debug_printf(SUDO_DEBUG_INFO|SUDO_DEBUG_LINENO,
166 	    "directory is writable by other");
167 	debug_return_int(true);
168     }
169 
170     /* Group writable? */
171     if (ISSET(sb.st_mode, S_IWGRP)) {
172 	if (group_matches(sb.st_gid, user_cred)) {
173 	    sudo_debug_printf(SUDO_DEBUG_INFO|SUDO_DEBUG_LINENO,
174 		"directory is writable by one of the user's groups");
175 	    debug_return_int(true);
176 	}
177     }
178 
179     errno = EACCES;
180     debug_return_int(false);
181 }
182 #endif /* HAVE_FACCESSAT && AT_EACCESS */
183 
184 #ifdef O_NOFOLLOW
185 static int
sudo_edit_openat_nofollow(int dfd,char * path,int oflags,mode_t mode)186 sudo_edit_openat_nofollow(int dfd, char *path, int oflags, mode_t mode)
187 {
188     debug_decl(sudo_edit_openat_nofollow, SUDO_DEBUG_EDIT);
189 
190     debug_return_int(openat(dfd, path, oflags|O_NOFOLLOW, mode));
191 }
192 #else
193 /*
194  * Returns true if fd and path don't match or path is a symlink.
195  * Used on older systems without O_NOFOLLOW.
196  */
197 static bool
sudo_edit_is_symlink(int fd,char * path)198 sudo_edit_is_symlink(int fd, char *path)
199 {
200     struct stat sb1, sb2;
201     debug_decl(sudo_edit_is_symlink, SUDO_DEBUG_EDIT);
202 
203     /*
204      * Treat [fl]stat() failure like there was a symlink.
205      */
206     if (fstat(fd, &sb1) == -1 || lstat(path, &sb2) == -1)
207 	debug_return_bool(true);
208 
209     /*
210      * Make sure we did not open a link and that what we opened
211      * matches what is currently on the file system.
212      */
213     if (S_ISLNK(sb2.st_mode) ||
214 	sb1.st_dev != sb2.st_dev || sb1.st_ino != sb2.st_ino) {
215 	debug_return_bool(true);
216     }
217 
218     debug_return_bool(false);
219 }
220 
221 static int
sudo_edit_openat_nofollow(int dfd,char * path,int oflags,mode_t mode)222 sudo_edit_openat_nofollow(int dfd, char *path, int oflags, mode_t mode)
223 {
224     int fd = -1, odfd = -1;
225     struct stat sb;
226     debug_decl(sudo_edit_openat_nofollow, SUDO_DEBUG_EDIT);
227 
228     /* Save cwd and chdir to dfd */
229     if ((odfd = open(".", O_RDONLY)) == -1)
230 	debug_return_int(-1);
231     if (fchdir(dfd) == -1) {
232 	close(odfd);
233 	debug_return_int(-1);
234     }
235 
236     /*
237      * Check if path is a symlink.  This is racey but we detect whether
238      * we lost the race in sudo_edit_is_symlink() after the open.
239      */
240     if (lstat(path, &sb) == -1 && errno != ENOENT)
241 	goto done;
242     if (S_ISLNK(sb.st_mode)) {
243 	errno = ELOOP;
244 	goto done;
245     }
246 
247     fd = open(path, oflags, mode);
248     if (fd == -1)
249 	goto done;
250 
251     /*
252      * Post-open symlink check.  This will leave a zero-length file if
253      * O_CREAT was specified but it is too dangerous to try and remove it.
254      */
255     if (sudo_edit_is_symlink(fd, path)) {
256 	close(fd);
257 	fd = -1;
258 	errno = ELOOP;
259     }
260 
261 done:
262     /* Restore cwd */
263     if (odfd != -1) {
264 	if (fchdir(odfd) == -1)
265 	    sudo_fatal("%s", U_("unable to restore current working directory"));
266 	close(odfd);
267     }
268 
269     debug_return_int(fd);
270 }
271 #endif /* O_NOFOLLOW */
272 
273 static int
sudo_edit_open_nonwritable(char * path,int oflags,mode_t mode,struct sudo_cred * user_cred,struct sudo_cred * cur_cred)274 sudo_edit_open_nonwritable(char *path, int oflags, mode_t mode,
275     struct sudo_cred *user_cred, struct sudo_cred *cur_cred)
276 {
277     const int dflags = DIR_OPEN_FLAGS;
278     int dfd, fd, is_writable;
279     debug_decl(sudo_edit_open_nonwritable, SUDO_DEBUG_EDIT);
280 
281     if (path[0] == '/') {
282 	dfd = open("/", dflags);
283 	path++;
284     } else {
285 	dfd = open(".", dflags);
286 	if (path[0] == '.' && path[1] == '/')
287 	    path += 2;
288     }
289     if (dfd == -1)
290 	debug_return_int(-1);
291 
292     for (;;) {
293 	char *slash;
294 	int subdfd;
295 
296 	/*
297 	 * Look up one component at a time, avoiding symbolic links in
298 	 * writable directories.
299 	 */
300 	is_writable = dir_is_writable(dfd, user_cred, cur_cred);
301 	if (is_writable == -1) {
302 	    close(dfd);
303 	    debug_return_int(-1);
304 	}
305 
306 	path += strspn(path, "/");
307 	slash = strchr(path, '/');
308 	if (slash == NULL)
309 	    break;
310 	*slash = '\0';
311 	if (is_writable)
312 	    subdfd = sudo_edit_openat_nofollow(dfd, path, dflags, 0);
313 	else
314 	    subdfd = openat(dfd, path, dflags, 0);
315 	*slash = '/';			/* restore path */
316 	close(dfd);
317 	if (subdfd == -1)
318 	    debug_return_int(-1);
319 	path = slash + 1;
320 	dfd = subdfd;
321     }
322 
323     if (is_writable) {
324 	close(dfd);
325 	errno = EISDIR;
326 	debug_return_int(-1);
327     }
328 
329     /*
330      * For "sudoedit /" we will receive ENOENT from openat() and sudoedit
331      * will try to create a file with an empty name.  We treat an empty
332      * path as the cwd so sudoedit can give a sensible error message.
333      */
334     fd = openat(dfd, *path ? path : ".", oflags, mode);
335     close(dfd);
336     debug_return_int(fd);
337 }
338 
339 #ifdef O_NOFOLLOW
340 int
sudo_edit_open(char * path,int oflags,mode_t mode,int sflags,struct sudo_cred * user_cred,struct sudo_cred * cur_cred)341 sudo_edit_open(char *path, int oflags, mode_t mode, int sflags,
342     struct sudo_cred *user_cred, struct sudo_cred *cur_cred)
343 {
344     int fd;
345     debug_decl(sudo_edit_open, SUDO_DEBUG_EDIT);
346 
347     if (!ISSET(sflags, CD_SUDOEDIT_FOLLOW))
348 	oflags |= O_NOFOLLOW;
349     if (ISSET(sflags, CD_SUDOEDIT_CHECKDIR) && user_cred->uid != ROOT_UID) {
350 	fd = sudo_edit_open_nonwritable(path, oflags|O_NONBLOCK, mode,
351 	    user_cred, cur_cred);
352     } else {
353 	fd = open(path, oflags|O_NONBLOCK, mode);
354     }
355     if (fd != -1 && !ISSET(oflags, O_NONBLOCK))
356 	(void) fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) & ~O_NONBLOCK);
357     debug_return_int(fd);
358 }
359 #else
360 int
sudo_edit_open(char * path,int oflags,mode_t mode,int sflags,struct sudo_cred * user_cred,struct sudo_cred * cur_cred)361 sudo_edit_open(char *path, int oflags, mode_t mode, int sflags,
362     struct sudo_cred *user_cred, struct sudo_cred *cur_cred)
363 {
364     struct stat sb;
365     int fd;
366     debug_decl(sudo_edit_open, SUDO_DEBUG_EDIT);
367 
368     /*
369      * Check if path is a symlink.  This is racey but we detect whether
370      * we lost the race in sudo_edit_is_symlink() after the file is opened.
371      */
372     if (!ISSET(sflags, CD_SUDOEDIT_FOLLOW)) {
373 	if (lstat(path, &sb) == -1 && errno != ENOENT)
374 	    debug_return_int(-1);
375 	if (S_ISLNK(sb.st_mode)) {
376 	    errno = ELOOP;
377 	    debug_return_int(-1);
378 	}
379     }
380 
381     if (ISSET(sflags, CD_SUDOEDIT_CHECKDIR) && user_cred->uid != ROOT_UID) {
382 	fd = sudo_edit_open_nonwritable(path, oflags|O_NONBLOCK, mode,
383 	    user_cred, cur_cred);
384     } else {
385 	fd = open(path, oflags|O_NONBLOCK, mode);
386     }
387     if (fd == -1)
388 	debug_return_int(-1);
389     if (!ISSET(oflags, O_NONBLOCK))
390 	(void) fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) & ~O_NONBLOCK);
391 
392     /*
393      * Post-open symlink check.  This will leave a zero-length file if
394      * O_CREAT was specified but it is too dangerous to try and remove it.
395      */
396     if (!ISSET(sflags, CD_SUDOEDIT_FOLLOW) && sudo_edit_is_symlink(fd, path)) {
397 	close(fd);
398 	fd = -1;
399 	errno = ELOOP;
400     }
401 
402     debug_return_int(fd);
403 }
404 #endif /* O_NOFOLLOW */
405 
406 /*
407  * Verify that the parent dir of a new file exists and is not writable
408  * by the user.  This fails early so the user knows ahead of time if the
409  * edit won't succeed.  Additional checks are performed when copying the
410  * temporary file back to the origin so there are no TOCTOU issues.
411  * Does not modify the value of errno.
412  */
413 bool
sudo_edit_parent_valid(char * path,int sflags,struct sudo_cred * user_cred,struct sudo_cred * cur_cred)414 sudo_edit_parent_valid(char *path, int sflags, struct sudo_cred *user_cred,
415     struct sudo_cred *cur_cred)
416 {
417     const int serrno = errno;
418     struct stat sb;
419     bool ret = false;
420     char *slash;
421     int dfd;
422     debug_decl(sudo_edit_parent_valid, SUDO_DEBUG_EDIT);
423 
424     /* Get dirname of path (the slash is restored later). */
425     slash = strrchr(path, '/');
426     if (slash == NULL) {
427 	/* cwd */
428 	path = ".";
429     } else if (slash == path) {
430 	path = "/";
431 	slash = NULL;
432     } else {
433 	*slash = '\0';
434     }
435 
436     /*
437      * The parent directory is allowed to be a symbolic link unless
438      * *its* parent is writable and CD_SUDOEDIT_CHECK is set.
439      */
440     dfd = sudo_edit_open(path, DIR_OPEN_FLAGS, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH,
441 	sflags|CD_SUDOEDIT_FOLLOW, user_cred, cur_cred);
442     if (dfd != -1) {
443 	if (fstat(dfd, &sb) == 0 && S_ISDIR(sb.st_mode))
444 	    ret = true;
445 	close(dfd);
446     }
447     if (slash != NULL)
448 	*slash = '/';
449 
450     /* Restore errno. */
451     errno = serrno;
452 
453     debug_return_bool(ret);
454 }
455 
456 #endif /* HAVE_SETRESUID || HAVE_SETREUID || HAVE_SETEUID */
457