Chris PeBenito 17de1b
#! /usr/bin/env python
Chris PeBenito 17de1b
# Copyright (C) 2004 Tresys Technology, LLC
Chris PeBenito 17de1b
# see file 'COPYING' for use and warranty information
Chris PeBenito 17de1b
#
Chris PeBenito 17de1b
# genhomedircon - this script is used to generate file context
Chris PeBenito 17de1b
# configuration entries for user home directories based on their
Chris PeBenito 17de1b
# default roles and is run when building the policy. Specifically, we
Chris PeBenito 17de1b
# replace HOME_ROOT, HOME_DIR, and ROLE macros in .fc files with
Chris PeBenito 17de1b
# generic and user-specific values.
Chris PeBenito 17de1b
#
Chris PeBenito 17de1b
# Based off original script by Dan Walsh, <dwalsh@redhat.com>
Chris PeBenito 17de1b
#
Chris PeBenito 17de1b
# ASSUMPTIONS:
Chris PeBenito 17de1b
#
Chris PeBenito 17de1b
# The file CONTEXTDIR/files/homedir_template exists.  This file is used to
Chris PeBenito 17de1b
# set up the home directory context for each real user.
Chris PeBenito 17de1b
# 
Chris PeBenito 17de1b
# If a user has more than one role in CONTEXTDIR/local.users, genhomedircon uses
Chris PeBenito 17de1b
#  the first role in the list.
Chris PeBenito 17de1b
#
Chris PeBenito 17de1b
# If a user is not listed in CONTEXTDIR/local.users, he will default to user_u, role user
Chris PeBenito 17de1b
#
Chris PeBenito 17de1b
# "Real" users (as opposed to system users) are those whose UID is greater than
Chris PeBenito 17de1b
#  or equal STARTING_UID (usually 500) and whose login is not a member of
Chris PeBenito 17de1b
#  EXCLUDE_LOGINS.  Users who are explicitly defined in CONTEXTDIR/local.users
Chris PeBenito 17de1b
#  are always "real" (including root, in the default configuration).
Chris PeBenito 17de1b
#
Chris PeBenito 17de1b
#  
Chris PeBenito 17de1b
# Old ASSUMPTIONS:
Chris PeBenito 17de1b
#
Chris PeBenito 17de1b
# If a user has more than one role in FILECONTEXTDIR/users, genhomedircon uses
Chris PeBenito 17de1b
#  the first role in the list.
Chris PeBenito 17de1b
#
Chris PeBenito 17de1b
# If a user is not listed in FILECONTEXTDIR/users, genhomedircon assumes that
Chris PeBenito 17de1b
#  the user's home dir will be found in one of the HOME_ROOTs.
Chris PeBenito 17de1b
#
Chris PeBenito 17de1b
# "Real" users (as opposed to system users) are those whose UID is greater than
Chris PeBenito 17de1b
#  or equal STARTING_UID (usually 500) and whose login is not a member of
Chris PeBenito 17de1b
#  EXCLUDE_LOGINS.  Users who are explicitly defined in FILECONTEXTDIR/users
Chris PeBenito 17de1b
#  are always "real" (including root, in the default configuration).
Chris PeBenito 17de1b
#
Chris PeBenito 17de1b
Chris PeBenito 17de1b
import commands, sys, os, pwd, string, getopt, re
Chris PeBenito 17de1b
Chris PeBenito 17de1b
EXCLUDE_LOGINS=["/sbin/nologin", "/bin/false"]
Chris PeBenito 17de1b
Chris PeBenito 17de1b
def getStartingUID():
Chris PeBenito 17de1b
	starting_uid = sys.maxint
Chris PeBenito 17de1b
	rc=commands.getstatusoutput("grep -h '^UID_MIN' /etc/login.defs")
Chris PeBenito 17de1b
	if rc[0] == 0:
Chris PeBenito 17de1b
		uid_min = re.sub("^UID_MIN[^0-9]*", "", rc[1])
Chris PeBenito 17de1b
		#stip any comment from the end of the line
Chris PeBenito 17de1b
		uid_min = uid_min.split("#")[0]
Chris PeBenito 17de1b
		uid_min = uid_min.strip()
Chris PeBenito 17de1b
		if int(uid_min) < starting_uid:
Chris PeBenito 17de1b
			starting_uid = int(uid_min)
Chris PeBenito 17de1b
	rc=commands.getstatusoutput("grep -h '^LU_UIDNUMBER' /etc/libuser.conf")
Chris PeBenito 17de1b
	if rc[0] == 0:
