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