Skip to contentSkip to conversation

policycoreutils latest diffs.

PATCH Daniel J Walsh 2 participants 3 messages Feb 22, 2006 – Mar 8, 2006 SELinux security module

lore
Share & tools
lore
#0 lore raw

audit2allow -

Added (-R/--reference) to audit2allow. This basically greps through reference policy and finds all matches for a particular access. Then outputs them. It attempts to find the best match. This makes updating reference policy a lot easier.

Changed load_policy to be looked at regardless of the granted flag.

Fixed some -M output so it is easier to cut and paste.

Fixed error handling output.

Handle "msg='avc:" as an AVC message also. This is output by Userspace tools.

Add some checks to semanage and seobject.py to turn off processing on non MLS/MCS machines. (These are untested on a Non MLS/MCS machine, since I do not have access.)

audit2allow/audit2allow +170 -10
diff --exclude-from=exclude -N -u -r nsapolicycoreutils/audit2allow/audit2allow policycoreutils-1.29.26/audit2allow/audit2allow
@@ -25,6 +25,118 @@
 #
 #  
 import commands, sys, os, pwd, string, getopt, re, selinux
+
+obj="(\{[^\}]*\}|[^ \t:]*)"
+allow_regexp="allow[ \t]+%s[ \t]*%s[ \t]*:[ \t]*%s[ \t]*%s" % (obj, obj, obj, obj)
+
+awk_script='/^[[:blank:]]*interface[[:blank:]]*\(/ {\n\
+        IFACEFILE=FILENAME\n\
+	IFACENAME = gensub("^[[:blank:]]*interface[[:blank:]]*\\\\(\`?","","g",$0);\n\
+	IFACENAME = gensub("\'?,.*$","","g",IFACENAME);\n\
+}\n\
+\n\
+/^[[:blank:]]*allow[[:blank:]]+.*;[[:blank:]]*$/ {\n\
+\n\
+  if ((length(IFACENAME) > 0) && (IFACEFILE == FILENAME)){\n\
+		ALLOW = gensub("^[[:blank:]]*","","g",$0)\n\
+		ALLOW = gensub(";[[:blank:]]*$","","g",$0)\n\
+		print FILENAME "\\t" IFACENAME "\\t" ALLOW;\n\
+	}\n\
+}\
+'
+
+class accessTrans:
+    def __init__(self):
+        self.dict={}
+	try:
+		fd=open("/usr/share/selinux/refpolicy/include/support/obj_perm_sets.spt")
+	except IOError, error:
+		raise IOError("Reference policy generation requires the policy development package.\n%s" % error)
+        records=fd.read().split("\n")
+        regexp="^define *\(`([^']*)' *, *` *\{([^}]*)}'"
+        for r in records:
+            m=re.match(regexp,r)
+            if m!=None:
+                self.dict[m.groups()[0]] = m.groups()[1].split()
+        fd.close()
+    def get(self, var):
+        l=[]
+        for v in var:
+            if v in self.dict.keys():
+                l += self.dict[v]
+            else:
+                if v not in ("{", "}"):
+                    l.append(v)
+        return l
+
+class interfaces:
+    def __init__(self):
+        self.dict={}
+        trans=accessTrans()
+	(input, output) = os.popen2("awk -f - /usr/share/selinux/refpolicy/include/*/*.if 2> /dev/null")
+	input.write(awk_script)
+	input.close()
+	records=output.read().split("\n")
+	input.close()
+        if len(records) > 0:
+            regexp="([^ \t]*)[ \t]+([^ \t]*)[ \t]+%s" % allow_regexp
+            for r in records:
+                m=re.match(regexp,r)
+                if m==None:
+                    continue
+                else:
+                    val=m.groups()
+                file=os.path.basename(val[0]).split(".")[0]
+                iface=val[1]
+                Scon=val[2].split()
+                Tcon=val[3].split()
+                Class=val[4].split()
+                Access=trans.get(val[5].split())
+                for s in Scon:
+                    for t in Tcon:
+                        for c in Class:
+                            if (s, t, c) not in self.dict.keys():
+                                self.dict[(s, t, c)]=[]
+                            self.dict[(s, t, c)].append((Access, file, iface))
+    def out(self):
+        keys=self.dict.keys()
+        keys.sort()
+        for k in keys:
+            print k
+            for i in self.dict[k]:
+                print "\t", i
+                
+    def match(self, Scon, Tcon, Class, Access):
+        keys=self.dict.keys()
+        ret=[]
+        if (Scon, Tcon, Class) in keys:
+            for i in self.dict[(Scon, Tcon, Class)]:
+                if Access in i[0]:
+                    if i[2].find(Access) >= 0:
+                        ret.insert(0, i)
+                    else:
+                        ret.append(i)
+            return ret
+        if ("$1", Tcon, Class) in keys:
+            for i in self.dict[("$1", Tcon, Class)]:
+                if Access in i[0]:
+                    if i[2].find(Access) >= 0:
+                        ret.insert(0, i)
+                    else:
+                        ret.append(i)
+            return ret
+        if (Scon, "$1", Class) in keys:
+            for i in self.dict[(Scon, "$1", Class)]:
+                if Access in i[0]:
+                    if i[2].find(Access) >= 0:
+                        ret.insert(0, i)
+                    else:
+                        ret.append(i)
+            return ret
+        else:
+            return ret
+        
+
 class serule:
 	def __init__(self, type, source, target, seclass):
 		self.type=type