Chris PeBenito 17de1b
		lu_uidnumber = re.sub("^LU_UIDNUMBER[^0-9]*", "", rc[1])
Chris PeBenito 17de1b
		#stip any comment from the end of the line
Chris PeBenito 17de1b
		lu_uidnumber = re.sub("[ \t].*", "", lu_uidnumber)
Chris PeBenito 17de1b
		lu_uidnumber = lu_uidnumber.split("#")[0]
Chris PeBenito 17de1b
		lu_uidnumber = lu_uidnumber.strip()
Chris PeBenito 17de1b
		if int(lu_uidnumber) < starting_uid:
Chris PeBenito 17de1b
			starting_uid = int(lu_uidnumber)
Chris PeBenito 17de1b
	if starting_uid == sys.maxint:
Chris PeBenito 17de1b
		starting_uid = 500
Chris PeBenito 17de1b
	return starting_uid
Chris PeBenito 17de1b
Chris PeBenito 17de1b
#############################################################################
Chris PeBenito 17de1b
#
Chris PeBenito 17de1b
# This section is just for backwards compatability
Chris PeBenito 17de1b
#
Chris PeBenito 17de1b
#############################################################################
Chris PeBenito 17de1b
def getPrefixes():
Chris PeBenito 17de1b
	ulist = pwd.getpwall()
Chris PeBenito 17de1b
	STARTING_UID=getStartingUID()
Chris PeBenito 17de1b
	prefixes = {}
Chris PeBenito 17de1b
	for u in ulist:
Chris PeBenito 17de1b
		if u[2] >= STARTING_UID and \
Chris PeBenito 17de1b
				not u[6] in EXCLUDE_LOGINS and \
Chris PeBenito 17de1b
				u[5] != "/" and \
Chris PeBenito 17de1b
				string.count(u[5], "/") > 1:
Chris PeBenito 17de1b
			prefix = u[5][:string.rfind(u[5], "/")]
Chris PeBenito 17de1b
			if not prefixes.has_key(prefix):
Chris PeBenito 17de1b
				prefixes[prefix] = ""
Chris PeBenito 17de1b
	return prefixes
Chris PeBenito 17de1b
 
Chris PeBenito 17de1b
def getUsers(filecontextdir):
Chris PeBenito 17de1b
	rc = commands.getstatusoutput("grep ^user %s/users" % filecontextdir)
Chris PeBenito 17de1b
	udict = {}
Chris PeBenito 17de1b
	if rc[0] == 0:
Chris PeBenito 17de1b
		ulist = rc[1].strip().split("\n")
Chris PeBenito 17de1b
		for u in ulist:
Chris PeBenito 17de1b
			user = u.split()
Chris PeBenito 17de1b
			try:
Chris PeBenito 17de1b
				if user[1] == "user_u" or user[1] == "system_u":
Chris PeBenito 17de1b
					continue
Chris PeBenito 17de1b
				# !!! chooses first role in the list to use in the file context !!!
Chris PeBenito 17de1b
				role = user[3]
Chris PeBenito 17de1b
				if role == "{":
Chris PeBenito 17de1b
					role = user[4]
Chris PeBenito 17de1b
				role = role.split("_r")[0]
Chris PeBenito 17de1b
				home = pwd.getpwnam(user[1])[5]
Chris PeBenito 17de1b
				if home == "/":
Chris PeBenito 17de1b
					continue
Chris PeBenito 17de1b
				prefs = {}
Chris PeBenito 17de1b
				prefs["role"] = role
Chris PeBenito 17de1b
				prefs["home"] = home
Chris PeBenito 17de1b
				udict[user[1]] = prefs
Chris PeBenito 17de1b
			except KeyError:
Chris PeBenito 17de1b
				sys.stderr.write("The user \"%s\" is not present in the passwd file, skipping...\n" % user[1])
Chris PeBenito 17de1b
	return udict
Chris PeBenito 17de1b
Chris PeBenito 17de1b
def update(filecontext, user, prefs):
Chris PeBenito 17de1b
	rc=commands.getstatusoutput("grep -h '^HOME_DIR' %s | grep -v vmware | sed -e 's|HOME_DIR|%s|' -e 's/ROLE/%s/' -e 's/system_u/%s/'" % (filecontext, prefs["home"], prefs["role"], user))
Chris PeBenito 17de1b
	if rc[0] == 0:
Chris PeBenito 17de1b
		print rc[1]
Chris PeBenito 17de1b
	else:
