Blob Blame History Raw
#! /usr/bin/python -Es
# Copyright (C) 2012 Red Hat 
# AUTHOR: Dan Walsh <dwalsh@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 argparse
import senetwork
import seobject
import selinux
import datetime
import setools
import commands
import sys
import os

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))
entrypoints =  setools.seinfo(setools.ATTRIBUTE,"entry_type")[0]["types"]
alldomains =  setools.seinfo(setools.ATTRIBUTE,"domain")[0]["types"]
domains = []

fc_path = selinux.selinux_file_context_path()

fd = open(selinux.selinux_file_context_path(), "r")
fc = fd.readlines()
fd.close()
fd = open(selinux.selinux_file_context_path()+".homedirs", "r")
fc += fd.readlines()
fd.close()
fcdict = {}
for i in fc:
    rec = i.split()
    try:
        t = rec[-1].split(":")[2]
        if t in fcdict:
            fcdict[t].append(rec[0])
        else:
            fcdict[t] = [ rec[0] ]
    except:
        pass
fcdict["logfile"] = [ "all log files" ]
fcdict["user_tmp_type"] = [ "all user tmp files" ]
fcdict["user_home_type"] = [ "all user home files" ]
fcdict["virt_image_type"] = [ "all virtual image files" ]
fcdict["noxattrfs"] = [ "all files on file systems which do not support extended attributes" ]
fcdict["sandbox_tmpfs_type"] = [ "all sandbox content in tmpfs file systems" ]
fcdict["user_tmpfs_type"] = [ "all user content in tmpfs file systems" ]
fcdict["file_type"] = [ "all files on the system" ]

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])

for d in alldomains:
    found = False
    domain = d[:-2]
    if domain + "_exec_t" not in entrypoints:
        continue
    if domain in domains or name == "pam":
        continue
    domains.append(domain)

for role in roles:
    if role in domains:
        continue
    domains.append(role)

domains.sort()

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()

import setools
all_types =  setools.seinfo(setools.TYPE)
types = {}
for rec in all_types:
    try:
        types[rec["name"]] = rec["attributes"]
    except:
        types[rec["name"]] = []

file_types =  setools.seinfo(setools.ATTRIBUTE,"file_type")[0]["types"]
file_types.sort()

port_types =  setools.seinfo(setools.ATTRIBUTE,"port_type")[0]["types"]
port_types.sort()

portrecs = seobject.portRecords().get_all_by_type()
filerecs = seobject.fcontextRecords()
files_dict = {}
fdict = filerecs.get_all()
for i in fdict:
    if fdict[i]:
        if fdict[i][2] in files_dict:
            files_dict[fdict[i][2]].append(i)
        else:
            files_dict[fdict[i][2]] = [i]
boolrecs = seobject.booleanRecords()
bools = seobject.booleans_dict.keys()

man = {}
date = datetime.datetime.now().strftime("%d %b %Y")
def prettyprint(f,trim):
    return " ".join(f[:-len(trim)].split("_"))

def get_os_version():
    os_version = ""
    pkg_name = "selinux-policy"
    try:
        import commands
        rc, output = commands.getstatusoutput("rpm -q '%s'" % pkg_name)
        if rc == 0:
            os_version = output.split(".")[-2]
    except:
        os_version = ""

    if os_version[0:2] == "fc":
        os_version = "Fedora"+os_version[2:]
    elif os_version[0:2] == "el":
        os_version = "RHEL"+os_version[2:]
    else:
        os_version = ""
		
    return os_version


os_version = get_os_version()

