Skip to contentSkip to conversation

Improve sepolicy audit log parsing.

PATCH In review Karl MacMillan 2 participants 2 messages May 14 – May 26 SELinux security module

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 Improve sepolicy audit log parsing.

This patch improves audit log parsing to include more information in the audit messages. This is restoring functionality in some ways, as it appears that the audit message formats subtly shifted over the years (though this is solely based on the test_audit.py messages - Google is not yielding any information on those old PATH messages).

This is really to make the -v (verbose) output useful for policy development by including the original audit ids (so that you can lookup the actual audit messages if needed) and include path, exe, comm, and other information in many more cases.

This also includes a fix for when you are running audit2allow without a standard tty / pty (e.g., ssh host "sudo audit2allow -al"). Before ausearch would assume that you were trying to read from stdin and no output would be produced. Now we are explicit that we want to read from the audit log.

---
 python/sepolgen/src/sepolgen/access.py    |   6 +-
 python/sepolgen/src/sepolgen/audit.py     | 344 ++++++++++++++++------
 python/sepolgen/src/sepolgen/policygen.py |  22 +-
 python/sepolgen/src/sepolgen/refparser.py |   2 +-
 python/sepolgen/tests/test_audit.py       |  15 +-
 5 files changed, 273 insertions(+), 116 deletions(-)
python/sepolgen/src/sepolgen/access.py +3 -3
index 791b9e85..06f2f495 100644
@@ -163,7 +163,6 @@ class AccessVector(util.Comparison):
             # trying to compare to foreign type
             return NotImplemented
 
-
 def avrule_to_access_vectors(avrule):
     """Convert an avrule into a list of access vectors.
 
@@ -292,8 +291,7 @@ class AccessVectorSet:
         else:
             cls[av.obj_class, av.type] = av
 
-        if audit_msg:
-            cls[av.obj_class, av.type].audit_msgs.append(audit_msg)
+        cls[av.obj_class, av.type].audit_msgs.append(audit_msg)
 
 def avs_extract_types(avs):
     types = refpolicy.IdSet()
@@ -314,6 +312,8 @@ def avs_extract_obj_perms(avs):
         s.update(av.perms)
     return perms
 
+
+
 class RoleTypeSet:
     """A non-overlapping set of role type statements.
 
python/sepolgen/src/sepolgen/audit.py +246 -98

492 lines not on this page · raw message

python/sepolgen/src/sepolgen/policygen.py +16 -6
index 7715bed5..f8ba6f85 100644
@@ -301,19 +301,29 @@ def explain_access(av, ml=None, verbosity=SHORT_EXPLANATION):
                      (str(msg.scontext), str(msg.tcontext)))
             s.append('  class="%s" perms="%s"' %
                      (msg.tclass, refpolicy.list_to_space_str(msg.accesses)))
-            s.append('  comm="%s" exe="%s" path="%s"' % (msg.comm, msg.exe, msg.path))
+            s.append('  comm="%s" exe="%s" path="%s"' % (msg.comm, msg.exe, msg.name))
             s.extend(textwrap.wrap('message="' + msg.message + '"', 80, initial_indent="  ",
                                    subsequent_indent="   "))
         explain_interfaces()
     elif verbosity:
         s.append(' src="%s" tgt="%s" class="%s", perms="%s"' %
                  (av.src_type, av.tgt_type, av.obj_class, av.perms.to_space_str()))
-        # For the short display we are only going to use the additional information
-        # from the first audit message. For the vast majority of cases this info
-        # will always be the same anyway.
+        # For the short display just summarize and get the audit ids in there so that
+        # the user can look it up later if they want.
         if len(av.audit_msgs) > 0:
-            msg = av.audit_msgs[0]
-            s.append(' comm="%s" exe="%s" path="%s"' % (msg.comm, msg.exe, msg.path))
+            msgs = set()
+            for msg in av.audit_msgs:
+                msgs.add(msg)
+                if msg.related:
+                    msgs.update(msg.related)
+
+            exes = {x.exe for x in msgs if x.exe != ""}
+            cwds = {x.cwd for x in msgs if x.cwd != ""}
+            comms = {x.comm for x in msgs if x.comm != ""}
+            names = {x.name for x in msgs if x.name != ""}
+            proctitles = {x.proctitle for x in msgs if x.proctitle != ""}
+            audit_ids = {x.audit_id for x in msgs}
+            s.append(' ids="%s" comms="%s" exes="%s" paths="%s" cwds="%s" proctitles="%s"' % (",".join(audit_ids), ",".join(comms), ",".join(exes), ",".join(names), ",".join(cwds), ",".join(proctitles)))
         explain_interfaces()
     return s
 
python/sepolgen/src/sepolgen/refparser.py +1 -1
index 01a322ca..db479e8b 100644
@@ -747,7 +747,7 @@ def p_pcidevicecon(p):
 def p_devicetreecon(p):
     'devicetreecon : DEVICETREECON NUMBER context'
     c = refpolicy.DevicetTeeCon()
-    c.path = p[2]
+    c.name = p[2]
     c.context = p[3]
 
     p[0] = c