Chris PeBenito 17de1b
		errorExit(string.join("grep/sed error ", rc[1]))
Chris PeBenito 17de1b
	return rc
Chris PeBenito 17de1b
Chris PeBenito 17de1b
def oldgenhomedircon(filecontextdir, filecontext):
Chris PeBenito 17de1b
	sys.stderr.flush()
Chris PeBenito 17de1b
Chris PeBenito 17de1b
	if os.path.isdir(filecontextdir) == 0:
Chris PeBenito 17de1b
		sys.stderr.write("New usage is the following\n")
Chris PeBenito 17de1b
		usage()
Chris PeBenito 17de1b
        #We are going to define home directory used by libuser and show-utils as a home directory root
Chris PeBenito 17de1b
        prefixes = {}
Chris PeBenito 17de1b
        rc=commands.getstatusoutput("grep -h '^HOME' /etc/default/useradd")
Chris PeBenito 17de1b
        if rc[0] == 0:
Chris PeBenito 17de1b
                homedir = rc[1].split("=")[1]
Chris PeBenito 17de1b
                homedir = homedir.split("#")[0]
Chris PeBenito 17de1b
                homedir = homedir.strip()
Chris PeBenito 17de1b
                if not prefixes.has_key(homedir):
Chris PeBenito 17de1b
                        prefixes[homedir] = ""
Chris PeBenito 17de1b
        else:
Chris PeBenito 17de1b
                #rc[0] == 256 means the file was there, we read it, but the grep didn't match
Chris PeBenito 17de1b
                if rc[0] != 256:
Chris PeBenito 17de1b
                        sys.stderr.write("%s\n" % rc[1])
Chris PeBenito 17de1b
                        sys.stderr.write("You do not have access to /etc/default/useradd HOME=\n")
Chris PeBenito 17de1b
                        sys.stderr.flush()
Chris PeBenito 17de1b
Chris PeBenito 17de1b
Chris PeBenito 17de1b
        rc=commands.getstatusoutput("grep -h '^LU_HOMEDIRECTORY' /etc/libuser.conf")
Chris PeBenito 17de1b
        if rc[0] == 0:
Chris PeBenito 17de1b
                homedir = rc[1].split("=")[1]
Chris PeBenito 17de1b
                homedir = homedir.split("#")[0]
Chris PeBenito 17de1b
                homedir = homedir.strip()
Chris PeBenito 17de1b
                homedir = re.sub(r"[^/a-zA-Z0-9].*$", "", homedir)
Chris PeBenito 17de1b
                if not prefixes.has_key(homedir):
Chris PeBenito 17de1b
                        prefixes[homedir] = ""
Chris PeBenito 17de1b
Chris PeBenito 17de1b
        #the idea is that we need to find all of the home_root_t directories we do this by just accepting
Chris PeBenito 17de1b
        #any default home directory defined by either /etc/libuser.conf or /etc/default/useradd
Justin P. Mattock d5932a
        #we then get the potential home directory roots from /etc/passwd or nis or wherever and look at
Chris PeBenito 17de1b
        #the defined homedir for all users with UID > STARTING_UID.  This list of possible root homedirs
Chris PeBenito 17de1b
        #is then checked to see if it has an explicite context defined in the file_contexts.  Explicit
Chris PeBenito 17de1b
        #is any regex that would match it which does not end with .*$ or .+$ since those are general
Chris PeBenito 17de1b
        #recursive matches.  We then take any regex which ends with [pattern](/.*)?$ and just check against
Chris PeBenito 17de1b
        #[pattern]
Chris PeBenito 17de1b
        potential_prefixes = getPrefixes()
Chris PeBenito 17de1b
        prefix_regex = {}
Chris PeBenito 17de1b
        #this works by grepping the file_contexts for
Chris PeBenito 17de1b
        # 1. ^/ makes sure this is not a comment
Chris PeBenito 17de1b
        # 2. prints only the regex in the first column first cut on \t then on space
Chris PeBenito 17de1b
        rc=commands.getstatusoutput("grep \"^/\" %s | cut -f 1 | cut -f 1 -d \" \" " %  (sys.argv[2]) )
Chris PeBenito 17de1b
        if rc[0] == 0:
Chris PeBenito 17de1b
                prefix_regex = rc[1].split("\n")
Chris PeBenito 17de1b
        else:
Chris PeBenito 17de1b
                sys.stderr.write("%s\n" % rc[1])
Chris PeBenito 17de1b
                sys.stderr.write("You do not have access to grep/cut/the file contexts\n")
