1 /*
2  * SPDX-License-Identifier: ISC
3  *
4  * Copyright (c) 2012, 2014-2016 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/stat.h>
27 #include <string.h>
28 
29 #include "sudo_compat.h"
30 #include "sudo_util.h"
31 #include "sudo_debug.h"
32 
33 /*
34  * Verify that path is the right type and not writable by other users.
35  */
36 static int
sudo_secure_path(const char * path,unsigned int type,uid_t uid,gid_t gid,struct stat * sbp)37 sudo_secure_path(const char *path, unsigned int type, uid_t uid, gid_t gid, struct stat *sbp)
38 {
39     struct stat sb;
40     int ret = SUDO_PATH_MISSING;
41     debug_decl(sudo_secure_path, SUDO_DEBUG_UTIL);
42 
43     if (path != NULL && stat(path, &sb) == 0) {
44 	if ((sb.st_mode & S_IFMT) != type) {
45 	    ret = SUDO_PATH_BAD_TYPE;
46 	} else if (uid != (uid_t)-1 && sb.st_uid != uid) {
47 	    ret = SUDO_PATH_WRONG_OWNER;
48 	} else if (sb.st_mode & S_IWOTH) {
49 	    ret = SUDO_PATH_WORLD_WRITABLE;
50 	} else if (ISSET(sb.st_mode, S_IWGRP) &&
51 	    (gid == (gid_t)-1 || sb.st_gid != gid)) {
52 	    ret = SUDO_PATH_GROUP_WRITABLE;
53 	} else {
54 	    ret = SUDO_PATH_SECURE;
55 	}
56 	if (sbp)
57 	    (void) memcpy(sbp, &sb, sizeof(struct stat));
58     }
59 
60     debug_return_int(ret);
61 }
62 
63 /*
64  * Verify that path is a regular file and not writable by other users.
65  */
66 int
sudo_secure_file_v1(const char * path,uid_t uid,gid_t gid,struct stat * sbp)67 sudo_secure_file_v1(const char *path, uid_t uid, gid_t gid, struct stat *sbp)
68 {
69     return sudo_secure_path(path, S_IFREG, uid, gid, sbp);
70 }
71 
72 /*
73  * Verify that path is a directory and not writable by other users.
74  */
75 int
sudo_secure_dir_v1(const char * path,uid_t uid,gid_t gid,struct stat * sbp)76 sudo_secure_dir_v1(const char *path, uid_t uid, gid_t gid, struct stat *sbp)
77 {
78     return sudo_secure_path(path, S_IFDIR, uid, gid, sbp);
79 }
80