Blob Blame History Raw
#! /usr/bin/python -Es
# Copyright (C) 2012 Red Hat 
# AUTHORS: Dan Walsh <dwalsh@redhat.com>
# AUTHORS: Miroslav Grepl <mgrepl@redhat.com>
# see file 'COPYING' for use and warranty information
#
# semanage is a tool for managing SELinux configuration files
#
#    This program is free software; you can redistribute it and/or
#    modify it under the terms of the GNU General Public License as
#    published by the Free Software Foundation; either version 2 of
#    the License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA     
#                                        02111-1307  USA
#
#

import senetwork
import os, sys
import selinux
import setools, commands
import seobject

import xml.etree.ElementTree
modules_dict = {}
try:
	tree = xml.etree.ElementTree.parse("/usr/share/selinux/devel/policy.xml")
	for l in  tree.findall("layer"):
		for m in  l.findall("module"):
			name = m.get("name")
			if name == "user" or name == "unconfined":
				continue
			if name == "unprivuser":
				name = "user"
			if name == "unconfineduser":
				name = "unconfined"
			for b in  m.findall("summary"):
				modules_dict[name] = b.text
except IOError, e:
	pass

all_attributes = map(lambda x: x['name'], setools.seinfo(setools.ATTRIBUTE))

bools = seobject.booleans_dict.keys()
role_allows = {}
for rule in commands.getoutput("sesearch --role_allow").split("\n"):
	role = rule.split()
	if len(role) == 3 and role[0] == "allow" and role[1] != "system_r" and role[2][:-1] != "system_r":
		if role[1] not in role_allows:
			role_allows[role[1]] = [role[2][:-1]]
		else:
			role_allows[role[1]].append(role[2][:-1])
#role_allows = setools.sesearch([setools.ROLE_ALLOW],{'scontext':self.type,'tcontext':'ping_t', 'class':'process'})
roles = []
allroles = map(lambda x: x['name'], setools.seinfo(setools.ROLE))
for r in allroles:
	if r not in [ "system_r", "object_r" ]:
		roles.append(r[:-2])

types = map(lambda x: x['name'], setools.seinfo(setools.TYPE))

users = []
allusers = map(lambda x: x['name'], setools.seinfo(setools.USER))
for u in allusers:
	if u not in [ "system_u", "root", "unconfined_u" ]:
		users.append(u.replace("_u",""))
users.sort()

