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/label.h>
38 #include <selinux/get_context_list.h>
39 
40 #ifndef SSH_SELINUX_UNCONFINED_TYPE
41 # define SSH_SELINUX_UNCONFINED_TYPE ":unconfined_t:"
42 #endif
43 
44 /* Wrapper around is_selinux_enabled() to log its return value once only */
45 int
46 ssh_selinux_enabled(void)
47 {
48 	static int enabled = -1;
49 
50 	if (enabled == -1) {
51 		enabled = (is_selinux_enabled() == 1);
52 		debug("SELinux support %s", enabled ? "enabled" : "disabled");
53 	}
54 
55 	return (enabled);
56 }
57 
58 /* Return the default security context for the given username */
59 static char *
60 ssh_selinux_getctxbyname(char *pwname)
61 {
62 	char *sc = NULL, *sename = NULL, *lvl = NULL;
63 	int r;
64 
65 #ifdef HAVE_GETSEUSERBYNAME
66 	if (getseuserbyname(pwname, &sename, &lvl) != 0)
67 		return NULL;
68 #else
69 	sename = pwname;
70 	lvl = NULL;
71 #endif
72 
73 #ifdef HAVE_GET_DEFAULT_CONTEXT_WITH_LEVEL
74 	r = get_default_context_with_level(sename, lvl, NULL, &sc);
75 #else
76 	r = get_default_context(sename, NULL, &sc);
77 #endif
78 
79 	if (r != 0) {
80 		switch (security_getenforce()) {
81 		case -1:
82 			fatal("%s: ssh_selinux_getctxbyname: "
83 			    "security_getenforce() failed", __func__);
84 		case 0:
85 			error("%s: Failed to get default SELinux security "
86 			    "context for %s", __func__, pwname);
87 			sc = NULL;
88 			break;
89 		default:
90 			fatal("%s: Failed to get default SELinux security "
91 			    "context for %s (in enforcing mode)",
92 			    __func__, pwname);
93 		}
94 	}
95 
96 #ifdef HAVE_GETSEUSERBYNAME
97 	free(sename);
98 	free(lvl);
99 #endif
100 
101 	return sc;
102 }
103 
104 /* Set the execution context to the default for the specified user */
105 void
106 ssh_selinux_setup_exec_context(char *pwname)
107 {
108 	char *user_ctx = NULL;
109 
110 	if (!ssh_selinux_enabled())
111 		return;
112 
113 	debug3("%s: setting execution context", __func__);
114 
115 	user_ctx = ssh_selinux_getctxbyname(pwname);
116 	if (setexeccon(user_ctx) != 0) {
117 		switch (security_getenforce()) {
118 		case -1:
119 			fatal("%s: security_getenforce() failed", __func__);
120 		case 0:
121 			error("%s: Failed to set SELinux execution "
122 			    "context for %s", __func__, pwname);
123 			break;
124 		default:
125 			fatal("%s: Failed to set SELinux execution context "
126 			    "for %s (in enforcing mode)", __func__, pwname);
127 		}
128 	}
129 	if (user_ctx != NULL)
130 		freecon(user_ctx);
131 
132 	debug3("%s: done", __func__);
133 }
134 
135 /* Set the TTY context for the specified user */
136 void
137 ssh_selinux_setup_pty(char *pwname, const char *tty)
138 {
139 	char *new_tty_ctx = NULL, *user_ctx = NULL, *old_tty_ctx = NULL;
140 	security_class_t chrclass;
141 
142 	if (!ssh_selinux_enabled())
143 		return;
144 
145 	debug3("%s: setting TTY context on %s", __func__, tty);
146 
147 	user_ctx = ssh_selinux_getctxbyname(pwname);
148 
149 	/* XXX: should these calls fatal() upon failure in enforcing mode? */
150 
151 	if (getfilecon(tty, &old_tty_ctx) == -1) {
152 		error("%s: getfilecon: %s", __func__, strerror(errno));
153 		goto out;
154 	}
155 	if ((chrclass = string_to_security_class("chr_file")) == 0) {
156 		error("%s: couldn't get security class for chr_file", __func__);
157 		goto out;
158 	}
159 	if (security_compute_relabel(user_ctx, old_tty_ctx,
160 	    chrclass, &new_tty_ctx) != 0) {
161 		error("%s: security_compute_relabel: %s",
162 		    __func__, strerror(errno));
163 		goto out;
164 	}
165 
166 	if (setfilecon(tty, new_tty_ctx) != 0)
167 		error("%s: setfilecon: %s", __func__, strerror(errno));
168  out:
169 	if (new_tty_ctx != NULL)
170 		freecon(new_tty_ctx);
171 	if (old_tty_ctx != NULL)
172 		freecon(old_tty_ctx);
173 	if (user_ctx != NULL)
174 		freecon(user_ctx);
175 	debug3("%s: done", __func__);
176 }
177 
178 void
179 ssh_selinux_change_context(const char *newname)
180 {
181 	char *oldctx, *newctx, *cx, *cx2;
182 	LogLevel log_level = SYSLOG_LEVEL_INFO;
183 
184 	if (!ssh_selinux_enabled())
185 		return;
186 
187 	if (getcon(&oldctx) < 0) {
188 		logit_f("getcon failed with %s", strerror(errno));
189 		return;
190 	}
191 	if ((cx = strchr(oldctx, ':')) == NULL ||
192 	    (cx = strchr(cx + 1, ':')) == NULL ||
193 	    (cx - oldctx) >= INT_MAX) {
194 		logit_f("unparsable context %s", oldctx);
195 		return;
196 	}
197 
198 	/*
199 	 * Check whether we are attempting to switch away from an unconfined
200 	 * security context.
201 	 */
202 	if (strncmp(cx, SSH_SELINUX_UNCONFINED_TYPE,
203 	    sizeof(SSH_SELINUX_UNCONFINED_TYPE) - 1) == 0)
204 		log_level = SYSLOG_LEVEL_DEBUG3;
205 
206 	cx2 = strchr(cx + 1, ':');
207 	xasprintf(&newctx, "%.*s%s%s", (int)(cx - oldctx + 1), oldctx,
208 	    newname, cx2 == NULL ? "" : cx2);
209 
210 	debug3_f("setting context from '%s' to '%s'", oldctx, newctx);
211 	if (setcon(newctx) < 0)
212 		do_log2_f(log_level, "setcon %s from %s failed with %s",
213 		    newctx, oldctx, strerror(errno));
214 	free(oldctx);
215 	free(newctx);
216 }
217 
218 void
219 ssh_selinux_setfscreatecon(const char *path)
220 {
221 	char *context;
222 	struct selabel_handle *shandle = NULL;
223 
224 	if (!ssh_selinux_enabled())
225 		return;
226 	if (path == NULL) {
227 		setfscreatecon(NULL);
228 		return;
229 	}
230 	if ((shandle = selabel_open(SELABEL_CTX_FILE, NULL, 0)) == NULL) {
231 		debug_f("selabel_open failed");
232 		return;
233 	}
234 	if (selabel_lookup(shandle, &context, path, 0700) == 0)
235 		setfscreatecon(context);
236 	selabel_close(shandle);
237 }
238 
239 #endif /* WITH_SELINUX */
240 
241 #ifdef LINUX_OOM_ADJUST
242 /*
243  * The magic "don't kill me" values, old and new, as documented in eg:
244  * http://lxr.linux.no/#linux+v2.6.32/Documentation/filesystems/proc.txt
245  * http://lxr.linux.no/#linux+v2.6.36/Documentation/filesystems/proc.txt
246  */
247 
248 static int oom_adj_save = INT_MIN;
249 static char *oom_adj_path = NULL;
250 struct {
251 	char *path;
252 	int value;
253 } oom_adjust[] = {
254 	{"/proc/self/oom_score_adj", -1000},	/* kernels >= 2.6.36 */
255 	{"/proc/self/oom_adj", -17},		/* kernels <= 2.6.35 */
256 	{NULL, 0},
257 };
258 
259 /*
260  * Tell the kernel's out-of-memory killer to avoid sshd.
261  * Returns the previous oom_adj value or zero.
262  */
263 void
264 oom_adjust_setup(void)
265 {
266 	int i, value;
267 	FILE *fp;
268 
269 	debug3("%s", __func__);
270 	 for (i = 0; oom_adjust[i].path != NULL; i++) {
271 		oom_adj_path = oom_adjust[i].path;
272 		value = oom_adjust[i].value;
273 		if ((fp = fopen(oom_adj_path, "r+")) != NULL) {
274 			if (fscanf(fp, "%d", &oom_adj_save) != 1)
275 				verbose("error reading %s: %s", oom_adj_path,
276 				    strerror(errno));
277 			else {
278 				rewind(fp);
279 				if (fprintf(fp, "%d\n", value) <= 0)
280 					verbose("error writing %s: %s",
281 					   oom_adj_path, strerror(errno));
282 				else
283 					debug("Set %s from %d to %d",
284 					   oom_adj_path, oom_adj_save, value);
285 			}
286 			fclose(fp);
287 			return;
288 		}
289 	}
290 	oom_adj_path = NULL;
291 }
292 
293 /* Restore the saved OOM adjustment */
294 void
295 oom_adjust_restore(void)
296 {
297 	FILE *fp;
298 
299 	debug3("%s", __func__);
300 	if (oom_adj_save == INT_MIN || oom_adj_path == NULL ||
301 	    (fp = fopen(oom_adj_path, "w")) == NULL)
302 		return;
303 
304 	if (fprintf(fp, "%d\n", oom_adj_save) <= 0)
305 		verbose("error writing %s: %s", oom_adj_path, strerror(errno));
306 	else
307 		debug("Set %s to %d", oom_adj_path, oom_adj_save);
308 
309 	fclose(fp);
310 	return;
311 }
312 #endif /* LINUX_OOM_ADJUST */
313 #endif /* WITH_SELINUX || LINUX_OOM_ADJUST */
314