python/sepolgen/tests/test_audit.py +7 -8
index b659bf3b..81cab473 100644
@@ -71,11 +71,10 @@ xperms_without = """type=AVC msg=audit(1516626657.910:4461): avc:  denied  { ioc
 class TestAVCMessage(unittest.TestCase):
     def test_defs(self):
         avc = sepolgen.audit.AVCMessage(audit1)
-        sc = sepolgen.refpolicy.SecurityContext()
-        self.assertEqual(avc.scontext, sc)
-        self.assertEqual(avc.tcontext, sc)
-        self.assertEqual(avc.tclass, "")
-        self.assertEqual(avc.accesses, [])
+        self.assertEqual(avc.scontext, None)
+        self.assertEqual(avc.tcontext, None)
+        self.assertEqual(avc.tclass, None)
+        self.assertEqual(avc.accesses, None)
         self.assertEqual(avc.ioctlcmd, None)
 
     def test_granted(self):
@@ -174,7 +173,7 @@ class TestPathMessage(unittest.TestCase):
         path = sepolgen.audit.PathMessage(path1)
         recs = path1.split()
         path.from_split_string(recs)
-        self.assertEqual(path.path, "/usr/lib/sa/sa1")
+        self.assertEqual(path.name, "/usr/lib/sa/sa1")
 
 # TODO - add tests for the other message types
 
@@ -195,8 +194,8 @@ class TestAuditParser(unittest.TestCase):
         a = sepolgen.audit.AuditParser()
         a.parse_string(log2)
         self.assertEqual(len(a.avc_msgs), 2)
-        self.assertEqual(a.avc_msgs[0].path, "/usr/lib/sa/sa1")
-        self.assertEqual(a.avc_msgs[1].path, "/usr/lib/sa/sa1")
+        self.assertEqual(a.avc_msgs[0].name, "/usr/lib/sa/sa1")
+        self.assertEqual(a.avc_msgs[1].name, "/usr/lib/sa/sa1")
 
     def test_parse_file(self):
         f = open("audit.txt")
Signature · 1 line
2.50.1 (Apple Git-155)
maintainer
#1 lore raw
Quoted 17 lines · Karl MacMillan

This patch improves audit log parsing to include more information in the audit messages. This is restoring functionality in some ways, as it appears that the audit message formats subtly shifted over the years (though this is solely based on the test_audit.py messages - Google is not yielding any information on those old PATH messages).

This is really to make the -v (verbose) output useful for policy development by including the original audit ids (so that you can lookup the actual audit messages if needed) and include path, exe, comm, and other information in many more cases.

This also includes a fix for when you are running audit2allow without a standard tty / pty (e.g., ssh host "sudo audit2allow -al"). Before ausearch would assume that you were trying to read from stdin and no output would be produced. Now we are explicit that we want to read from the audit log.

Quoted 7 lines
---
 python/sepolgen/src/sepolgen/access.py    |   6 +-
 python/sepolgen/src/sepolgen/audit.py     | 344 ++++++++++++++++------
 python/sepolgen/src/sepolgen/policygen.py |  22 +-
 python/sepolgen/src/sepolgen/refparser.py |   2 +-
 python/sepolgen/tests/test_audit.py       |  15 +-
 5 files changed, 273 insertions(+), 116 deletions(-)

Per Claude:

Actual bugs
1. add_av() now appends None to audit_msgs (access.py:294). The if
auditmsg: guard was removed, but audit_msg=None is still the default and is used by every caller in interfaces.py and access.py/test_access.py/test_policygen.py. policygen.explain_access() accesses msg.comm, msg.exe, msg.name on each entry producing AttributeError. Also changes test semantics in test_access.py/test_policygen.py.
2. rec == "MAC_CONFIG_CHANGE" never matches (audit.py:527); should be rec == "type=MAC_CONFIG_CHANGE" or rec =="type=1405".
3. by_audit_id grouping leaks on None. audit_id defaults to None and if msg.audit_id != "" should be if msg.audit_id:, None != "" is always true so every message that
failed header parsing gets bucketed under None.
4. refparser.py p_devicetreecon c.name = p[2] is wrong; refpolicy.DeviceTreeCon has .path not .name. The rule is already dead; refpolicy.DevicetTeeCon is a typo for
DeviceTreeCon.
5. assign_field_from_rec: value[0] == '"' on empty value. Guard with if value and value[0] =='"'.

Correct but worth noting
6. PolicyLoadMessage gained 12 fields but no from_split_string override to populate them - they stay "" forever.
7. Dead writes: found_src/found_tgt (audit.py:317,320) are assigned but never read.
8. Proctitle.decode_proctitle assumes hex. audit will sometimes emit proctitle="literal string" when it doesn't contain whitespace or control characters; unhexlify raises binascii.Error promotes to ValueError, caught and replaces entire line with InvalidMessage.
9. API surface change: AVCMessage.path no longer exists (folded into .name). policygen.py was updated but external consumers (setroubleshoot, sepolicy gui, etc) that read avc.path will break.
10. __post_process overwrites a.name/a.comm unconditionally. Probably fine in practice but "last comm wins" behavior.

Cosmetic
Gratuitous whitespace churn in access.py (163, 312) and audit.py (689). __rep__ returning a multi-line pretty-print is unconventional; makes lists of messages unreadable in a debugger.