Chris PeBenito 17de1b
                sys.stderr.flush()
Chris PeBenito 17de1b
        for potential in potential_prefixes.keys():
Chris PeBenito 17de1b
                addme = 1
Chris PeBenito 17de1b
                for regex in prefix_regex:
Chris PeBenito 17de1b
                        #match a trailing (/*)? which is actually a bug in rpc_pipefs
Chris PeBenito 17de1b
                        regex = re.sub("\(/\*\)\?$", "", regex)
Chris PeBenito 17de1b
                        #match a trailing .+
Chris PeBenito 17de1b
                        regex = re.sub("\.+$", "", regex)
Chris PeBenito 17de1b
                        #match a trailing .*
Chris PeBenito 17de1b
                        regex = re.sub("\.\*$", "", regex)
Chris PeBenito 17de1b
                        #strip a (/.*)? which matches anything trailing to a /*$ which matches trailing /'s
Chris PeBenito 17de1b
                        regex = re.sub("\(\/\.\*\)\?", "", regex)
Chris PeBenito 17de1b
                        regex = regex + "/*$"
Chris PeBenito 17de1b
                        if re.search(regex, potential, 0):
Chris PeBenito 17de1b
                                addme = 0
Chris PeBenito 17de1b
                if addme == 1:
Chris PeBenito 17de1b
                        if not prefixes.has_key(potential):
Chris PeBenito 17de1b
                                prefixes[potential] = ""
Chris PeBenito 17de1b
Chris PeBenito 17de1b
Chris PeBenito 17de1b
        if prefixes.__eq__({}):
Chris PeBenito 17de1b
                sys.stderr.write("LU_HOMEDIRECTORY not set in /etc/libuser.conf\n")
Chris PeBenito 17de1b
                sys.stderr.write("HOME= not set in /etc/default/useradd\n")
Chris PeBenito 17de1b
                sys.stderr.write("And no users with a reasonable homedir found in passwd/nis/ldap/etc...\n")
Chris PeBenito 17de1b
                sys.stderr.write("Assuming /home is the root of home directories\n")
Chris PeBenito 17de1b
                sys.stderr.flush()
Chris PeBenito 17de1b
                prefixes["/home"] = ""
Chris PeBenito 17de1b
Chris PeBenito 17de1b
	# There may be a more elegant sed script to expand a macro to multiple lines, but this works
Chris PeBenito 17de1b
	sed_root = "h; s|^HOME_ROOT|%s|" % (string.join(prefixes.keys(), "|; p; g; s|^HOME_ROOT|"),)
Chris PeBenito 17de1b
	sed_dir = "h; s|^HOME_DIR|%s/[^/]+|; s|ROLE_|user_|" % (string.join(prefixes.keys(), "/[^/]+|; s|ROLE_|user_|; p; g; s|^HOME_DIR|"),)
Chris PeBenito 17de1b
Chris PeBenito 17de1b
	# Fill in HOME_ROOT, HOME_DIR, and ROLE for users not explicitly defined in /etc/security/selinux/src/policy/users
Chris PeBenito 17de1b
	rc=commands.getstatusoutput("sed -e \"/^HOME_ROOT/{%s}\" -e \"/^HOME_DIR/{%s}\" %s" % (sed_root, sed_dir, filecontext))
Chris PeBenito 17de1b
	if rc[0] == 0:
Chris PeBenito 17de1b
		print rc[1]
Chris PeBenito 17de1b
	else:
Chris PeBenito 17de1b
		errorExit(string.join("sed error ", rc[1]))
Chris PeBenito 17de1b
Chris PeBenito 17de1b
	users = getUsers(filecontextdir)
Chris PeBenito 17de1b
	print "\n#\n# User-specific file contexts\n#\n"
Chris PeBenito 17de1b
Chris PeBenito 17de1b
	# Fill in HOME and ROLE for users that are defined
Chris PeBenito 17de1b
	for u in users.keys():
Chris PeBenito 17de1b
		update(filecontext, u, users[u]) 
Chris PeBenito 17de1b
Chris PeBenito 17de1b
#############################################################################
Chris PeBenito 17de1b
#
Chris PeBenito 17de1b
# End of backwards compatability section
Chris PeBenito 17de1b
#
Chris PeBenito 17de1b
#############################################################################
Chris PeBenito 17de1b
Chris PeBenito 17de1b
def getDefaultHomeDir():
Chris PeBenito 17de1b
	ret = []
Chris PeBenito 17de1b
	rc=commands.getstatusoutput("grep -h '^HOME' /etc/default/useradd")