@@ -32,6 +144,8 @@
 		self.target=target
 		self.seclass=seclass
 		self.avcinfo={}
+		self.iface=None
+		
 	def add(self, avc):
 		for a in avc[0]:
 			if a not in self.avcinfo.keys():
@@ -67,6 +181,33 @@
 					ret=ret + " : " + i 
 		return ret
 		
+	def gen_reference_policy(self, iface):
+		ret=""
+		Scon=self.source
+		Tcon=self.gettarget()
+		Class=self.seclass
+		Access=self.getAccess()
+		m=iface.match(Scon,Tcon,Class,Access)
+		if len(m)==0:
+			return self.out()
+		else:
+			file=m[0][1]
+			ret="\n#%s\n"% self.out()
+			ret += "optional_policy(`%s', `\n" % m[0][1]
+			first=True
+			for i in m:
+				if file != i[1]:
+					ret += "')\ngen_require(`%s', `\n" % i[1]
+					file = i[1]
+					first=True
+				if first:
+					ret += "\t%s(%s)\n" % (i[2], Scon)
+					first=False
+				else:
+					ret += "#\t%s(%s)\n" % (i[2], Scon)
+			ret += "');"
+		return ret
+		
 	def gettarget(self):
 		if self.source == self.target:
 			return "self"
@@ -81,7 +222,12 @@
 		self.types=[]
 		self.roles=[]
 		self.load(input, te_ind)
-		
+		self.gen_ref_policy = False
+
+	def gen_reference_policy(self):
+		self.gen_ref_policy = True
+		self.iface=interfaces()
+
 	def warning(self, error):
 		sys.stderr.write("%s: " % sys.argv[0])
 		sys.stderr.write("%s\n" % error)
@@ -104,7 +250,8 @@
 			while line:
 				rec=line.split()
 				for i in rec:
-					if i=="avc:" or i=="message=avc:":
+					if i=="avc:" or i=="message=avc:" or i=="msg='avc:":
+
 						found=1
 					else:
 						avc.append(i)
@@ -182,9 +329,10 @@
 		if "security_compute_sid" in avc:
 			return
 		
+		if "load_policy" in avc and self.last_reload:
+			self.seRules={}
+
 		if "granted" in avc:
-			if "load_policy" in avc and self.last_reload:
-				self.seRules={}
 			return
 		try:
 			for i in range (0, len(avc)):
@@ -292,7 +440,10 @@
 		keys=self.seRules.keys()
 		keys.sort()
 		for i in keys:
-			rec += self.seRules[i].out(verbose)+"\n"
+			if self.gen_ref_policy:
+				rec += self.seRules[i].gen_reference_policy(self.iface)+"\n"
+			else:
+				rec += self.seRules[i].out(verbose)+"\n"
 		return rec
 
 if __name__ == '__main__':
@@ -342,11 +493,12 @@
 		buildPP=0
 		input_ind=0
 		output_ind=0
+		ref_ind=False
 		te_ind=0
 
 		fc_file=""
 		gopts, cmds = getopt.getopt(sys.argv[1:],
-					    'adf:hi:lm:M:o:rtv',
+					    'adf:hi:lm:M:o:rtvR',
 					    ['all',
 					     'dmesg',
 					     'fcfile=',
@@ -356,6 +508,7 @@
 					     'module=',
 					     'output=',
 					     'requires',
+					     'reference',
 					     'tefile',
 					     'verbose'
 					     ])
@@ -397,6 +550,9 @@
 				if auditlogs:
 					usage()
 				te_ind=1
+			if o == "-R" or o == "--reference":
+				ref_ind=True
+				
 			if o == "-o" or o == "--output":
 				if module != ""  or a[0]=="-":
 					usage()
@@ -413,6 +569,10 @@
 			
 		out=seruleRecords(input, last_reload, verbose, te_ind)
 
+
+		if ref_ind:
+			out.gen_reference_policy()
+
 		if auditlogs:
 			input=os.popen("ausearch -m avc")
 			out.load(input)
