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 #include <stdlib.h>
30 
31 #include "log.h"
32 #include "xmalloc.h"
33 #include "port-linux.h"
34 
35 #ifdef WITH_SELINUX
36 #include <selinux/selinux.h>
37 #include <selinux/get_context_list.h>
38 
39 #ifndef SSH_SELINUX_UNCONFINED_TYPE
40 # define SSH_SELINUX_UNCONFINED_TYPE ":unconfined_t:"
41 #endif
42 
43 /* Wrapper around is_selinux_enabled() to log its return value once only */
44 int
45 ssh_selinux_enabled(void)
46 {
47 	static int enabled = -1;
48 
49 	if (enabled == -1) {
50 		enabled = (is_selinux_enabled() == 1);
51 		debug("SELinux support %s", enabled ? "enabled" : "disabled");
52 	}
53 
54 	return (enabled);
55 }
56 
57 /* Return the default security context for the given username */
58 static char *
59 ssh_selinux_getctxbyname(char *pwname)
60 {
61 	char *sc = NULL, *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 	char *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 	char *new_tty_ctx = NULL, *user_ctx = NULL, *old_tty_ctx = NULL;
139 	security_class_t chrclass;
140 
141 	if (!ssh_selinux_enabled())
142 		return;
143 
144 	debug3("%s: setting TTY context on %s", __func__, tty);
145 
146 	user_ctx = ssh_selinux_getctxbyname(pwname);
147 
148 	/* XXX: should these calls fatal() upon failure in enforcing mode? */
149 
150 	if (getfilecon(tty, &old_tty_ctx) == -1) {
151 		error("%s: getfilecon: %s", __func__, strerror(errno));
152 		goto out;
153 	}
154 	if ((chrclass = string_to_security_class("chr_file")) == 0) {
155 		error("%s: couldn't get security class for chr_file", __func__);
156 		goto out;
157 	}
158 	if (security_compute_relabel(user_ctx, old_tty_ctx,
159 	    chrclass, &new_tty_ctx) != 0) {
160 		error("%s: security_compute_relabel: %s",
161 		    __func__, strerror(errno));
162 		goto out;
163 	}
164 
165 	if (setfilecon(tty, new_tty_ctx) != 0)
166 		error("%s: setfilecon: %s", __func__, strerror(errno));
167  out:
168 	if (new_tty_ctx != NULL)
169 		freecon(new_tty_ctx);
170 	if (old_tty_ctx != NULL)
171 		freecon(old_tty_ctx);
172 	if (user_ctx != NULL)
173 		freecon(user_ctx);
174 	debug3("%s: done", __func__);
175 }
176 
177 void
178 ssh_selinux_change_context(const char *newname)
179 {
180 	int len, newlen;
181 	char *oldctx, *newctx, *cx;
182 	LogLevel log_level = SYSLOG_LEVEL_INFO;
183 
184 	if (!ssh_selinux_enabled())
185 		return;
186 
187 	if (getcon(&oldctx) < 0) {
188 		logit("%s: getcon failed with %s", __func__, strerror(errno));
189 		return;
190 	}
191 	if ((cx = index(oldctx, ':')) == NULL || (cx = index(cx + 1, ':')) ==
192 	    NULL) {
193 		logit("%s: unparsable context %s", __func__, oldctx);
194 		return;
195 	}
196 
197 	/*
198 	 * Check whether we are attempting to switch away from an unconfined
199 	 * security context.
200 	 */
201 	if (strncmp(cx, SSH_SELINUX_UNCONFINED_TYPE,
202 	    sizeof(SSH_SELINUX_UNCONFINED_TYPE) - 1) == 0)
203 		log_level = SYSLOG_LEVEL_DEBUG3;
204 
205 	newlen = strlen(oldctx) + strlen(newname) + 1;
206 	newctx = xmalloc(newlen);
207 	len = cx - oldctx + 1;
208 	memcpy(newctx, oldctx, len);
209 	strlcpy(newctx + len, newname, newlen - len);
210 	if ((cx = index(cx + 1, ':')))
211 		strlcat(newctx, cx, newlen);
212 	debug3("%s: setting context from '%s' to '%s'", __func__,
213 	    oldctx, newctx);
214 	if (setcon(newctx) < 0)
215 		do_log2(log_level, "%s: setcon %s from %s failed with %s",
216 		    __func__, newctx, oldctx, strerror(errno));
217 	free(oldctx);
218 	free(newctx);
219 }
220 
221 void
222 ssh_selinux_setfscreatecon(const char *path)
223 {
224 	char *context;
225 
226 	if (!ssh_selinux_enabled())
227 		return;
228 	if (path == NULL) {
229 		setfscreatecon(NULL);
230 		return;
231 	}
232 	if (matchpathcon(path, 0700, &context) == 0)
233 		setfscreatecon(context);
234 }
235 
236 #endif /* WITH_SELINUX */
237 
238 #ifdef LINUX_OOM_ADJUST
239 /*
240  * The magic "don't kill me" values, old and new, as documented in eg:
241  * http://lxr.linux.no/#linux+v2.6.32/Documentation/filesystems/proc.txt
242  * http://lxr.linux.no/#linux+v2.6.36/Documentation/filesystems/proc.txt
243  */
244 
245 static int oom_adj_save = INT_MIN;
246 static char *oom_adj_path = NULL;
247 struct {
248 	char *path;
249 	int value;
250 } oom_adjust[] = {
251 	{"/proc/self/oom_score_adj", -1000},	/* kernels >= 2.6.36 */
252 	{"/proc/self/oom_adj", -17},		/* kernels <= 2.6.35 */
253 	{NULL, 0},
254 };
255 
256 /*
257  * Tell the kernel's out-of-memory killer to avoid sshd.
258  * Returns the previous oom_adj value or zero.
259  */
260 void
261 oom_adjust_setup(void)
262 {
263 	int i, value;
264 	FILE *fp;
265 
266 	debug3("%s", __func__);
267 	 for (i = 0; oom_adjust[i].path != NULL; i++) {
268 		oom_adj_path = oom_adjust[i].path;
269 		value = oom_adjust[i].value;
270 		if ((fp = fopen(oom_adj_path, "r+")) != NULL) {
271 			if (fscanf(fp, "%d", &oom_adj_save) != 1)
272 				verbose("error reading %s: %s", oom_adj_path,
273 				    strerror(errno));
274 			else {
275 				rewind(fp);
276 				if (fprintf(fp, "%d\n", value) <= 0)
277 					verbose("error writing %s: %s",
278 					   oom_adj_path, strerror(errno));
279 				else
280 					debug("Set %s from %d to %d",
281 					   oom_adj_path, oom_adj_save, value);
282 			}
283 			fclose(fp);
284 			return;
285 		}
286 	}
287 	oom_adj_path = NULL;
288 }
289 
290 /* Restore the saved OOM adjustment */
291 void
292 oom_adjust_restore(void)
293 {
294 	FILE *fp;
295 
296 	debug3("%s", __func__);
297 	if (oom_adj_save == INT_MIN || oom_adj_path == NULL ||
298 	    (fp = fopen(oom_adj_path, "w")) == NULL)
299 		return;
300 
301 	if (fprintf(fp, "%d\n", oom_adj_save) <= 0)
302 		verbose("error writing %s: %s", oom_adj_path, strerror(errno));
303 	else
304 		debug("Set %s to %d", oom_adj_path, oom_adj_save);
305 
306 	fclose(fp);
307 	return;
308 }
309 #endif /* LINUX_OOM_ADJUST */
310 #endif /* WITH_SELINUX || LINUX_OOM_ADJUST */
311