class ManPage:
	def __init__(self,user,path="/tmp"):
		self.user = user
		self.role = user + "_r"
		self.type = user + "_t"
		self.fd = open("%s/%s_selinux.8" % (path, self.user), 'w')
		try:
			self.desc = modules_dict[self.user]
		except:
			self.desc = "%s user role" % self.user 

		if self.user in users:
			self.attributes = setools.seinfo(setools.TYPE,(self.type))[0]["attributes"]
			self.user_header()
			self.user_attribute()
			self.can_sudo()
			self.xwindows_login()
			self.terminal_login()
			self.network()
			self.booleans()
			self.home_exec()
			self.transitions()
		else:
			self.role_header()

		self.footer()
		self.fd.close()

	def user_header(self):
		self.fd.write('.TH  "%(type)s_selinux"  "8"  "%(type)s" "mgrepl@redhat.com" "%(type)s SELinux Policy documentation"'
			%	{'type':self.user})

		self.fd.write(r"""
.SH "NAME"
%(user)s_u \- \fB%(desc)s\fP - Security Enhanced Linux Policy 

.SH DESCRIPTION

\fB%(user)s_u\fP is an SELinux User defined in the SELinux
policy. SELinux users have default roles, \fB%(user)s_r\fP.  The
default role has a default type, \fB%(user)s_t\fP, associated with it.

The SELinux user will usually login to a system with a context that looks like:

.B %(user)s_u:%(user)s_r:%(user)s_u:s0-s0:c0.c1023

Linux users are automatically assigned an SELinux users at login.  
Login programs use the SELinux User to assign initial context to the user's shell.

SELinux policy uses the context to control the user's access.

By default all users are assigned to the SELinux user via the \fB__default__\fP flag

On Targeted policy systems the \fB__default__\fP user is assigned to the \fBunconfined_u\fP SELinux user.

You can list all Linux User to SELinux user mapping using:

.B semanage login -l

If you wanted to change the default user mapping to use the %(user)s_u user, you would execute:

.B semanage login -m -s %(user)s_u __default__

""" % {'desc': self.desc, 'type':self.type, 'user':self.user})

		if "login_userdomain" in self.attributes and "login_userdomain" in all_attributes:
			self.fd.write("""
If you want to map the one Linux user (joe) to the SELinux user %(user)s, you would execute:

.B $ semanage login -a -s %(user)s_u joe

"""	%	{'user':self.user})

	def can_sudo(self):
		sudotype = "%s_sudo_t" % self.user
		self.fd.write("""
.SH SUDO
""")
		if sudotype in types:
			role = self.user + "_r"
			self.fd.write("""
The SELinux user %(user)s can execute sudo. 

You can set up sudo to allow %(user)s to transition to an administrative domain:

Add one or more of the following record to sudoers using visudo.

""" % { 'user':self.user } )
			for adminrole in role_allows[role]:
				self.fd.write("""
USERNAME ALL=(ALL) ROLE=%(admin)s_r TYPE=%(admin)s_t COMMAND
.br
sudo will run COMMAND as %(user)s_u:%(admin)s_r:%(admin)s_t:LEVEL
""" % {'admin':adminrole[:-2], 'user':self.user } )

			self.fd.write("""
You might also need to add one or more of these new roles to your SELinux user record.

List the SELinux roles your SELinux user can reach by executing:

.B $ semanage user -l |grep selinux_name

Modify the roles list and add %(user)s_r to this list.

.B $ semanage user -m -R '%(roles)s' %(user)s_u 

For more details you can see semanage man page.

""" % {'user':self.user, "roles": " ".join([role] + role_allows[role]) } )
		else:
			self.fd.write("""
The SELinux type %s_t is not allowed to execute sudo. 
""" % self.user)

	def user_attribute(self):
		self.fd.write("""
.SH USER DESCRIPTION
""")
		if "unconfined_usertype" in self.attributes:
			self.fd.write("""
The SELinux user %s_u is an unconfined user. It means that a mapped Linux user to this SELinux user is supposed to be allow all actions. 		
""" % self.user)

		if "unpriv_userdomain" in self.attributes:
			self.fd.write("""
The SELinux user %s_u is defined in policy as a unprivileged user. SELinux prevents unprivileged users from doing administration tasks without transitioning to a different role.
""" % self.user)

		if "admindomain" in self.attributes:
			self.fd.write("""
The SELinux user %s_u is an admin user. It means that a mapped Linux user to this SELinux user is intended for administrative actions. Usually this is assigned to a root Linux user.  
""" % self.user)

	def xwindows_login(self):
		if "x_domain" in all_attributes:
			self.fd.write("""
.SH X WINDOWS LOGIN
""")
			if "x_domain" in self.attributes:
				self.fd.write("""
The SELinux user %s_u is able to X Windows login.
""" % self.user)
			else:
				self.fd.write("""
The SELinux user %s_u is not able to X Windows login.
""" % self.user)

	def terminal_login(self):
		if "login_userdomain" in all_attributes:
			self.fd.write("""
.SH TERMINAL LOGIN
""")
			if "login_userdomain" in self.attributes:
				self.fd.write("""
The SELinux user %s_u is able to terminal login.
""" % self.user)
			else:
				self.fd.write("""
The SELinux user %s_u is not able to terminal login.
""" % self.user)

	def booleans(self):
		self.booltext = ""
		for b in bools:
			if b.startswith("allow_user_") is True or \
				    b.startswith("allow_" + self.user + "_") or \
				    b.startswith(self.user + "_") or \
				    b.startswith("user_"):
				desc = seobject.booleans_dict[b][2][0].lower() + seobject.booleans_dict[b][2][1:]
				if desc[-1] == ".":
					desc = desc[:-1]
				self.booltext += """
.PP
If you want to %s, you must turn on the %s boolean.

.EX
.B setsebool -P %s 1
.EE
""" % (desc, b, b)
    
		if self.booltext != "":        
			self.fd.write("""
.SH BOOLEANS
SELinux policy is customizable based on least access required.  %s policy is extremely flexible and has several booleans that allow you to manipulate the policy and run %s with the tightest access possible.

""" % (self.type, self.type))

			self.fd.write(self.booltext)

	def network(self):
		self.fd.write("""
.SH NETWORK
""")
		for net in ("tcp", "udp"):
			portdict = senetwork.get_network_connect(self.type, net, "name_bind")
			if len(portdict) > 0:
				self.fd.write("""
.TP
The SELinux user %s_u is able to listen on the following %s ports.
""" % (self.user, net))
				for p in portdict:
					for recs in portdict[p]:
						self.fd.write("""
.B %s
""" % recs)
		portdict = senetwork.get_network_connect(self.type, "tcp", "name_connect")
		if len(portdict) > 0:
			self.fd.write("""
.TP
The SELinux user %s_u is able to connect to the following tcp ports.
""" % (self.user))
			for p in portdict:
				for recs in portdict[p]:
					self.fd.write("""
.B %s
""" % recs)

	def home_exec(self):
		permlist = setools.sesearch([setools.ALLOW],{'scontext':self.type,'tcontext':'user_home_type', 'class':'file', 'permlist':['ioctl', 'read', 'getattr', 'execute', 'execute_no_trans', 'open']})
		self.fd.write("""
.SH HOME_EXEC
""" )
		if permlist is not None:
			self.fd.write("""
The SELinux user %s_u is able execute home content files.
"""  % self.user)

		else:
			self.fd.write("""
The SELinux user %s_u is not able execute home content files.
"""  % self.user)

	def transitions(self):
		self.fd.write(r"""
.SH TRANSITIONS

Three things can happen when %(type)s attempts to execute a program.

\fB1.\fP SELinux Policy can deny %(type)s from executing the program.

.TP

\fB2.\fP SELinux Policy can allow %(type)s to execute the program in the current user type.

Execute the following to see the types that the SELinux user %(type)s can execute without transitioning:

.B sesearch -A -s %(type)s -c file -p execute_no_trans

.TP

\fB3.\fP SELinux can allow %(type)s to execute the program and transition to a new type.

Execute the following to see the types that the SELinux user %(type)s can execute and transition:

.B $ sesearch -A -s %(type)s -c process -p transition

"""	% {'user':self.user, 'type':self.type})

	def role_header(self):
		self.fd.write('.TH  "%(user)s_selinux"  "8"  "%(user)s" "mgrepl@redhat.com" "%(user)s SELinux Policy documentation"'
			%	{'user':self.user})

		self.fd.write(r"""
.SH "NAME"
%(user)s_r \- \fB%(desc)s\fP - Security Enhanced Linux Policy 

.SH DESCRIPTION

SELinux supports Roles Based Access Control, some Linux roles are login roles, while other roles need to be transition to. 

Note: The examples in the man page will user the staff_u user.

Non login roles are usually used for administrative tasks.

Roles usually have default types assigned to them. 

The default type for the %(user)s_r role is %(user)s_t.

You can use the 
.B newrole 
program to transition directly to this role.

.B newrole -r %(user)s_r -t %(user)s_t

.B sudo 
can also be setup to transition to this role using the visudo command.

USERNAME ALL=(ALL) ROLE=%(user)s_r TYPE=%(user)s_t COMMAND
.br
sudo will run COMMAND as staff_u:%(user)s_r:%(user)s_t:LEVEL

If you want to use a non login role, you need to make sure the SELinux user you are using can reach this role.

You can see all of the assigned SELinux roles using the following

.B semanage user -l

If you wanted to add %(user)s_r to the staff_u user, you would execute:

.B $ semanage user -m -R 'staff_r %(user)s_r' staff_u 

""" % {'desc': self.desc, 'user':self.user})
		troles = []
		for i in role_allows:
			if self.user +"_r" in role_allows[i]:
				troles.append(i)
		if len(troles) > 0:
			plural = ""
			if len(troles) > 1:
				plural = "s"

			self.fd.write("""

SELinux policy also controls which roles can transition to a different role.  
You can list these rules using the following command.

.B sesearch --role_allow

SELinux policy allows the %s role%s can transition to the %s_r role.

""" % (", ".join(troles), plural, self.user))

	def footer(self):
		self.fd.write("""
.SH "COMMANDS"

.B semanage login
can also be used to manipulate the Linux User to SELinux User mappings

.B semanage user
can also be used to manipulate SELinux user definitions.

.B system-config-selinux 
is a GUI tool available to customize SELinux policy settings.

.SH AUTHOR	
This manual page was autogenerated by genuserman.py.

.SH "SEE ALSO"
selinux(8), semanage(8).
""")

for r in roles:
	 ManPage(r)