Chris PeBenito 17de1b
	if rc[0] == 0:
Chris PeBenito 17de1b
		homedir = rc[1].split("=")[1]
Chris PeBenito 17de1b
		homedir = homedir.split("#")[0]
Chris PeBenito 17de1b
		homedir = homedir.strip()
Chris PeBenito 17de1b
		if not homedir in ret:
Chris PeBenito 17de1b
			ret.append(homedir)
Chris PeBenito 17de1b
	else:
Chris PeBenito 17de1b
		#rc[0] == 256 means the file was there, we read it, but the grep didn't match
Chris PeBenito 17de1b
		if rc[0] != 256:
Chris PeBenito 17de1b
			sys.stderr.write("%s\n" % rc[1])
Chris PeBenito 17de1b
			sys.stderr.write("You do not have access to /etc/default/useradd HOME=\n")
Chris PeBenito 17de1b
			sys.stderr.flush()
Chris PeBenito 17de1b
	rc=commands.getstatusoutput("grep -h '^LU_HOMEDIRECTORY' /etc/libuser.conf")
Chris PeBenito 17de1b
	if rc[0] == 0:
Chris PeBenito 17de1b
		homedir = rc[1].split("=")[1]
Chris PeBenito 17de1b
		homedir = homedir.split("#")[0]
Chris PeBenito 17de1b
		homedir = homedir.strip()
Chris PeBenito 17de1b
		if not homedir in ret:
Chris PeBenito 17de1b
			ret.append(homedir)
Chris PeBenito 17de1b
	else:
Chris PeBenito 17de1b
		#rc[0] == 256 means the file was there, we read it, but the grep didn't match
Chris PeBenito 17de1b
		if rc[0] != 256:
Chris PeBenito 17de1b
			sys.stderr.write("%s\n" % rc[1])
Chris PeBenito 17de1b
			sys.stderr.write("You do not have access to /etc/libuser.conf LU_HOMEDIRECTORY=\n")
Chris PeBenito 17de1b
			sys.stderr.flush()
Chris PeBenito 17de1b
	if ret == []:
Chris PeBenito 17de1b
		ret.append("/home")
Chris PeBenito 17de1b
	return ret
Chris PeBenito 17de1b
Chris PeBenito 17de1b
def getSELinuxType(directory):
Chris PeBenito 17de1b
	rc=commands.getstatusoutput("grep ^SELINUXTYPE= %s/config" % directory)
Chris PeBenito 17de1b
	if rc[0]==0:
Chris PeBenito 17de1b
		return rc[1].split("=")[-1].strip()
Chris PeBenito 17de1b
	return "targeted"
Chris PeBenito 17de1b
Chris PeBenito 17de1b
def usage(error = ""):
Chris PeBenito 17de1b
	if error != "":
Chris PeBenito 17de1b
		sys.stderr.write("%s\n" % error)
Chris PeBenito 17de1b
	sys.stderr.write("Usage: %s [ -d selinuxdir ] [-n | --nopasswd] [-t selinuxtype ]\n" % sys.argv[0])
Chris PeBenito 17de1b
	sys.stderr.flush()
Chris PeBenito 17de1b
	sys.exit(1)
Chris PeBenito 17de1b
Chris PeBenito 17de1b
def warning(warning = ""):
Chris PeBenito 17de1b
	sys.stderr.write("%s\n" % warning)
Chris PeBenito 17de1b
	sys.stderr.flush()
Chris PeBenito 17de1b
	
Chris PeBenito 17de1b
def errorExit(error):
Chris PeBenito 17de1b
	sys.stderr.write("%s exiting for: " % sys.argv[0])
Chris PeBenito 17de1b
	sys.stderr.write("%s\n" % error)
Chris PeBenito 17de1b
	sys.stderr.flush()
Chris PeBenito 17de1b
	sys.exit(1)
Chris PeBenito 17de1b
Chris PeBenito 17de1b
class selinuxConfig:
Chris PeBenito 17de1b
	def __init__(self, selinuxdir="/etc/selinux", type="targeted", usepwd=1):
Chris PeBenito 17de1b
		self.type=type
Chris PeBenito 17de1b
		self.selinuxdir=selinuxdir +"/"
Chris PeBenito 17de1b
		self.contextdir="/contexts"
Chris PeBenito 17de1b
		self.filecontextdir=self.contextdir+"/files"
Chris PeBenito 17de1b
		self.usepwd=usepwd