@@ -423,15 +583,15 @@
 		output.flush()
 		if buildPP:
 			cmd="checkmodule %s -m -o %s.mod %s.te" % (get_mls_flag(), module, module)
-			print "Compiling policy: %s" % cmd
+			print "Compiling policy"
+			print cmd
 			rc=commands.getstatusoutput(cmd)
 			if rc[0]==0:
 				cmd="semodule_package -o %s.pp -m %s.mod" % (module, module)
-				print cmd
 				if fc_file != "":
 					cmd = "%s -f %s" % (cmd, fc_file)
 					
-				print "Building package: %s" % cmd
+				print cmd
 				rc=commands.getstatusoutput(cmd)
 				if rc[0]==0:
 					print ("\n******************** IMPORTANT ***********************\n")
@@ -446,6 +606,6 @@
 	except ValueError, error:
 		errorExit(error.args[0])
 	except IOError, error:
-		errorExit(error.args[1])
+		errorExit(error)
 	except KeyboardInterrupt, error:
 		sys.exit(0)
audit2allow/audit2allow.1 +3 -0
diff --exclude-from=exclude -N -u -r nsapolicycoreutils/audit2allow/audit2allow.1 policycoreutils-1.29.26/audit2allow/audit2allow.1
@@ -65,6 +65,9 @@
 .B "\-r" | "\-\-requires"
 Generate require output syntax for loadable modules.
 .TP
+.B "\-R" | "\-\-reference"
+Generate reference policy using installed macros
+.TP
 .B "\-t "  | "\-\-tefile"
 Indicates input file is a te (type enforcement) file.  This can be used to translate old te format to new policy format.
 .TP
semanage/semanage +9 -2
diff --exclude-from=exclude -N -u -r nsapolicycoreutils/semanage/semanage policycoreutils-1.29.26/semanage/semanage
@@ -22,6 +22,9 @@
 #  
 import os, sys, getopt
 import seobject
+import selinux
+
+is_mls_enabled=selinux.is_selinux_mls_enabled()
 
 if __name__ == '__main__':
 
@@ -57,13 +60,13 @@
 		-p (named pipe) \n\n\
 \
 	-p, --proto      Port protocol (tcp or udp)\n\
-	-L, --level      Default SELinux Level\n\
+	-L, --level      Default SELinux Level (MLS/MCS Systems only)\n\
 	-R, --roles      SELinux Roles (ex: "sysadm_r staff_r")\n\
 	-T, --trans      SELinux Level Translation\n\n\
 \
 	-s, --seuser     SELinux User Name\n\
 	-t, --type       SELinux Type for the object\n\
