1 /*
2  * Copyright (c) 2005 Daniel Walsh <dwalsh@redhat.com>
3  * Copyright (c) 2006 Damien Miller <djm@openbsd.org>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 
18 /*
19  * Linux-specific portability code - just SELinux support at present
20  */
21 
22 #include "includes.h"
23 
24 #if defined(WITH_SELINUX) || defined(LINUX_OOM_ADJUST)
25 #include <errno.h>
26 #include <stdarg.h>
27 #include <string.h>
28 #include <stdio.h>
29 
30 #include "log.h"
31 #include "xmalloc.h"
32 #include "port-linux.h"
33 
34 #ifdef WITH_SELINUX
35 #include <selinux/selinux.h>
36 #include <selinux/get_context_list.h>
37 
38 #ifndef SSH_SELINUX_UNCONFINED_TYPE
39 # define SSH_SELINUX_UNCONFINED_TYPE ":unconfined_t:"
40 #endif
41 
42 /* Wrapper around is_selinux_enabled() to log its return value once only */
43 int
44 ssh_selinux_enabled(void)
45 {
46 	static int enabled = -1;
47 
48 	if (enabled == -1) {
49 		enabled = (is_selinux_enabled() == 1);
50 		debug("SELinux support %s", enabled ? "enabled" : "disabled");
51 	}
52 
53 	return (enabled);
54 }
55 
56 /* Return the default security context for the given username */
57 static security_context_t
58 ssh_selinux_getctxbyname(char *pwname)
59 {
60 	security_context_t sc = NULL;
61 	char *sename = NULL, *lvl = NULL;
62 	int r;
63 
64 #ifdef HAVE_GETSEUSERBYNAME
65 	if (getseuserbyname(pwname, &sename, &lvl) != 0)
66 		return NULL;
67 #else
68 	sename = pwname;
69 	lvl = NULL;
70 #endif
71 
72 #ifdef HAVE_GET_DEFAULT_CONTEXT_WITH_LEVEL
73 	r = get_default_context_with_level(sename, lvl, NULL, &sc);
74 #else
75 	r = get_default_context(sename, NULL, &sc);
76 #endif
77 
78 	if (r != 0) {
79 		switch (security_getenforce()) {
80 		case -1:
81 			fatal("%s: ssh_selinux_getctxbyname: "
82 			    "security_getenforce() failed", __func__);
83 		case 0:
84 			error("%s: Failed to get default SELinux security "
85 			    "context for %s", __func__, pwname);
86 			sc = NULL;
87 			break;
88 		default:
89 			fatal("%s: Failed to get default SELinux security "
90 			    "context for %s (in enforcing mode)",
91 			    __func__, pwname);
92 		}
93 	}
94 
95 #ifdef HAVE_GETSEUSERBYNAME
96 	free(sename);
97 	free(lvl);
98 #endif
99 
100 	return sc;
101 }
102 
103 /* Set the execution context to the default for the specified user */
104 void
105 ssh_selinux_setup_exec_context(char *pwname)
106 {
107 	security_context_t user_ctx = NULL;
108 
109 	if (!ssh_selinux_enabled())
110 		return;
111 
112 	debug3("%s: setting execution context", __func__);
113 
114 	user_ctx = ssh_selinux_getctxbyname(pwname);
115 	if (setexeccon(user_ctx) != 0) {
116 		switch (security_getenforce()) {
117 		case -1:
118 			fatal("%s: security_getenforce() failed", __func__);
119 		case 0:
120 			error("%s: Failed to set SELinux execution "
121 			    "context for %s", __func__, pwname);
122 			break;
123 		default:
124 			fatal("%s: Failed to set SELinux execution context "
125 			    "for %s (in enforcing mode)", __func__, pwname);
126 		}
127 	}
128 	if (user_ctx != NULL)
129 		freecon(user_ctx);
130 
131 	debug3("%s: done", __func__);
132 }
133 
134 /* Set the TTY context for the specified user */
135 void
136 ssh_selinux_setup_pty(char *pwname, const char *tty)
137 {
138 	security_context_t new_tty_ctx = NULL;
139 	security_context_t user_ctx = NULL;
140 	security_context_t old_tty_ctx = NULL;
141 	security_class_t chrclass;
142 
143 	if (!ssh_selinux_enabled())
144 		return;
145 
146 	debug3("%s: setting TTY context on %s", __func__, tty);
147 
148 	user_ctx = ssh_selinux_getctxbyname(pwname);
149 
150 	/* XXX: should these calls fatal() upon failure in enforcing mode? */
151 
152 	if (getfilecon(tty, &old_tty_ctx) == -1) {
153 		error("%s: getfilecon: %s", __func__, strerror(errno));
154 		goto out;
155 	}
156 	if ((chrclass = string_to_security_class("chr_file")) == 0) {
157 		error("%s: couldn't get security class for chr_file", __func__);
158 		goto out;
159 	}
160 	if (security_compute_relabel(user_ctx, old_tty_ctx,
161 	    chrclass, &new_tty_ctx) != 0) {
162 		error("%s: security_compute_relabel: %s",
163 		    __func__, strerror(errno));
164 		goto out;
165 	}
166 
167 	if (setfilecon(tty, new_tty_ctx) != 0)
168 		error("%s: setfilecon: %s", __func__, strerror(errno));
169  out:
170 	if (new_tty_ctx != NULL)
171 		freecon(new_tty_ctx);
172 	if (old_tty_ctx != NULL)
173 		freecon(old_tty_ctx);
174 	if (user_ctx != NULL)
175 		freecon(user_ctx);
176 	debug3("%s: done", __func__);
177 }
178 
179 void
180 ssh_selinux_change_context(const char *newname)
181 {
182 	int len, newlen;
183 	char *oldctx, *newctx, *cx;
184 	void (*switchlog) (const char *fmt,...) = logit;
185 
186 	if (!ssh_selinux_enabled())
187 		return;
188 
189 	if (getcon((security_context_t *)&oldctx) < 0) {
190 		logit("%s: getcon failed with %s", __func__, strerror(errno));
191 		return;
192 	}
193 	if ((cx = index(oldctx, ':')) == NULL || (cx = index(cx + 1, ':')) ==
194 	    NULL) {
195 		logit ("%s: unparseable context %s", __func__, oldctx);
196 		return;
197 	}
198 
199 	/*
200 	 * Check whether we are attempting to switch away from an unconfined
201 	 * security context.
202 	 */
203 	if (strncmp(cx, SSH_SELINUX_UNCONFINED_TYPE,
204 	    sizeof(SSH_SELINUX_UNCONFINED_TYPE) - 1) == 0)
205 		switchlog = debug3;
206 
207 	newlen = strlen(oldctx) + strlen(newname) + 1;
208 	newctx = xmalloc(newlen);
209 	len = cx - oldctx + 1;
210 	memcpy(newctx, oldctx, len);
211 	strlcpy(newctx + len, newname, newlen - len);
212 	if ((cx = index(cx + 1, ':')))
213 		strlcat(newctx, cx, newlen);
214 	debug3("%s: setting context from '%s' to '%s'", __func__,
215 	    oldctx, newctx);
216 	if (setcon(newctx) < 0)
217 		switchlog("%s: setcon %s from %s failed with %s", __func__,
218 		    newctx, oldctx, strerror(errno));
219 	free(oldctx);
220 	free(newctx);
221 }
222 
223 void
224 ssh_selinux_setfscreatecon(const char *path)
225 {
226 	security_context_t context;
227 
228 	if (!ssh_selinux_enabled())
229 		return;
230 	if (path == NULL) {
231 		setfscreatecon(NULL);
232 		return;
233 	}
234 	if (matchpathcon(path, 0700, &context) == 0)
235 		setfscreatecon(context);
236 }
237 
238 #endif /* WITH_SELINUX */
239 
240 #ifdef LINUX_OOM_ADJUST
241 /*
242  * The magic "don't kill me" values, old and new, as documented in eg:
243  * http://lxr.linux.no/#linux+v2.6.32/Documentation/filesystems/proc.txt
244  * http://lxr.linux.no/#linux+v2.6.36/Documentation/filesystems/proc.txt
245  */
246 
247 static int oom_adj_save = INT_MIN;
248 static char *oom_adj_path = NULL;
249 struct {
250 	char *path;
251 	int value;
252 } oom_adjust[] = {
253 	{"/proc/self/oom_score_adj", -1000},	/* kernels >= 2.6.36 */
254 	{"/proc/self/oom_adj", -17},		/* kernels <= 2.6.35 */
255 	{NULL, 0},
256 };
257 
258 /*
259  * Tell the kernel's out-of-memory killer to avoid sshd.
260  * Returns the previous oom_adj value or zero.
261  */
262 void
263 oom_adjust_setup(void)
264 {
265 	int i, value;
266 	FILE *fp;
267 
268 	debug3("%s", __func__);
269 	 for (i = 0; oom_adjust[i].path != NULL; i++) {
270 		oom_adj_path = oom_adjust[i].path;
271 		value = oom_adjust[i].value;
272 		if ((fp = fopen(oom_adj_path, "r+")) != NULL) {
273 			if (fscanf(fp, "%d", &oom_adj_save) != 1)
274 				verbose("error reading %s: %s", oom_adj_path,
275 				    strerror(errno));
276 			else {
277 				rewind(fp);
278 				if (fprintf(fp, "%d\n", value) <= 0)
279 					verbose("error writing %s: %s",
280 					   oom_adj_path, strerror(errno));
281 				else
282 					debug("Set %s from %d to %d",
283 					   oom_adj_path, oom_adj_save, value);
284 			}
285 			fclose(fp);
286 			return;
287 		}
288 	}
289 	oom_adj_path = NULL;
290 }
291 
292 /* Restore the saved OOM adjustment */
293 void
294 oom_adjust_restore(void)
295 {
296 	FILE *fp;
297 
298 	debug3("%s", __func__);
299 	if (oom_adj_save == INT_MIN || oom_adj_path == NULL ||
300 	    (fp = fopen(oom_adj_path, "w")) == NULL)
301 		return;
302 
303 	if (fprintf(fp, "%d\n", oom_adj_save) <= 0)
304 		verbose("error writing %s: %s", oom_adj_path, strerror(errno));
305 	else
306 		debug("Set %s to %d", oom_adj_path, oom_adj_save);
307 
308 	fclose(fp);
309 	return;
310 }
311 #endif /* LINUX_OOM_ADJUST */
312 #endif /* WITH_SELINUX || LINUX_OOM_ADJUST */
313