Chris PeBenito 17de1b
Chris PeBenito 17de1b
	def getFileContextDir(self):
Chris PeBenito 17de1b
		return self.selinuxdir+self.type+self.filecontextdir
Chris PeBenito 17de1b
Chris PeBenito 17de1b
	def getFileContextFile(self):
Chris PeBenito 17de1b
		return self.getFileContextDir()+"/file_contexts"
Chris PeBenito 17de1b
	
Chris PeBenito 17de1b
	def getContextDir(self):
Chris PeBenito 17de1b
		return self.selinuxdir+self.type+self.contextdir
Chris PeBenito 17de1b
Chris PeBenito 17de1b
	def getHomeDirTemplate(self):
Chris PeBenito 17de1b
		return self.getFileContextDir()+"/homedir_template"
Chris PeBenito 17de1b
Chris PeBenito 17de1b
	def getHomeRootContext(self, homedir):
Chris PeBenito 17de1b
		rc=commands.getstatusoutput("grep HOME_ROOT  %s | sed -e \"s|^HOME_ROOT|%s|\"" % ( self.getHomeDirTemplate(), homedir))
Chris PeBenito 17de1b
		if rc[0] == 0:
Chris PeBenito 17de1b
			return rc[1]+"\n"
Chris PeBenito 17de1b
		else:
Chris PeBenito 17de1b
			errorExit(string.join("sed error ", rc[1]))
Chris PeBenito 17de1b
Chris PeBenito 17de1b
	def getUsersFile(self):
Chris PeBenito 17de1b
		return self.selinuxdir+self.type+"/users/local.users"
Chris PeBenito 17de1b
Chris PeBenito 17de1b
	def getSystemUsersFile(self):
Chris PeBenito 17de1b
		return self.selinuxdir+self.type+"/users/system.users"
Chris PeBenito 17de1b
		
Chris PeBenito 17de1b
	def heading(self):
Chris PeBenito 17de1b
		ret = "\n#\n#\n# User-specific file contexts, generated via %s\n" % sys.argv[0]
Chris PeBenito 17de1b
		ret += "# edit %s to change file_context\n#\n#\n" % self.getUsersFile()
Chris PeBenito 17de1b
		return ret
Chris PeBenito 17de1b
Chris PeBenito 17de1b
	def getUsers(self):
Chris PeBenito 17de1b
		users=""
Chris PeBenito 17de1b
		rc = commands.getstatusoutput('grep "^user" %s' % self.getSystemUsersFile())
Chris PeBenito 17de1b
		if rc[0] == 0:
Chris PeBenito 17de1b
			users+=rc[1]+"\n"
Chris PeBenito 17de1b
		rc = commands.getstatusoutput("grep ^user %s" % self.getUsersFile())
Chris PeBenito 17de1b
		if rc[0] == 0:
Chris PeBenito 17de1b
			users+=rc[1]
Chris PeBenito 17de1b
		udict = {}
Chris PeBenito 17de1b
		prefs = {}
Chris PeBenito 17de1b
		if users != "":
Chris PeBenito 17de1b
			ulist = users.split("\n")
Chris PeBenito 17de1b
			for u in ulist:
Chris PeBenito 17de1b
				user = u.split()
Chris PeBenito 17de1b
				try:
Chris PeBenito 17de1b
					if len(user)==0 or user[1] == "user_u" or user[1] == "system_u":
Chris PeBenito 17de1b
						continue
Chris PeBenito 17de1b
					# !!! chooses first role in the list to use in the file context !!!
Chris PeBenito 17de1b
					role = user[3]
Chris PeBenito 17de1b
					if role == "{":
Chris PeBenito 17de1b
						role = user[4]
Chris PeBenito 17de1b
					role = role.split("_r")[0]
Chris PeBenito 17de1b
					home = pwd.getpwnam(user[1])[5]
Chris PeBenito 17de1b
					if home == "/":
Chris PeBenito 17de1b
						continue
Chris PeBenito 17de1b
					prefs = {}
Chris PeBenito 17de1b
					prefs["role"] = role
Chris PeBenito 17de1b
					prefs["home"] = home
Chris PeBenito 17de1b
					udict[user[1]] = prefs
Chris PeBenito 17de1b
				except KeyError:
Chris PeBenito 17de1b
					sys.stderr.write("The user \"%s\" is not present in the passwd file, skipping...\n" % user[1])
Chris PeBenito 17de1b
		return udict
Chris PeBenito 17de1b
Chris PeBenito 17de1b
	def getHomeDirContext(self, user, home, role):
