Imported Upstream version 1.8.7
[debian/sudo] / common / secure_path.c
1 /*
2  * Copyright (c) 2012 Todd C. Miller <Todd.Miller@courtesan.com>
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16
17 #include <config.h>
18
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <stdio.h>
22 #ifdef HAVE_STRING_H
23 # include <string.h>
24 #endif /* HAVE_STRING_H */
25 #ifdef HAVE_STRINGS_H
26 # include <strings.h>
27 #endif /* HAVE_STRINGS_H */
28 #ifdef HAVE_UNISTD_H
29 # include <unistd.h>
30 #endif /* HAVE_UNISTD_H */
31 #include <errno.h>
32
33 #include "missing.h"
34 #include "sudo_debug.h"
35 #include "secure_path.h"
36
37 /*
38  * Verify that path is the right type and not writable by other users.
39  */
40 int
41 sudo_secure_path(const char *path, int type, uid_t uid, gid_t gid, struct stat *sbp)
42 {
43     struct stat sb;
44     int rval = SUDO_PATH_MISSING;
45     debug_decl(sudo_secure_path, SUDO_DEBUG_UTIL)
46
47     if (path != NULL && stat(path, &sb) == 0) {
48         if ((sb.st_mode & _S_IFMT) != type) {
49             rval = SUDO_PATH_BAD_TYPE;
50         } else if (uid != (uid_t)-1 && sb.st_uid != uid) {
51             rval = SUDO_PATH_WRONG_OWNER;
52         } else if (sb.st_mode & S_IWOTH) {
53             rval = SUDO_PATH_WORLD_WRITABLE;
54         } else if (ISSET(sb.st_mode, S_IWGRP) &&
55             (gid == (gid_t)-1 || sb.st_gid != gid)) {
56             rval = SUDO_PATH_GROUP_WRITABLE;
57         } else {
58             rval = SUDO_PATH_SECURE;
59         }
60         if (sbp)
61             (void) memcpy(sbp, &sb, sizeof(struct stat));
62     }
63
64     debug_return_int(rval);
65 }
66
67 /*
68  * Verify that path is a regular file and not writable by other users.
69  */
70 int
71 sudo_secure_file(const char *path, uid_t uid, gid_t gid, struct stat *sbp)
72 {
73     return sudo_secure_path(path, _S_IFREG, uid, gid, sbp);
74 }
75
76 /*
77  * Verify that path is a directory and not writable by other users.
78  */
79 int
80 sudo_secure_dir(const char *path, uid_t uid, gid_t gid, struct stat *sbp)
81 {
82     return sudo_secure_path(path, _S_IFDIR, uid, gid, sbp);
83 }