-	-r, --range      MLS/MCS Security Range\n\
+	-r, --range      MLS/MCS Security Range (MLS/MCS Systems only\n\
 '
 		print message
 		sys.exit(1)
@@ -167,12 +170,16 @@
 				modify = 1
 				
 			if o == "-r" or o == '--range':
+				if is_mls_enabled == 0:
+					errorExit("range not supported on Non MLS machines")
 				serange = a
 
 			if o == "-l" or o == "--list":
 				list = 1
 
 			if o == "-L" or o == '--level':
+				if is_mls_enabled == 0:
+					errorExit("range not supported on Non MLS machines")
 				selevel = a
 
 			if o == "-p" or o == '--proto':
semanage/semanage.8 +2 -2
diff --exclude-from=exclude -N -u -r nsapolicycoreutils/semanage/semanage.8 policycoreutils-1.29.26/semanage/semanage.8
@@ -46,7 +46,7 @@
 List the OBJECTS
 .TP
 .I                \-L, \-\-level
-Default SELinux Level for SELinux use. (s0)
+Default SELinux Level for SELinux use, s0 Default. (MLS/MCS Systems only)
 .TP
 .I                \-m, \-\-modify     
 Modify a OBJECT record NAME
@@ -58,7 +58,7 @@
 Protocol for the specified port (tcp|udp).
 .TP
 .I                \-r, \-\-range      
-MLS/MCS Security Range
+MLS/MCS Security Range (MLS/MCS Systems only)
 .TP
 .I                \-R, \-\-role
 SELinux Roles.  You must enclose multiple roles within quotes, separate by spaces. Or specify \-R multiple times.
semanage/seobject.py +315 -213

662 lines not on this page · raw message

#1 lore raw
Quoted 8 lines · Daniel J Walsh

audit2allow -

Added (-R/--reference) to audit2allow. This basically greps through reference policy and finds all matches for a particular access. Then outputs them. It attempts to find the best match. This makes updating reference policy a lot easier.

Changed load_policy to be looked at regardless of the granted flag.

Is this to catch reloads that occur in permissive mode? Going forward, you should be able to key off the new audit messages added by Steve Grubb for policy reloads, as they will indicate when a reload actually occurred (vs. just a permission check for them).

Quoted 3 lines

Add some checks to semanage and seobject.py to turn off processing on non MLS/MCS machines.
(These are untested on a Non MLS/MCS machine, since I do not have access.)

Doesn't quite work yet.

# semanage login -l
Login Name                SELinux User

Traceback (most recent call last):
File "/usr/sbin/semanage", line 219, in ?
OBJECT.list(heading)
File "/usr/lib/python2.4/site-packages/seobject.py", line 375, in list

    print "%-25s %-25s %-25s" % (k, ddict[k][0])

TypeError: not enough arguments for format string

That one is easy to fix:

seobject.py renamed from seobject.py.0 +1 -1
@@ -372,7 +372,7 @@ class loginRecords(semanageRecords):
 			if heading:
 				print "\n%-25s %-25s\n" % ("Login Name", "SELinux User")
 			for k in keys:
-				print "%-25s %-25s %-25s" % (k, ddict[k][0])
+				print "%-25s %-25s" % (k, ddict[k][0])
 
 class seluserRecords(semanageRecords):
 	def __init__(self):

Then login -l works, but:

# semanage login -a sds
libsemanage.validate_handler: MLS is disabled, but MLS range  was found for Unix user sds
libsemanage.validate_handler: seuser mapping [sds -> (user_u, )] is invalid
libsemanage.dbase_llist_iterate: could not iterate over records
/usr/sbin/semanage: Could not add login mapping for sds

So it looks like semanage (util) is passing libsemanage an empty string rather than a NULL?

Signature · 8 lines
Stephen Smalley
National Security Agency


--
This message was distributed to subscribers of the selinux mailing list.
If you no longer wish to subscribe, send mail to [email protected] with
the words "unsubscribe selinux" without quotes as the message.
#2 lore raw
Quoted 45 lines · Stephen Smalley
Quoted 8 lines · Daniel J Walsh

audit2allow -

Added (-R/--reference) to audit2allow. This basically greps through reference policy and finds all matches for a particular access. Then outputs them. It attempts to find the best match. This makes updating reference policy a lot easier.

Changed load_policy to be looked at regardless of the granted flag.

Is this to catch reloads that occur in permissive mode? Going forward, you should be able to key off the new audit messages added by Steve Grubb for policy reloads, as they will indicate when a reload actually occurred (vs. just a permission check for them).

Quoted 3 lines

Add some checks to semanage and seobject.py to turn off processing on non MLS/MCS machines.
(These are untested on a Non MLS/MCS machine, since I do not have access.)

Doesn't quite work yet.

# semanage login -l
Login Name                SELinux User

Traceback (most recent call last):
File "/usr/sbin/semanage", line 219, in ?
OBJECT.list(heading)
File "/usr/lib/python2.4/site-packages/seobject.py", line 375, in list

    print "%-25s %-25s %-25s" % (k, ddict[k][0])

TypeError: not enough arguments for format string

That one is easy to fix:

seobject.py renamed from seobject.py.0 +1 -1
@@ -372,7 +372,7 @@ class loginRecords(semanageRecords):
 			if heading:
 				print "\n%-25s %-25s\n" % ("Login Name", "SELinux User")
 			for k in keys:
-				print "%-25s %-25s %-25s" % (k, ddict[k][0])
+				print "%-25s %-25s" % (k, ddict[k][0])
 
 class seluserRecords(semanageRecords):
 	def __init__(self):

Then login -l works, but:

Quoted 8 lines
# semanage login -a sds
libsemanage.validate_handler: MLS is disabled, but MLS range  was found for Unix user sds
libsemanage.validate_handler: seuser mapping [sds -> (user_u, )] is invalid
libsemanage.dbase_llist_iterate: could not iterate over records
/usr/sbin/semanage: Could not add login mapping for sds

So it looks like semanage (util) is passing libsemanage an empty string rather than a NULL?

I updated to the latest version of this patch from Fedora CVS, worked around the two issues for MLS-disabled, and committed. Dropped the fixfiles diff as it seems to be broken (try fixfiles check /boot).

I think that the audit2allow -R code will need further generalization (e.g. location of policy devel files is presently hardcoded into the script) for other distributions.

I verified that semanage login -l and semanage login -a sds worked on a FC4 system (non-MLS, no python audit bindings), and it appeared to work and syslog'd the audit message (but the record appears from "python:" rather than "semanage").

Signature · 8 lines
Stephen Smalley
National Security Agency


--
This message was distributed to subscribers of the selinux mailing list.
If you no longer wish to subscribe, send mail to [email protected] with
the words "unsubscribe selinux" without quotes as the message.