Chris PeBenito 17de1b
		ret="\n\n#\n# Context for user %s\n#\n\n" % user
Chris PeBenito 17de1b
		rc=commands.getstatusoutput("grep '^HOME_DIR' %s | sed -e 's|HOME_DIR|%s|' -e 's/ROLE/%s/' -e 's/system_u/%s/'" % (self.getHomeDirTemplate(), home, role, user))
Chris PeBenito 17de1b
		return ret + rc[1] + "\n"
Chris PeBenito 17de1b
Chris PeBenito 17de1b
	def genHomeDirContext(self):
Chris PeBenito 17de1b
		users = self.getUsers()
Chris PeBenito 17de1b
		ret=""
Chris PeBenito 17de1b
		# Fill in HOME and ROLE for users that are defined
Chris PeBenito 17de1b
		for u in users.keys():
Chris PeBenito 17de1b
			ret += self.getHomeDirContext (u, users[u]["home"], users[u]["role"])
Chris PeBenito 17de1b
		return ret+"\n"
Chris PeBenito 17de1b
Chris PeBenito 17de1b
	def checkExists(self, home):
Chris PeBenito 17de1b
		if commands.getstatusoutput("grep -E '^%s[^[:alnum:]_-]' %s" % (home, self.getFileContextFile()))[0] == 0:
Chris PeBenito 17de1b
			return 0
Chris PeBenito 17de1b
		#this works by grepping the file_contexts for
Chris PeBenito 17de1b
		# 1. ^/ makes sure this is not a comment
Chris PeBenito 17de1b
		# 2. prints only the regex in the first column first cut on \t then on space
Chris PeBenito 17de1b
		rc=commands.getstatusoutput("grep \"^/\" %s | cut -f 1 | cut -f 1 -d \" \" " %  self.getFileContextFile() )
Chris PeBenito 17de1b
		if rc[0] == 0:
Chris PeBenito 17de1b
			prefix_regex = rc[1].split("\n")
Chris PeBenito 17de1b
		else:
Chris PeBenito 17de1b
			sys.stderr.write("%s\n" % rc[1])
Chris PeBenito 17de1b
			sys.stderr.write("You do not have access to grep/cut/the file contexts\n")
Chris PeBenito 17de1b
			sys.stderr.flush()
Chris PeBenito 17de1b
		exists=1
Chris PeBenito 17de1b
		for regex in prefix_regex:
Chris PeBenito 17de1b
			#match a trailing (/*)? which is actually a bug in rpc_pipefs
Chris PeBenito 17de1b
			regex = re.sub("\(/\*\)\?$", "", regex)
Chris PeBenito 17de1b
			#match a trailing .+
Chris PeBenito 17de1b
			regex = re.sub("\.+$", "", regex)
Chris PeBenito 17de1b
			#match a trailing .*
Chris PeBenito 17de1b
			regex = re.sub("\.\*$", "", regex)
Chris PeBenito 17de1b
			#strip a (/.*)? which matches anything trailing to a /*$ which matches trailing /'s
Chris PeBenito 17de1b
			regex = re.sub("\(\/\.\*\)\?", "", regex)
Chris PeBenito 17de1b
			regex = regex + "/*$"
Chris PeBenito 17de1b
			if re.search(regex, home, 0):
Chris PeBenito 17de1b
				exists = 0
Chris PeBenito 17de1b
				break
Chris PeBenito 17de1b
		if exists == 1:
Chris PeBenito 17de1b
			return 1
Chris PeBenito 17de1b
		else:
Chris PeBenito 17de1b
			return 0
Chris PeBenito 17de1b
Chris PeBenito 17de1b
Chris PeBenito 17de1b
	def getHomeDirs(self):
Chris PeBenito 17de1b
		homedirs = []
Chris PeBenito 17de1b
		homedirs = homedirs + getDefaultHomeDir()
Chris PeBenito 17de1b
		starting_uid=getStartingUID()
Chris PeBenito 17de1b
		if self.usepwd==0:
Chris PeBenito 17de1b
			return homedirs
Chris PeBenito 17de1b
		ulist = pwd.getpwall()
Chris PeBenito 17de1b
		for u in ulist:
Chris PeBenito 17de1b
			if u[2] >= starting_uid and \
Chris PeBenito 17de1b
					not u[6] in EXCLUDE_LOGINS and \
Chris PeBenito 17de1b
					u[5] != "/" and \
Chris PeBenito 17de1b
					string.count(u[5], "/") > 1:
