1/* $Id: port-linux.c,v 1.17 2012/03/08 23:25:18 djm Exp $ */
2
3/*
4 * Copyright (c) 2005 Daniel Walsh <dwalsh@redhat.com>
5 * Copyright (c) 2006 Damien Miller <djm@openbsd.org>
6 *
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
10 *
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 */
19
20/*
21 * Linux-specific portability code - just SELinux support at present
22 */
23
24#include "includes.h"
25
26#if defined(WITH_SELINUX) || defined(LINUX_OOM_ADJUST)
27#include <errno.h>
28#include <stdarg.h>
29#include <string.h>
30#include <stdio.h>
31
32#include "log.h"
33#include "xmalloc.h"
34#include "port-linux.h"
35
36#ifdef WITH_SELINUX
37#include <selinux/selinux.h>
38#include <selinux/flask.h>
39#include <selinux/get_context_list.h>
40
41#ifndef SSH_SELINUX_UNCONFINED_TYPE
42# define SSH_SELINUX_UNCONFINED_TYPE ":unconfined_t:"
43#endif
44
45/* Wrapper around is_selinux_enabled() to log its return value once only */
46int
47ssh_selinux_enabled(void)
48{
49	static int enabled = -1;
50
51	if (enabled == -1) {
52		enabled = (is_selinux_enabled() == 1);
53		debug("SELinux support %s", enabled ? "enabled" : "disabled");
54	}
55
56	return (enabled);
57}
58
59/* Return the default security context for the given username */
60static security_context_t
61ssh_selinux_getctxbyname(char *pwname)
62{
63	security_context_t sc = NULL;
64	char *sename = NULL, *lvl = NULL;
65	int r;
66
67#ifdef HAVE_GETSEUSERBYNAME
68	if (getseuserbyname(pwname, &sename, &lvl) != 0)
69		return NULL;
70#else
71	sename = pwname;
72	lvl = NULL;
73#endif
74
75#ifdef HAVE_GET_DEFAULT_CONTEXT_WITH_LEVEL
76	r = get_default_context_with_level(sename, lvl, NULL, &sc);
77#else
78	r = get_default_context(sename, NULL, &sc);
79#endif
80
81	if (r != 0) {
82		switch (security_getenforce()) {
83		case -1:
84			fatal("%s: ssh_selinux_getctxbyname: "
85			    "security_getenforce() failed", __func__);
86		case 0:
87			error("%s: Failed to get default SELinux security "
88			    "context for %s", __func__, pwname);
89			sc = NULL;
90			break;
91		default:
92			fatal("%s: Failed to get default SELinux security "
93			    "context for %s (in enforcing mode)",
94			    __func__, pwname);
95		}
96	}
97
98#ifdef HAVE_GETSEUSERBYNAME
99	if (sename != NULL)
100		xfree(sename);
101	if (lvl != NULL)
102		xfree(lvl);
103#endif
104
105	return sc;
106}
107
108/* Set the execution context to the default for the specified user */
109void
110ssh_selinux_setup_exec_context(char *pwname)
111{
112	security_context_t user_ctx = NULL;
113
114	if (!ssh_selinux_enabled())
115		return;
116
117	debug3("%s: setting execution context", __func__);
118
119	user_ctx = ssh_selinux_getctxbyname(pwname);
120	if (setexeccon(user_ctx) != 0) {
121		switch (security_getenforce()) {
122		case -1:
123			fatal("%s: security_getenforce() failed", __func__);
124		case 0:
125			error("%s: Failed to set SELinux execution "
126			    "context for %s", __func__, pwname);
127			break;
128		default:
129			fatal("%s: Failed to set SELinux execution context "
130			    "for %s (in enforcing mode)", __func__, pwname);
131		}
132	}
133	if (user_ctx != NULL)
134		freecon(user_ctx);
135
136	debug3("%s: done", __func__);
137}
138
139/* Set the TTY context for the specified user */
140void
141ssh_selinux_setup_pty(char *pwname, const char *tty)
142{
143	security_context_t new_tty_ctx = NULL;
144	security_context_t user_ctx = NULL;
145	security_context_t old_tty_ctx = NULL;
146
147	if (!ssh_selinux_enabled())
148		return;
149
150	debug3("%s: setting TTY context on %s", __func__, tty);
151
152	user_ctx = ssh_selinux_getctxbyname(pwname);
153
154	/* XXX: should these calls fatal() upon failure in enforcing mode? */
155
156	if (getfilecon(tty, &old_tty_ctx) == -1) {
157		error("%s: getfilecon: %s", __func__, strerror(errno));
158		goto out;
159	}
160
161	if (security_compute_relabel(user_ctx, old_tty_ctx,
162	    SECCLASS_CHR_FILE, &new_tty_ctx) != 0) {
163		error("%s: security_compute_relabel: %s",
164		    __func__, strerror(errno));
165		goto out;
166	}
167
168	if (setfilecon(tty, new_tty_ctx) != 0)
169		error("%s: setfilecon: %s", __func__, strerror(errno));
170 out:
171	if (new_tty_ctx != NULL)
172		freecon(new_tty_ctx);
173	if (old_tty_ctx != NULL)
174		freecon(old_tty_ctx);
175	if (user_ctx != NULL)
176		freecon(user_ctx);
177	debug3("%s: done", __func__);
178}
179
180void
181ssh_selinux_change_context(const char *newname)
182{
183	int len, newlen;
184	char *oldctx, *newctx, *cx;
185	void (*switchlog) (const char *fmt,...) = logit;
186
187	if (!ssh_selinux_enabled())
188		return;
189
190	if (getcon((security_context_t *)&oldctx) < 0) {
191		logit("%s: getcon failed with %s", __func__, strerror(errno));
192		return;
193	}
194	if ((cx = index(oldctx, ':')) == NULL || (cx = index(cx + 1, ':')) ==
195	    NULL) {
196		logit ("%s: unparseable context %s", __func__, oldctx);
197		return;
198	}
199
200	/*
201	 * Check whether we are attempting to switch away from an unconfined
202	 * security context.
203	 */
204	if (strncmp(cx, SSH_SELINUX_UNCONFINED_TYPE,
205	    sizeof(SSH_SELINUX_UNCONFINED_TYPE) - 1) == 0)
206		switchlog = debug3;
207
208	newlen = strlen(oldctx) + strlen(newname) + 1;
209	newctx = xmalloc(newlen);
210	len = cx - oldctx + 1;
211	memcpy(newctx, oldctx, len);
212	strlcpy(newctx + len, newname, newlen - len);
213	if ((cx = index(cx + 1, ':')))
214		strlcat(newctx, cx, newlen);
215	debug3("%s: setting context from '%s' to '%s'", __func__,
216	    oldctx, newctx);
217	if (setcon(newctx) < 0)
218		switchlog("%s: setcon %s from %s failed with %s", __func__,
219		    newctx, oldctx, strerror(errno));
220	xfree(oldctx);
221	xfree(newctx);
222}
223
224void
225ssh_selinux_setfscreatecon(const char *path)
226{
227	security_context_t context;
228
229	if (!ssh_selinux_enabled())
230		return;
231	if (path == NULL) {
232		setfscreatecon(NULL);
233		return;
234	}
235	if (matchpathcon(path, 0700, &context) == 0)
236		setfscreatecon(context);
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
248static int oom_adj_save = INT_MIN;
249static char *oom_adj_path = NULL;
250struct {
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 */
263void
264oom_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					verbose("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 */
294void
295oom_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		verbose("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