bmh10 / rpms / openssh

Forked from rpms/openssh 2 days ago
Clone
Blob Blame History Raw
diff --git a/auth-pam.c b/auth-pam.c
index d789bad..cd1a775 100644
--- a/auth-pam.c
+++ b/auth-pam.c
@@ -1068,7 +1068,7 @@ is_pam_session_open(void)
  * during the ssh authentication process.
  */
 int
-do_pam_putenv(char *name, char *value)
+do_pam_putenv(char *name, const char *value)
 {
 	int ret = 1;
 #ifdef HAVE_PAM_PUTENV
diff --git a/auth-pam.h b/auth-pam.h
index a1a2b52..b109a5a 100644
--- a/auth-pam.h
+++ b/auth-pam.h
@@ -38,7 +38,7 @@ void do_pam_session(void);
 void do_pam_set_tty(const char *);
 void do_pam_setcred(int );
 void do_pam_chauthtok(void);
-int do_pam_putenv(char *, char *);
+int do_pam_putenv(char *, const char *);
 char ** fetch_pam_environment(void);
 char ** fetch_pam_child_environment(void);
 void free_pam_environment(char **);
diff --git a/auth.h b/auth.h
index 124e597..4605588 100644
--- a/auth.h
+++ b/auth.h
@@ -59,6 +59,9 @@ struct Authctxt {
 	char		*service;
 	struct passwd	*pw;		/* set if 'valid' */
 	char		*style;
+#ifdef WITH_SELINUX
+	char		*role;
+#endif
 	void		*kbdintctxt;
 	char		*info;		/* Extra info for next auth_log */
 #ifdef BSD_AUTH
diff --git a/auth1.c b/auth1.c
index 0f870b3..df040bb 100644
--- a/auth1.c
+++ b/auth1.c
@@ -381,6 +381,9 @@ do_authentication(Authctxt *authctxt)
 {
 	u_int ulen;
 	char *user, *style = NULL;
+#ifdef WITH_SELINUX
+	char *role=NULL;
+#endif
 
 	/* Get the name of the user that we wish to log in as. */
 	packet_read_expect(SSH_CMSG_USER);
@@ -389,11 +392,24 @@ do_authentication(Authctxt *authctxt)
 	user = packet_get_cstring(&ulen);
 	packet_check_eom();
 
+#ifdef WITH_SELINUX
+	if ((role = strchr(user, '/')) != NULL)
+		*role++ = '\0';
+#endif
+
 	if ((style = strchr(user, ':')) != NULL)
 		*style++ = '\0';
+#ifdef WITH_SELINUX
+	else
+		if (role && (style = strchr(role, ':')) != NULL)
+			*style++ = '\0';
+#endif
 
 	authctxt->user = user;
 	authctxt->style = style;
+#ifdef WITH_SELINUX
+	authctxt->role = role;
+#endif
 
 	/* Verify that the user is a valid user. */
 	if ((authctxt->pw = PRIVSEP(getpwnamallow(user))) != NULL)
diff --git a/auth2-gss.c b/auth2-gss.c
index c28a705..4756dd7 100644
--- a/auth2-gss.c
+++ b/auth2-gss.c
@@ -251,6 +251,7 @@ input_gssapi_mic(int type, u_int32_t plen, void *ctxt)
 	Authctxt *authctxt = ctxt;
 	Gssctxt *gssctxt;
 	int authenticated = 0;
+	char *micuser;
 	Buffer b;
 	gss_buffer_desc mic, gssbuf;
 	u_int len;
@@ -263,7 +264,13 @@ input_gssapi_mic(int type, u_int32_t plen, void *ctxt)
 	mic.value = packet_get_string(&len);
 	mic.length = len;
 
-	ssh_gssapi_buildmic(&b, authctxt->user, authctxt->service,
+#ifdef WITH_SELINUX
+	if (authctxt->role && (strlen(authctxt->role) > 0))
+		xasprintf(&micuser, "%s/%s", authctxt->user, authctxt->role);
+	else
+#endif
+		micuser = authctxt->user;
+	ssh_gssapi_buildmic(&b, micuser, authctxt->service,
 	    "gssapi-with-mic");
 
 	gssbuf.value = buffer_ptr(&b);
@@ -275,6 +282,8 @@ input_gssapi_mic(int type, u_int32_t plen, void *ctxt)
 		logit("GSSAPI MIC check failed");
 
 	buffer_free(&b);
+	if (micuser != authctxt->user)
+		free(micuser);
 	free(mic.value);
 
 	authctxt->postponed = 0;
diff --git a/auth2-hostbased.c b/auth2-hostbased.c
index eca0069..95d678e 100644
--- a/auth2-hostbased.c
+++ b/auth2-hostbased.c
@@ -112,7 +112,15 @@ userauth_hostbased(Authctxt *authctxt)
 	buffer_put_string(&b, session_id2, session_id2_len);
 	/* reconstruct packet */
 	buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
-	buffer_put_cstring(&b, authctxt->user);
+#ifdef WITH_SELINUX
+	if (authctxt->role) {
+		buffer_put_int(&b, strlen(authctxt->user)+strlen(authctxt->role)+1);
+		buffer_append(&b, authctxt->user, strlen(authctxt->user));
+		buffer_put_char(&b, '/');
+		buffer_append(&b, authctxt->role, strlen(authctxt->role));
+	} else 
+#endif
+		buffer_put_cstring(&b, authctxt->user);
 	buffer_put_cstring(&b, service);
 	buffer_put_cstring(&b, "hostbased");
 	buffer_put_string(&b, pkalg, alen);
diff --git a/auth2-pubkey.c b/auth2-pubkey.c
index 749b11a..c0ae0d4 100644
--- a/auth2-pubkey.c
+++ b/auth2-pubkey.c
@@ -133,9 +133,11 @@ userauth_pubkey(Authctxt *authctxt)
 		}
 		/* reconstruct packet */
 		buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST);
-		xasprintf(&userstyle, "%s%s%s", authctxt->user,
+		xasprintf(&userstyle, "%s%s%s%s%s", authctxt->user,
 		    authctxt->style ? ":" : "",
-		    authctxt->style ? authctxt->style : "");
+		    authctxt->style ? authctxt->style : "",
+		    authctxt->role ? "/" : "",
+		    authctxt->role ? authctxt->role : "");
 		buffer_put_cstring(&b, userstyle);
 		free(userstyle);
 		buffer_put_cstring(&b,
diff --git a/auth2.c b/auth2.c
index a5490c0..5f4f26f 100644
--- a/auth2.c
+++ b/auth2.c
@@ -215,6 +215,9 @@ input_userauth_request(int type, u_int32_t seq, void *ctxt)
 	Authctxt *authctxt = ctxt;
 	Authmethod *m = NULL;
 	char *user, *service, *method, *style = NULL;
+#ifdef WITH_SELINUX
+	char *role = NULL;
+#endif
 	int authenticated = 0;
 
 	if (authctxt == NULL)
@@ -226,6 +229,11 @@ input_userauth_request(int type, u_int32_t seq, void *ctxt)
 	debug("userauth-request for user %s service %s method %s", user, service, method);
 	debug("attempt %d failures %d", authctxt->attempt, authctxt->failures);
 
+#ifdef WITH_SELINUX
+	if ((role = strchr(user, '/')) != NULL)
+		*role++ = 0;
+#endif
+
 	if ((style = strchr(user, ':')) != NULL)
 		*style++ = 0;
 
@@ -251,8 +259,15 @@ input_userauth_request(int type, u_int32_t seq, void *ctxt)
 		    use_privsep ? " [net]" : "");
 		authctxt->service = xstrdup(service);
 		authctxt->style = style ? xstrdup(style) : NULL;
-		if (use_privsep)
+#ifdef WITH_SELINUX
+		authctxt->role = role ? xstrdup(role) : NULL;
+#endif
+		if (use_privsep) {
 			mm_inform_authserv(service, style);
+#ifdef WITH_SELINUX
+			mm_inform_authrole(role);
+#endif
+		}
 		userauth_banner();
 		if (auth2_setup_methods_lists(authctxt) != 0)
 			packet_disconnect("no authentication methods enabled");
diff --git a/misc.c b/misc.c
index e4c8c32..f31cd91 100644
--- a/misc.c
+++ b/misc.c
@@ -430,6 +430,7 @@ char *
 colon(char *cp)
 {
 	int flag = 0;
+	int start = 1;
 
 	if (*cp == ':')		/* Leading colon is part of file name. */
 		return NULL;
@@ -445,6 +446,13 @@ colon(char *cp)
 			return (cp);
 		if (*cp == '/')
 			return NULL;
+		if (start) {
+		/* Slash on beginning or after dots only denotes file name. */
+			if (*cp == '/')
+				return (0);
+			if (*cp != '.')
+				start = 0;
+		}
 	}
 	return NULL;
 }
diff --git a/monitor.c b/monitor.c
index 531c4f9..229fada 100644
--- a/monitor.c
+++ b/monitor.c
@@ -145,6 +145,9 @@ int mm_answer_sign(int, Buffer *);
 int mm_answer_pwnamallow(int, Buffer *);
 int mm_answer_auth2_read_banner(int, Buffer *);
 int mm_answer_authserv(int, Buffer *);
+#ifdef WITH_SELINUX
+int mm_answer_authrole(int, Buffer *);
+#endif
 int mm_answer_authpassword(int, Buffer *);
 int mm_answer_bsdauthquery(int, Buffer *);
 int mm_answer_bsdauthrespond(int, Buffer *);
@@ -219,6 +222,9 @@ struct mon_table mon_dispatch_proto20[] = {
     {MONITOR_REQ_SIGN, MON_ONCE, mm_answer_sign},
     {MONITOR_REQ_PWNAM, MON_ONCE, mm_answer_pwnamallow},
     {MONITOR_REQ_AUTHSERV, MON_ONCE, mm_answer_authserv},
+#ifdef WITH_SELINUX
+    {MONITOR_REQ_AUTHROLE, MON_ONCE, mm_answer_authrole},
+#endif
     {MONITOR_REQ_AUTH2_READ_BANNER, MON_ONCE, mm_answer_auth2_read_banner},
     {MONITOR_REQ_AUTHPASSWORD, MON_AUTH, mm_answer_authpassword},
 #ifdef USE_PAM
@@ -805,6 +811,9 @@ mm_answer_pwnamallow(int sock, Buffer *m)
 	else {
 		/* Allow service/style information on the auth context */
 		monitor_permit(mon_dispatch, MONITOR_REQ_AUTHSERV, 1);
+#ifdef WITH_SELINUX
+		monitor_permit(mon_dispatch, MONITOR_REQ_AUTHROLE, 1);
+#endif
 		monitor_permit(mon_dispatch, MONITOR_REQ_AUTH2_READ_BANNER, 1);
 	}
 #ifdef USE_PAM
@@ -846,6 +855,25 @@ mm_answer_authserv(int sock, Buffer *m)
 	return (0);
 }
 
+#ifdef WITH_SELINUX
+int
+mm_answer_authrole(int sock, Buffer *m)
+{
+	monitor_permit_authentications(1);
+
+	authctxt->role = buffer_get_string(m, NULL);
+	debug3("%s: role=%s",
+	    __func__, authctxt->role);
+
+	if (strlen(authctxt->role) == 0) {
+		free(authctxt->role);
+		authctxt->role = NULL;
+	}
+
+	return (0);
+}
+#endif
+
 int
 mm_answer_authpassword(int sock, Buffer *m)
 {
@@ -1220,7 +1248,7 @@ static int
 monitor_valid_userblob(u_char *data, u_int datalen)
 {
 	Buffer b;
-	char *p, *userstyle;
+	char *p, *r, *userstyle;
 	u_int len;
 	int fail = 0;
 
@@ -1246,6 +1274,8 @@ monitor_valid_userblob(u_char *data, u_int datalen)
 	if (buffer_get_char(&b) != SSH2_MSG_USERAUTH_REQUEST)
 		fail++;
 	p = buffer_get_cstring(&b, NULL);
+	if ((r = strchr(p, '/')) != NULL)
+		*r = '\0';
 	xasprintf(&userstyle, "%s%s%s", authctxt->user,
 	    authctxt->style ? ":" : "",
 	    authctxt->style ? authctxt->style : "");
@@ -1281,7 +1311,7 @@ monitor_valid_hostbasedblob(u_char *data, u_int datalen, char *cuser,
     char *chost)
 {
 	Buffer b;
-	char *p, *userstyle;
+	char *p, *r, *userstyle;
 	u_int len;
 	int fail = 0;
 
@@ -1298,6 +1328,8 @@ monitor_valid_hostbasedblob(u_char *data, u_int datalen, char *cuser,
 	if (buffer_get_char(&b) != SSH2_MSG_USERAUTH_REQUEST)
 		fail++;
 	p = buffer_get_cstring(&b, NULL);
+	if ((r = strchr(p, '/')) != NULL)
+		*r = '\0';
 	xasprintf(&userstyle, "%s%s%s", authctxt->user,
 	    authctxt->style ? ":" : "",
 	    authctxt->style ? authctxt->style : "");
diff --git a/monitor.h b/monitor.h
index 5bc41b5..20e2b4a 100644
--- a/monitor.h
+++ b/monitor.h
@@ -57,6 +57,10 @@ enum monitor_reqtype {
 	MONITOR_REQ_GSSCHECKMIC = 48, MONITOR_ANS_GSSCHECKMIC = 49,
 	MONITOR_REQ_TERM = 50,
 
+#ifdef WITH_SELINUX
+	MONITOR_REQ_AUTHROLE = 80,
+#endif
+
 	MONITOR_REQ_PAM_START = 100,
 	MONITOR_REQ_PAM_ACCOUNT = 102, MONITOR_ANS_PAM_ACCOUNT = 103,
 	MONITOR_REQ_PAM_INIT_CTX = 104, MONITOR_ANS_PAM_INIT_CTX = 105,
diff --git a/monitor_wrap.c b/monitor_wrap.c
index 1a47e41..d1b6d99 100644
--- a/monitor_wrap.c
+++ b/monitor_wrap.c
@@ -336,6 +336,25 @@ mm_inform_authserv(char *service, char *style)
 	buffer_free(&m);
 }
 
+/* Inform the privileged process about role */
+
+#ifdef WITH_SELINUX
+void
+mm_inform_authrole(char *role)
+{
+	Buffer m;
+
+	debug3("%s entering", __func__);
+
+	buffer_init(&m);
+	buffer_put_cstring(&m, role ? role : "");
+
+	mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_AUTHROLE, &m);
+
+	buffer_free(&m);
+}
+#endif
+
 /* Do the password authentication */
 int
 mm_auth_password(Authctxt *authctxt, char *password)
diff --git a/monitor_wrap.h b/monitor_wrap.h
index 18c2501..9d5e5ba 100644
--- a/monitor_wrap.h
+++ b/monitor_wrap.h
@@ -42,6 +42,9 @@ int mm_is_monitor(void);
 DH *mm_choose_dh(int, int, int);
 int mm_key_sign(Key *, u_char **, u_int *, u_char *, u_int);
 void mm_inform_authserv(char *, char *);
+#ifdef WITH_SELINUX
+void mm_inform_authrole(char *);
+#endif
 struct passwd *mm_getpwnamallow(const char *);
 char *mm_auth2_read_banner(void);
 int mm_auth_password(struct Authctxt *, char *);
diff --git a/openbsd-compat/Makefile.in b/openbsd-compat/Makefile.in
index 6ecfb93..b912dbe 100644
--- a/openbsd-compat/Makefile.in
+++ b/openbsd-compat/Makefile.in
@@ -20,7 +20,7 @@ OPENBSD=base64.o basename.o bcrypt_pbkdf.o bindresvport.o blowfish.o daemon.o di
 
 COMPAT=arc4random.o bsd-asprintf.o bsd-closefrom.o bsd-cray.o bsd-cygwin_util.o bsd-getpeereid.o getrrsetbyname-ldns.o bsd-misc.o bsd-nextstep.o bsd-openpty.o bsd-poll.o bsd-setres_id.o bsd-snprintf.o bsd-statvfs.o bsd-waitpid.o fake-rfc2553.o openssl-compat.o xmmap.o xcrypt.o
 
-PORTS=port-aix.o port-irix.o port-linux.o port-solaris.o port-tun.o port-uw.o
+PORTS=port-aix.o port-irix.o port-linux.o port-linux-sshd.o port-solaris.o port-tun.o port-uw.o
 
 .c.o:
 	$(CC) $(CFLAGS) $(CPPFLAGS) -c $<
diff --git a/openbsd-compat/port-linux-sshd.c b/openbsd-compat/port-linux-sshd.c
new file mode 100644
index 0000000..c18524e
--- /dev/null
+++ b/openbsd-compat/port-linux-sshd.c
@@ -0,0 +1,414 @@
+/*
+ * Copyright (c) 2005 Daniel Walsh <dwalsh@redhat.com>
+ * Copyright (c) 2014 Petr Lautrbach <plautrba@redhat.com>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+/*
+ * Linux-specific portability code - just SELinux support for sshd at present
+ */
+
+#include "includes.h"
+
+#if defined(WITH_SELINUX) || defined(LINUX_OOM_ADJUST)
+#include <errno.h>
+#include <stdarg.h>
+#include <string.h>
+#include <stdio.h>
+
+#include "log.h"
+#include "xmalloc.h"
+#include "servconf.h"
+#include "port-linux.h"
+#include "key.h"
+#include "hostfile.h"
+#include "auth.h"
+
+#ifdef WITH_SELINUX
+#include <selinux/selinux.h>
+#include <selinux/flask.h>
+#include <selinux/context.h>
+#include <selinux/get_context_list.h>
+#include <selinux/get_default_type.h>
+#include <selinux/av_permissions.h>
+
+#ifdef HAVE_LINUX_AUDIT
+#include <libaudit.h>
+#include <unistd.h>
+#endif
+
+extern ServerOptions options;
+extern Authctxt *the_authctxt;
+extern int inetd_flag;
+extern int rexeced_flag;
+
+/* Send audit message */
+static int
+sshd_selinux_send_audit_message(int success, security_context_t default_context,
+		       security_context_t selected_context)
+{
+	int rc=0;
+#ifdef HAVE_LINUX_AUDIT
+	char *msg = NULL;
+	int audit_fd = audit_open();
+	security_context_t default_raw=NULL;
+	security_context_t selected_raw=NULL;
+	rc = -1;
+	if (audit_fd < 0) {
+		if (errno == EINVAL || errno == EPROTONOSUPPORT ||
+					errno == EAFNOSUPPORT)
+				return 0; /* No audit support in kernel */
+		error("Error connecting to audit system.");
+		return rc;
+	}
+	if (selinux_trans_to_raw_context(default_context, &default_raw) < 0) {
+		error("Error translating default context.");
+		default_raw = NULL;
+	}
+	if (selinux_trans_to_raw_context(selected_context, &selected_raw) < 0) {
+		error("Error translating selected context.");
+		selected_raw = NULL;
+	}
+	if (asprintf(&msg, "sshd: default-context=%s selected-context=%s",
+		     default_raw ? default_raw : (default_context ? default_context: "?"),
+		     selected_context ? selected_raw : (selected_context ? selected_context :"?")) < 0) {
+		error("Error allocating memory.");
+		goto out;
+	}
+	if (audit_log_user_message(audit_fd, AUDIT_USER_ROLE_CHANGE,
+				   msg, NULL, NULL, NULL, success) <= 0) {
+		error("Error sending audit message.");
+		goto out;
+	}
+	rc = 0;
+      out:
+	free(msg);
+	freecon(default_raw);
+	freecon(selected_raw);
+	close(audit_fd);
+#endif
+	return rc;
+}
+
+static int
+mls_range_allowed(security_context_t src, security_context_t dst)
+{
+	struct av_decision avd;
+	int retval;
+	unsigned int bit = CONTEXT__CONTAINS;
+
+	debug("%s: src:%s dst:%s", __func__, src, dst);
+	retval = security_compute_av(src, dst, SECCLASS_CONTEXT, bit, &avd);
+	if (retval || ((bit & avd.allowed) != bit))
+		return 0;
+
+	return 1;
+}
+
+static int
+get_user_context(const char *sename, const char *role, const char *lvl,
+	security_context_t *sc) {
+#ifdef HAVE_GET_DEFAULT_CONTEXT_WITH_LEVEL
+	if (lvl == NULL || lvl[0] == '\0' || get_default_context_with_level(sename, lvl, NULL, sc) != 0) {
+	        /* User may have requested a level completely outside of his 
+	           allowed range. We get a context just for auditing as the
+	           range check below will certainly fail for default context. */
+#endif
+		if (get_default_context(sename, NULL, sc) != 0) {
+			*sc = NULL;
+			return -1;
+		}
+#ifdef HAVE_GET_DEFAULT_CONTEXT_WITH_LEVEL
+	}
+#endif
+	if (role != NULL && role[0]) {
+		context_t con;
+		char *type=NULL;
+		if (get_default_type(role, &type) != 0) {
+			error("get_default_type: failed to get default type for '%s'",
+				role);
+			goto out;
+		}
+		con = context_new(*sc);
+		if (!con) {
+			goto out;
+		}
+		context_role_set(con, role);
+		context_type_set(con, type);
+		freecon(*sc);
+		*sc = strdup(context_str(con));
+		context_free(con);
+		if (!*sc)
+			return -1;
+	}
+#ifdef HAVE_GET_DEFAULT_CONTEXT_WITH_LEVEL
+	if (lvl != NULL && lvl[0]) {
+		/* verify that the requested range is obtained */
+		context_t con;
+		security_context_t obtained_raw;
+		security_context_t requested_raw;
+		con = context_new(*sc);
+		if (!con) {
+			goto out;
+		}
+		context_range_set(con, lvl);
+		if (selinux_trans_to_raw_context(*sc, &obtained_raw) < 0) {
+			context_free(con);
+			goto out;
+		}
+		if (selinux_trans_to_raw_context(context_str(con), &requested_raw) < 0) {
+			freecon(obtained_raw);
+			context_free(con);
+			goto out;
+		}
+
+		debug("get_user_context: obtained context '%s' requested context '%s'",
+			obtained_raw, requested_raw);
+		if (strcmp(obtained_raw, requested_raw)) {
+			/* set the context to the real requested one but fail */
+			freecon(requested_raw);
+			freecon(obtained_raw);
+			freecon(*sc);
+			*sc = strdup(context_str(con));
+			context_free(con);
+			return -1;
+		}
+		freecon(requested_raw);
+		freecon(obtained_raw);
+		context_free(con);
+	}
+#endif
+	return 0;
+      out:
+	freecon(*sc);
+	*sc = NULL;
+	return -1;
+}
+
+static void
+ssh_selinux_get_role_level(char **role, const char **level)
+{
+	*role = NULL;
+	*level = NULL;
+	if (the_authctxt) {
+		if (the_authctxt->role != NULL) {
+			char *slash;
+			*role = xstrdup(the_authctxt->role);
+			if ((slash = strchr(*role, '/')) != NULL) {
+				*slash = '\0';
+				*level = slash + 1;
+			}
+		}
+	}
+}
+
+/* Return the default security context for the given username */
+static int
+sshd_selinux_getctxbyname(char *pwname,
+	security_context_t *default_sc, security_context_t *user_sc)
+{
+	char *sename, *lvl;
+	char *role;
+	const char *reqlvl;
+	int r = 0;
+	context_t con = NULL;
+
+	ssh_selinux_get_role_level(&role, &reqlvl);
+
+#ifdef HAVE_GETSEUSERBYNAME
+	if ((r=getseuserbyname(pwname, &sename, &lvl)) != 0) {
+		sename = NULL;
+		lvl = NULL;
+	}
+#else
+	sename = pwname;
+	lvl = "";
+#endif
+
+	if (r == 0) {
+#ifdef HAVE_GET_DEFAULT_CONTEXT_WITH_LEVEL
+		r = get_default_context_with_level(sename, lvl, NULL, default_sc);
+#else
+		r = get_default_context(sename, NULL, default_sc);
+#endif
+	}
+
+	if (r == 0) {
+		/* If launched from xinetd, we must use current level */
+		if (inetd_flag && !rexeced_flag) {
+			security_context_t sshdsc=NULL;
+
+			if (getcon_raw(&sshdsc) < 0)
+				fatal("failed to allocate security context");
+
+			if ((con=context_new(sshdsc)) == NULL)
+				fatal("failed to allocate selinux context");
+			reqlvl = context_range_get(con);
+			freecon(sshdsc);
+			if (reqlvl !=NULL && lvl != NULL && strcmp(reqlvl, lvl) == 0)
+			    /* we actually don't change level */
+			    reqlvl = "";
+
+			debug("%s: current connection level '%s'", __func__, reqlvl);
+
+		}
+
+		if ((reqlvl != NULL && reqlvl[0]) || (role != NULL && role[0])) {
+			r = get_user_context(sename, role, reqlvl, user_sc);
+
+			if (r == 0 && reqlvl != NULL && reqlvl[0]) {
+				security_context_t default_level_sc = *default_sc;
+				if (role != NULL && role[0]) {
+					if (get_user_context(sename, role, lvl, &default_level_sc) < 0)
+						default_level_sc = *default_sc;
+				}
+				/* verify that the requested range is contained in the user range */
+				if (mls_range_allowed(default_level_sc, *user_sc)) {
+					logit("permit MLS level %s (user range %s)", reqlvl, lvl);
+				} else {
+					r = -1;
+					error("deny MLS level %s (user range %s)", reqlvl, lvl);
+				}
+				if (default_level_sc != *default_sc)
+					freecon(default_level_sc);
+			}
+		} else {
+			*user_sc = *default_sc;
+		}
+	}
+	if (r != 0) {
+		error("%s: Failed to get default SELinux security "
+		    "context for %s", __func__, pwname);
+	}
+
+#ifdef HAVE_GETSEUSERBYNAME
+	free(sename);
+	free(lvl);
+#endif
+
+	if (role != NULL)
+		free(role);
+	if (con)
+		context_free(con);
+
+	return (r);
+}
+
+/* Setup environment variables for pam_selinux */
+static int
+sshd_selinux_setup_pam_variables(void)
+{
+	const char *reqlvl;
+	char *role;
+	char *use_current;
+	int rv;
+
+	debug3("%s: setting execution context", __func__);
+
+	ssh_selinux_get_role_level(&role, &reqlvl);
+
+	rv = do_pam_putenv("SELINUX_ROLE_REQUESTED", role ? role : "");
+
+	if (inetd_flag && !rexeced_flag) {
+		use_current = "1";
+	} else {
+		use_current = "";
+		rv = rv || do_pam_putenv("SELINUX_LEVEL_REQUESTED", reqlvl ? reqlvl: "");
+	}
+
+	rv = rv || do_pam_putenv("SELINUX_USE_CURRENT_RANGE", use_current);
+
+	if (role != NULL)
+		free(role);
+
+	return rv;
+}
+
+/* Set the execution context to the default for the specified user */
+void
+sshd_selinux_setup_exec_context(char *pwname)
+{
+	security_context_t user_ctx = NULL;
+	int r = 0;
+	security_context_t default_ctx = NULL;
+
+	if (!ssh_selinux_enabled())
+		return;
+
+	if (options.use_pam) {
+		/* do not compute context, just setup environment for pam_selinux */
+		if (sshd_selinux_setup_pam_variables()) {
+			switch (security_getenforce()) {
+			case -1:
+				fatal("%s: security_getenforce() failed", __func__);
+			case 0:
+				error("%s: SELinux PAM variable setup failure. Continuing in permissive mode.",
+				    __func__);
+			break;
+			default:
+				fatal("%s: SELinux PAM variable setup failure. Aborting connection.",
+				    __func__);
+			}
+		}
+		return;
+	}
+
+	debug3("%s: setting execution context", __func__);
+
+	r = sshd_selinux_getctxbyname(pwname, &default_ctx, &user_ctx);
+	if (r >= 0) {
+		r = setexeccon(user_ctx);
+		if (r < 0) {
+			error("%s: Failed to set SELinux execution context %s for %s",
+			    __func__, user_ctx, pwname);
+		}
+#ifdef HAVE_SETKEYCREATECON
+		else if (setkeycreatecon(user_ctx) < 0) {
+			error("%s: Failed to set SELinux keyring creation context %s for %s",
+			    __func__, user_ctx, pwname);
+		}
+#endif
+	}
+	if (user_ctx == NULL) {
+		user_ctx = default_ctx;
+	}
+	if (r < 0 || user_ctx != default_ctx) {
+		/* audit just the case when user changed a role or there was
+		   a failure */
+		sshd_selinux_send_audit_message(r >= 0, default_ctx, user_ctx);
+	}
+	if (r < 0) {
+		switch (security_getenforce()) {
+		case -1:
+			fatal("%s: security_getenforce() failed", __func__);
+		case 0:
+			error("%s: SELinux failure. Continuing in permissive mode.",
+			    __func__);
+			break;
+		default:
+			fatal("%s: SELinux failure. Aborting connection.",
+			    __func__);
+		}
+	}
+	if (user_ctx != NULL && user_ctx != default_ctx)
+		freecon(user_ctx);
+	if (default_ctx != NULL)
+		freecon(default_ctx);
+
+	debug3("%s: done", __func__);
+}
+
+#endif
+#endif
+
diff --git a/openbsd-compat/port-linux.c b/openbsd-compat/port-linux.c
index 4637a7a..22ea8ef 100644
--- a/openbsd-compat/port-linux.c
+++ b/openbsd-compat/port-linux.c
@@ -103,37 +103,6 @@ ssh_selinux_getctxbyname(char *pwname)
 	return sc;
 }
 
-/* Set the execution context to the default for the specified user */
-void
-ssh_selinux_setup_exec_context(char *pwname)
-{
-	security_context_t user_ctx = NULL;
-
-	if (!ssh_selinux_enabled())
-		return;
-
-	debug3("%s: setting execution context", __func__);
-
-	user_ctx = ssh_selinux_getctxbyname(pwname);
-	if (setexeccon(user_ctx) != 0) {
-		switch (security_getenforce()) {
-		case -1:
-			fatal("%s: security_getenforce() failed", __func__);
-		case 0:
-			error("%s: Failed to set SELinux execution "
-			    "context for %s", __func__, pwname);
-			break;
-		default:
-			fatal("%s: Failed to set SELinux execution context "
-			    "for %s (in enforcing mode)", __func__, pwname);
-		}
-	}
-	if (user_ctx != NULL)
-		freecon(user_ctx);
-
-	debug3("%s: done", __func__);
-}
-
 /* Set the TTY context for the specified user */
 void
 ssh_selinux_setup_pty(char *pwname, const char *tty)
diff --git a/openbsd-compat/port-linux.h b/openbsd-compat/port-linux.h
index e3d1004..8ef6cc4 100644
--- a/openbsd-compat/port-linux.h
+++ b/openbsd-compat/port-linux.h
@@ -22,9 +22,10 @@
 #ifdef WITH_SELINUX
 int ssh_selinux_enabled(void);
 void ssh_selinux_setup_pty(char *, const char *);
-void ssh_selinux_setup_exec_context(char *);
 void ssh_selinux_change_context(const char *);
 void ssh_selinux_setfscreatecon(const char *);
+
+void sshd_selinux_setup_exec_context(char *);
 #endif
 
 #ifdef LINUX_OOM_ADJUST
diff --git a/platform.c b/platform.c
index 30fc609..0d39ab2 100644
--- a/platform.c
+++ b/platform.c
@@ -183,7 +183,7 @@ platform_setusercontext_post_groups(struct passwd *pw)
 	}
 #endif /* HAVE_SETPCRED */
 #ifdef WITH_SELINUX
-	ssh_selinux_setup_exec_context(pw->pw_name);
+	sshd_selinux_setup_exec_context(pw->pw_name);
 #endif
 }
 
diff --git a/sshd.c b/sshd.c
index 7523de9..07f9926 100644
--- a/sshd.c
+++ b/sshd.c
@@ -2138,6 +2138,9 @@ main(int ac, char **av)
 		restore_uid();
 	}
 #endif
+#ifdef WITH_SELINUX
+	sshd_selinux_setup_exec_context(authctxt->pw->pw_name);
+#endif
 #ifdef USE_PAM
 	if (options.use_pam) {
 		do_pam_setcred(1);