class ManPage:
    def __init__(self, domainname, path):
        self.domainname = domainname
	self.short_name = domainname
        self.type = self.domainname + "_t"
        self.fd = open("%s/%s_selinux.8" % (path, domainname), 'w')
        if domainname in roles:
            self.__gen_user_man_page()
        else:
            self.__gen_man_page()
        self.fd.close()

    def __gen_user_man_page(self):
        self.role = self.domainname + "_r"

        try:
            self.desc = modules_dict[self.domainname]
        except:
            self.desc = "%s user role" % self.domainname 
            
        if self.domainname in users:
            self.attributes = setools.seinfo(setools.TYPE,(self.type))[0]["attributes"]
            self.user_header()
            self.user_attribute()
            self.can_sudo()
            self.xwindows_login()
            # until a new policy build with login_userdomain attribute
        #self.terminal_login()
            self.network()
            self.booleans()
            self.home_exec()
            self.transitions()
        else:
            self.role_header()
            self.booleans()

        self.port_types()
        self.writes()
        self.footer()

    def __gen_man_page(self):
        if self.domainname[-1]=='d':
            self.short_name = self.domainname[:-1]

        self.anon_list = []

        self.attributes = {}
        self.ptypes = []
        self.get_ptypes()

        for domain_type in self.ptypes:
            self.attributes[domain_type] = setools.seinfo(setools.TYPE,("%s") % domain_type)[0]["attributes"]

        self.header()
	self.entrypoints()
        self.process_types()
        self.booleans()
        self.public_content()
        self.file_context()
        self.port_types()
        self.writes()
        self.nsswitch_domain()
        self.footer()

    def get_ptypes(self):
        for f in alldomains:
            if f.startswith(self.short_name):
                self.ptypes.append(f)

    def header(self):
        self.fd.write('.TH  "%(domainname)s_selinux"  "8"  "%(domainname)s" "dwalsh@redhat.com" "%(domainname)s SELinux Policy documentation"'
                 % {'domainname':self.domainname})
        self.fd.write(r"""
.SH "NAME"
%(domainname)s_selinux \- Security Enhanced Linux Policy for the %(domainname)s processes
.SH "DESCRIPTION"

Security-Enhanced Linux secures the %(domainname)s processes via flexible mandatory access control.

The %(domainname)s processes execute with the %(domainname)s_t SELinux type. You can check if you have these processes running by executing the \fBps\fP command with the \fB\-Z\fP qualifier. 

For example:

.B ps -eZ | grep %(domainname)s_t

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


    def explain(self, f):
        if f.endswith("_var_run_t"):
            return "store the %s files under the /run directory." % prettyprint(f, "_var_run_t")
        if f.endswith("_pid_t"):
            return "store the %s files under the /run directory." % prettyprint(f, "_pid_t")
        if f.endswith("_var_lib_t"):
            return "store the %s files under the /var/lib directory."  % prettyprint(f, "_var_lib_t")
        if f.endswith("_var_t"):
            return "store the %s files under the /var directory."  % prettyprint(f, "_var_lib_t")
        if f.endswith("_var_spool_t"):
            return "store the %s files under the /var/spool directory." % prettyprint(f, "_spool_t")
        if f.endswith("_spool_t"):
            return "store the %s files under the /var/spool directory." % prettyprint(f, "_spool_t")
        if f.endswith("_cache_t") or f.endswith("_var_cache_t"):
            return "store the files under the /var/cache directory."
        if f.endswith("_keytab_t"):
            return "treat the files as kerberos keytab files."
        if f.endswith("_lock_t"):
            return "treat the files as %s lock data, stored under the /var/lock directory" % prettyprint(f,"_lock_t")
        if f.endswith("_log_t"):
            return "treat the data as %s log data, usually stored under the /var/log directory." % prettyprint(f,"_log_t")
        if f.endswith("_config_t"):
            return "treat the files as %s configuration data, usually stored under the /etc directory." % prettyprint(f,"_config_t")
        if f.endswith("_conf_t"):
            return "treat the files as %s configuration data, usually stored under the /etc directory." % prettyprint(f,"_conf_t")
        if f.endswith("_exec_t"):
            return "transition an executable to the %s_t domain." % f[:-len("_exec_t")]
        if f.endswith("_cgi_content_t"):
            return "treat the files as %s cgi content." % prettyprint(f, "_cgi_content_t")
        if f.endswith("_rw_content_t"):
            return "treat the files as %s read/write content." % prettyprint(f,"_rw_content_t")
        if f.endswith("_rw_t"):
            return "treat the files as %s read/write content." % prettyprint(f,"_rw_t")
        if f.endswith("_write_t"):
            return "treat the files as %s read/write content." % prettyprint(f,"_write_t")
        if f.endswith("_db_t"):
            return "treat the files as %s database content." % prettyprint(f,"_db_t")
        if f.endswith("_ra_content_t"):
            return "treat the files as %s read/append content." % prettyprint(f,"_ra_conten_t")
        if f.endswith("_cert_t"):
            return "treat the files as %s certificate data." % prettyprint(f,"_cert_t")
        if f.endswith("_key_t"):
            return "treat the files as %s key data." % prettyprint(f,"_key_t")

        if f.endswith("_secret_t"):
            return "treat the files as %s secret data." % prettyprint(f,"_key_t")

        if f.endswith("_ra_t"):
            return "treat the files as %s read/append content." % prettyprint(f,"_ra_t")

        if f.endswith("_ro_t"):
            return "treat the files as %s read/only content." % prettyprint(f,"_ro_t")

        if f.endswith("_modules_t"):
            return "treat the files as %s modules." % prettyprint(f, "_modules_t")

        if f.endswith("_content_t"):
            return "treat the files as %s content." % prettyprint(f, "_content_t")

        if f.endswith("_state_t"):
            return "treat the files as %s state data." % prettyprint(f, "_state_t")

        if f.endswith("_files_t"):
            return "treat the files as %s content." % prettyprint(f, "_files_t")

        if f.endswith("_file_t"):
            return "treat the files as %s content." % prettyprint(f, "_file_t")

        if f.endswith("_data_t"):
            return "treat the files as %s content." % prettyprint(f, "_data_t")

        if f.endswith("_file_t"):
            return "treat the data as %s content." % prettyprint(f, "_file_t")

        if f.endswith("_tmp_t"):
            return "store %s temporary files in the /tmp directories." % prettyprint(f, "_tmp_t")
        if f.endswith("_etc_t"):
            return "store %s files in the /etc directories." % prettyprint(f, "_tmp_t")
        if f.endswith("_home_t"):
            return "store %s files in the users home directory." % prettyprint(f, "_home_t")
        if f.endswith("_tmpfs_t"):
            return "store %s files on a tmpfs file system." % prettyprint(f, "_tmpfs_t")
        if f.endswith("_unit_file_t"):
            return "treat files as a systemd unit file." 
        if f.endswith("_htaccess_t"):
            return "treat the file as a %s access file." % prettyprint(f, "_htaccess_t")

        return "treat the files as %s data." % prettyprint(f,"_t")

    def booleans(self):
        self.booltext = ""
        for b in bools:
            if b.find(self.short_name) >= 0:
                if b.endswith("anon_write"):
                    self.anon_list.append(b)
                else:
                    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.domainname, self.domainname))

            self.fd.write(self.booltext)

    def nsswitch_domain(self):
        nsswitch_types = []
        nsswitch_booleans = ['authlogin_nsswitch_use_ldap', 'kerberos_enabled']
        nsswitchbooltext = ""
        if "nsswitch_domain" in all_attributes:
            self.fd.write("""
.SH NSSWITCH DOMAIN
""")
            for k in self.attributes.keys():    
                if "nsswitch_domain" in self.attributes[k]:
                    nsswitch_types.append(k)

            if len(nsswitch_types):
                for i in nsswitch_booleans:
                    desc = seobject.booleans_dict[i][2][0].lower() + seobject.booleans_dict[i][2][1:-1]
                    nsswitchbooltext += """
.PP
If you want to %s for the %s, you must turn on the %s boolean.

.EX
.B setsebool -P %s 1
.EE
""" % (desc,(", ".join(nsswitch_types)), i, i)

        self.fd.write(nsswitchbooltext)

    def process_types(self):
        if len(self.ptypes) == 0:
            return
        self.fd.write(r"""
.SH PROCESS TYPES
SELinux defines process types (domains) for each process running on the system
.PP
You can see the context of a process using the \fB\-Z\fP option to \fBps\bP
.PP
Policy governs the access confined processes have to files. 
SELinux %(domainname)s policy is very flexible allowing users to setup their %(domainname)s processes in as secure a method as possible.
.PP 
The following process types are defined for %(domainname)s:
""" % {'domainname':self.domainname})
        self.fd.write("""
.EX
.B %s 
.EE""" % ", ".join(self.ptypes))
        self.fd.write("""
.PP
Note: 
.B semanage permissive -a PROCESS_TYPE 
can be used to make a process type permissive. Permissive process types are not denied access by SELinux. AVC messages will still be generated.
""")

    def port_types(self):
        self.ports = []
        for f in port_types:
            if f.startswith(self.short_name):
                self.ports.append(f)

        if len(self.ports) == 0:
            return
        self.fd.write("""
.SH PORT TYPES
SELinux defines port types to represent TCP and UDP ports. 
.PP
You can see the types associated with a port by using the following command: 

.B semanage port -l

.PP
Policy governs the access confined processes have to these ports. 
SELinux %(domainname)s policy is very flexible allowing users to setup their %(domainname)s processes in as secure a method as possible.
.PP 
The following port types are defined for %(domainname)s:""" % {'domainname':self.domainname})

        for p in self.ports:
            self.fd.write("""

.EX
.TP 5
.B %s 
.TP 10
.EE
""" % p)
            once = True
            for prot in ( "tcp", "udp" ):
               if (p,prot) in portrecs:
                    if once:
                        self.fd.write("""

Default Defined Ports:""")
                    once = False
                    self.fd.write(r"""
%s %s
.EE""" % (prot, ",".join(portrecs[(p,prot)])))

    def file_context(self):
        self.fd.write(r"""
.SH FILE CONTEXTS
SELinux requires files to have an extended attribute to define the file type. 
.PP
You can see the context of a file using the \fB\-Z\fP option to \fBls\bP
.PP
Policy governs the access confined processes have to these files. 
SELinux %(domainname)s policy is very flexible allowing users to setup their %(domainname)s processes in as secure a method as possible.
.PP 
The following file types are defined for %(domainname)s:
""" % {'domainname':self.domainname})
        for f in file_types:
            if f.startswith(self.domainname):
                self.fd.write("""

.EX
.PP
.B %s 
.EE

- Set files with the %s type, if you want to %s
""" % (f, f, self.explain(f)))

                if f in files_dict:
                    plural = ""
                    if len(files_dict[f]) > 1:
                        plural = "s"
                        self.fd.write("""
.br
.TP 5
Path%s: 
%s""" % (plural, files_dict[f][0][0]))
                        for x in files_dict[f][1:]:
                            self.fd.write(", %s" % x[0])

        self.fd.write("""

.PP
Note: File context can be temporarily modified with the chcon command.  If you want to permanently change the file context you need to use the 
.B semanage fcontext 
command.  This will modify the SELinux labeling database.  You will need to use
.B restorecon
to apply the labels.
""")

    def see_also(self):
	    ret = ""
	    prefix = self.short_name.split("_")[0]
	    for d in domains:
		    if d == self.domainname:
			    continue
		    if d.startswith(prefix):
			    ret += ", %s_selinux(8)" % d
		    if self.domainname.startswith(d):
			    ret += ", %s_selinux(8)" % d
	    self.fd.write(ret)

    def public_content(self):
        if len(self.anon_list) > 0:
            self.fd.write("""
.SH SHARING FILES
If you want to share files with multiple domains (Apache, FTP, rsync, Samba), you can set a file context of public_content_t and public_content_rw_t.  These context allow any of the above domains to read the content.  If you want a particular domain to write to the public_content_rw_t domain, you must set the appropriate boolean.
.TP
Allow %(domainname)s servers to read the /var/%(domainname)s directory by adding the public_content_t file type to the directory and by restoring the file type.
.PP
.B
semanage fcontext -a -t public_content_t "/var/%(domainname)s(/.*)?"
.br
.B restorecon -F -R -v /var/%(domainname)s
.pp
.TP
Allow %(domainname)s servers to read and write /var/tmp/incoming by adding the public_content_rw_t type to the directory and by restoring the file type.  This also requires the allow_%(domainname)sd_anon_write boolean to be set.
.PP
.B
semanage fcontext -a -t public_content_rw_t "/var/%(domainname)s/incoming(/.*)?"
.br
.B restorecon -F -R -v /var/%(domainname)s/incoming

"""  % {'domainname':self.domainname})
            for b in self.anon_list:
                desc = seobject.booleans_dict[b][2][0].lower() + seobject.booleans_dict[b][2][1:]
                self.fd.write("""
.PP
If you want to %s, you must turn on the %s boolean.

.EX
.B setsebool -P %s 1
.EE
""" % (desc, b, b))

    def footer(self):
        self.fd.write("""
.SH "COMMANDS"
.B semanage fcontext
can also be used to manipulate default file context mappings.
.PP
.B semanage permissive
can also be used to manipulate whether or not a process type is permissive.
.PP
.B semanage module
can also be used to enable/disable/install/remove policy modules.
""")

        if len(self.ports) > 0:
            self.fd.write("""
.B semanage port
can also be used to manipulate the port definitions
""")

        if self.booltext != "":        
            self.fd.write("""
.B semanage boolean
can also be used to manipulate the booleans
""")

        self.fd.write("""
.PP
.B system-config-selinux 
is a GUI tool available to customize SELinux policy settings.

.SH AUTHOR	
This manual page was auto-generated by genman.py.

.SH "SEE ALSO"
selinux(8), %s(8), semanage(8), restorecon(8), chcon(1)
""" % self.domainname)

        if self.booltext != "":        
            self.fd.write(", setsebool(8)")

	self.see_also()

    def valid_write(self, check, attributes):
            if check in [ self.type, "domain" ]:
		    return False
	    if check.endswith("_t"):
		    for a in attributes:
			    if a in types[check]:
				    return False
	    return True

    def entrypoints(self):
        entrypoints = map(lambda x: x['tcontext'], setools.sesearch([setools.ALLOW],{'scontext':self.type,  'permlist':['entrypoint'], 'class':'file'}))
	if entrypoints == None:
		return
        self.fd.write ("""
.SH "ENTRYPOINTS"
""")
	if len(entrypoints) > 1:
		entrypoints_str = "\"%s\" file types" % ",".join(entrypoints)
	else:
		entrypoints_str = "\"%s\" file type" % entrypoints[0]
		
        self.fd.write ("""
The %s_t SELinux type can be entered via the %s.  The default entrypoint paths for the %s_t domain are the following:"
"""   %	(self.domainname, entrypoints_str, self.domainname))
	paths=[]
	for entrypoint in entrypoints:
		for f in fdict:
			if fdict[f] and entrypoint in fdict[f]:
				paths.append(f[0])
	
	self.fd.write("""
%s""" % ", ".join(paths))

    def writes(self):
        permlist = setools.sesearch([setools.ALLOW],{'scontext':self.type,  'permlist':['open', 'write'], 'class':'file'})
	if permlist == None or len(permlist) == 0:
		return

        all_writes = []
	attributes = ["proc_type", "sysctl_type"]
	for i in permlist:
		if not i['tcontext'].endswith("_t"):
			attributes.append(i['tcontext'])

        for i in permlist:
		if self.valid_write(i['tcontext'],attributes):
			if i['tcontext'] not in all_writes:
				all_writes.append(i['tcontext'])

	if len(all_writes) == 0:
		return
        self.fd.write ("""
.SH "MANAGED FILES"
""")
        self.fd.write ("""
The SELinux process type %s_t can manage files labeled with the following file types.  The paths listed are the default paths for these file types.  Note the processes UID still need to have DAC permissions.
"""   %	self.domainname)

        all_writes.sort()
        if "file_type" in all_writes:
            all_writes = [ "file_type" ]
        for f in all_writes:
            self.fd.write("""
.br
.B %s

""" % f)
            if f in fcdict:
                for path in fcdict[f]:
                    self.fd.write("""\t%s
.br
""" % path)

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

        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_t: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.domainname})

        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.domainname})

    def can_sudo(self):
        sudotype = "%s_sudo_t" % self.domainname
        self.fd.write("""
.SH SUDO
""")
        if sudotype in types:
            role = self.domainname + "_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.domainname } )
            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.domainname } )

                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.domainname, "roles": " ".join([role] + role_allows[role]) } )
            else:
                self.fd.write("""
The SELinux type %s_t is not allowed to execute sudo. 
""" % self.domainname)

    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.domainname)

        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.domainname)

        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.domainname)

    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.domainname)
            else:
                self.fd.write("""
The SELinux user %s_u is not able to X Windows login.
""" % self.domainname)

    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.domainname)
            else:
                self.fd.write("""
The SELinux user %s_u is not able to terminal login.
""" % self.domainname)

    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.domainname, 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.domainname))
                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.domainname)

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

    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.domainname, '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.domainname})

        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 (RBAC), some Linux roles are login roles, while other roles need to be transition into. 

.I Note: 
Examples in this man page will use the 
.B staff_u 
SELinux user.

Non login roles are usually used for administrative tasks. For example, tasks that require root privileges.  Roles control which types a user can run processes with. Roles often have default types assigned to them. 

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

The 
.B newrole 
program to transition directly to this role.

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

.B sudo 
is the preferred method to do transition from one role to another.  You setup sudo to transition to %(user)s_r by adding a similar line to the /etc/sudoers file.

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

When using a a non login role, you need to setup SELinux so that your SELinux user can reach %(user)s_r role.

Execute the following to see all of the assigned SELinux roles:

.B semanage user -l

You need to add %(user)s_r to the staff_u user.  You could setup the staff_u user to be able to use the %(user)s_r role with a command like:

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

""" % {'desc': self.desc, 'user':self.domainname})
        troles = []
        for i in role_allows:
            if self.domainname +"_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.domainname))

class CheckPath(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        if not os.path.exists(values):
		raise ValueError("%s does not exist" % values)

if __name__ == '__main__':
	parser = argparse.ArgumentParser(description='Generate SELinux man pages')
	parser.add_argument("-p", "--path", dest="path", default="/tmp", 
			    action=CheckPath,
			    help="Path in which tool will create SELinux man pages")
	group = parser.add_mutually_exclusive_group(required=True)
	group.add_argument("-a", "--all", dest="all", default=False,
			   action="store_true",
			   help="All domains")
	group.add_argument("-d", "--domain", nargs="+", 
			   help="Domain name(s) of man pages to be created")

	try:
		args = parser.parse_args()
		path = args.path
		if args.all:
			test_domains = domains
		else:
			test_domains = args.domain

		for domain in test_domains:
			print domain
			ManPage(domain, path)

	except ValueError,e:
		sys.stderr.write("%s: %s" % (e.__class__.__name__, str(e)))
		sys.exit(1)
	except Exception,e:
		sys.stderr.write("exception %s: %s" % (e.__class__.__name__, str(e)))
		sys.exit(1)