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 <sys/param.h>
22#include <stdio.h>
23#ifdef HAVE_STRING_H
24# include <string.h>
25#endif /* HAVE_STRING_H */
26#ifdef HAVE_STRINGS_H
27# include <strings.h>
28#endif /* HAVE_STRINGS_H */
29#ifdef HAVE_UNISTD_H
30# include <unistd.h>
31#endif /* HAVE_UNISTD_H */
32#include <errno.h>
33
34#include "missing.h"
35#include "secure_path.h"
36
37/*
38 * Verify that path is the right type and not writable by other users.
39 */
40int
41sudo_secure_path(path, type, uid, gid, sbp)
42    const char *path;
43    int type;
44    uid_t uid;
45    gid_t gid;
46    struct stat *sbp;
47{
48    struct stat sb;
49    int rval = SUDO_PATH_MISSING;
50
51    if (path != NULL && stat(path, &sb) == 0) {
52	if ((sb.st_mode & _S_IFMT) != type) {
53	    rval = SUDO_PATH_BAD_TYPE;
54	} else if (uid != (uid_t)-1 && sb.st_uid != uid) {
55	    rval = SUDO_PATH_WRONG_OWNER;
56	} else if (sb.st_mode & S_IWOTH) {
57	    rval = SUDO_PATH_WORLD_WRITABLE;
58	} else if (ISSET(sb.st_mode, S_IWGRP) &&
59	    (gid == (gid_t)-1 || sb.st_gid != gid)) {
60	    rval = SUDO_PATH_GROUP_WRITABLE;
61	} else {
62	    rval = SUDO_PATH_SECURE;
63	}
64	if (sbp)
65	    (void) memcpy(sbp, &sb, sizeof(struct stat));
66    }
67
68    return rval;
69}
70
71/*
72 * Verify that path is a regular file and not writable by other users.
73 */
74int
75sudo_secure_file(path, uid, gid, sbp)
76    const char *path;
77    uid_t uid;
78    gid_t gid;
79    struct stat *sbp;
80{
81    return sudo_secure_path(path, _S_IFREG, uid, gid, sbp);
82}
83
84/*
85 * Verify that path is a directory and not writable by other users.
86 */
87int
88sudo_secure_dir(path, uid, gid, sbp)
89    const char *path;
90    uid_t uid;
91    gid_t gid;
92    struct stat *sbp;
93{
94    return sudo_secure_path(path, _S_IFDIR, uid, gid, sbp);
95}
96