Chris PeBenito 17de1b
				homedir = u[5][:string.rfind(u[5], "/")]
Chris PeBenito 17de1b
				if not homedir in homedirs:
Chris PeBenito 17de1b
					if self.checkExists(homedir)==0:
Chris PeBenito 17de1b
						warning("%s is already defined in %s,\n%s will not create a new context." % (homedir, self.getFileContextFile(), sys.argv[0]))
Chris PeBenito 17de1b
					else:
Chris PeBenito 17de1b
						homedirs.append(homedir)
Chris PeBenito 17de1b
Chris PeBenito 17de1b
		homedirs.sort()
Chris PeBenito 17de1b
		return homedirs
Chris PeBenito 17de1b
 
Chris PeBenito 17de1b
	def genoutput(self):
Chris PeBenito 17de1b
		ret= self.heading()
Chris PeBenito 17de1b
		for h in self.getHomeDirs():
Chris PeBenito 17de1b
			ret += self.getHomeDirContext ("user_u" , h+'/[^/]*', "user")
Chris PeBenito 17de1b
			ret += self.getHomeRootContext(h)
Chris PeBenito 17de1b
		ret += self.genHomeDirContext()
Chris PeBenito 17de1b
		return ret
Chris PeBenito 17de1b
Chris PeBenito 17de1b
	def printout(self):
Chris PeBenito 17de1b
		print self.genoutput()
Chris PeBenito 17de1b
Chris PeBenito 17de1b
	def write(self):
Chris PeBenito 17de1b
		try:
Chris PeBenito 17de1b
			fd = open(self.getFileContextDir()+"/file_contexts.homedirs", "w")
Chris PeBenito 17de1b
			fd.write(self.genoutput())
Chris PeBenito 17de1b
			fd.close()
Chris PeBenito 17de1b
		except IOError, error:
Chris PeBenito 17de1b
			sys.stderr.write("%s: %s\n" % ( sys.argv[0], error ))
Chris PeBenito 17de1b
Chris PeBenito 17de1b
Chris PeBenito 17de1b
Chris PeBenito 17de1b
#
Chris PeBenito 17de1b
# This script will generate home dir file context
Chris PeBenito 17de1b
# based off the homedir_template file, entries in the password file, and
Chris PeBenito 17de1b
#
Chris PeBenito 17de1b
try:
Chris PeBenito 17de1b
	usepwd=1
Chris PeBenito 17de1b
	directory="/etc/selinux"
Chris PeBenito 17de1b
	type=None
Chris PeBenito 17de1b
	gopts, cmds = getopt.getopt(sys.argv[1:], 'nd:t:', ['help',
Chris PeBenito 17de1b
						'type=',
Chris PeBenito 17de1b
						'nopasswd',
Chris PeBenito 17de1b
						'dir='])
Chris PeBenito 17de1b
	for o,a in gopts:
Chris PeBenito 17de1b
		if o == '--type' or o == "-t":
Chris PeBenito 17de1b
			type=a
Chris PeBenito 17de1b
		if o == '--nopasswd'  or o == "-n":
Chris PeBenito 17de1b
			usepwd=0
Chris PeBenito 17de1b
		if o == '--dir'  or o == "-d":
Chris PeBenito 17de1b
			directory=a
Chris PeBenito 17de1b
		if o == '--help':
Chris PeBenito 17de1b
			usage()
Chris PeBenito 17de1b
Chris PeBenito 17de1b
Chris PeBenito 17de1b
	if type==None:
Chris PeBenito 17de1b
		type=getSELinuxType(directory)
Chris PeBenito 17de1b
Chris PeBenito 17de1b
	if len(cmds) == 2:
Chris PeBenito 17de1b
		oldgenhomedircon(cmds[0], cmds[1])
Chris PeBenito 17de1b
		sys.exit(0)
Chris PeBenito 17de1b
Chris PeBenito 17de1b
	if len(cmds) != 0:
Chris PeBenito 17de1b
		usage()
Chris PeBenito 17de1b
	selconf=selinuxConfig(directory, type, usepwd)
Chris PeBenito 17de1b
	selconf.write()
Chris PeBenito 17de1b
Chris PeBenito 17de1b
except getopt.error, error:
Chris PeBenito 17de1b
	errorExit(string.join("Options Error ", error))
Chris PeBenito 17de1b
except ValueError, error:
Chris PeBenito 17de1b
	errorExit(string.join("ValueError ", error))
Chris PeBenito 17de1b
except IndexError, error:
Chris PeBenito 17de1b
	errorExit("IndexError")