Hello,

proposed patch for GNU find adding SELinux support (-context predicate
and %Z printf directive) is attached. Patch like this has been already 
proposed on the list: 
http://lists.gnu.org/archive/html/bug-findutils/2005-11/msg00079.html
and discussed again at bug-coreutils:
http://lists.gnu.org/archive/html/bug-coreutils/2008-11/msg00017.html

The SELinux support is already in Fedora findutils for a long time. Proposed 
patch is modified to use gnulib module selinux-h which adds selinux/selinux.h 
header on systems that lack it.


Kamil
From 2212fcc63960ac417f161ac6a3a29367385ad65a Mon Sep 17 00:00:00 2001
From: Kamil Dudka <kdu...@redhat.com>
Date: Wed, 28 Jan 2009 15:00:34 +0100
Subject: [PATCH] Add SELinux support.

* find/defs.h: Add SELinux definitions.
* find/tree.c: Add -context predicate to lookup.
* find/pred.c: Handle %Z printf directive.
* find/parser.c: Parse -context predicate and %Z printf directive.
* find/find.1: Mention -context predicate and %Z printf directive.
* doc/find.texi: Mention -context predicate and %Z printf directive.
* find/Makefile.am: Add SELinux libraries.
* import-gnulib.config: Require gnulib module selinux-h.
---
 doc/find.texi        |   10 ++++
 find/Makefile.am     |    2 +-
 find/defs.h          |    6 +++
 find/find.1          |    4 ++
 find/parser.c        |  119 +++++++++++++++++++++++++++++++++++++++++++++++++-
 find/pred.c          |   38 ++++++++++++++++
 find/tree.c          |    4 +-
 import-gnulib.config |    1 +
 8 files changed, 180 insertions(+), 4 deletions(-)

diff --git a/doc/find.texi b/doc/find.texi
index 56d3e32..242ff42 100644
--- a/doc/find.texi
+++ b/doc/find.texi
@@ -1242,6 +1242,14 @@ situation.
 
 @end deffn
 
+...@deffn Test -context pattern
+True if file's SELinux context matches the pattern @var{pattern}.
+The pattern uses shell glob matching.
+
+This predicate is supported only on @code{find} versions compiled with
+SELinux support and only when SELinux is enabled.
+...@end deffn
+
 @node Contents
 @section Contents
 
@@ -1826,6 +1834,8 @@ value used for BLOCKSIZE is system-dependent, but is usually 512
 bytes.  If the file size is zero, the value printed is undefined.  On
 systems which lack support for st_blocks, a file's sparseness is
 assumed to be 1.0.
+...@item %Z
+File's SELinux context, or empty string if the file has no SELinux context.
 @end table
 
 @node Location Directives
diff --git a/find/Makefile.am b/find/Makefile.am
index b001509..6fc7df3 100644
--- a/find/Makefile.am
+++ b/find/Makefile.am
@@ -26,7 +26,7 @@ endif
 
 EXTRA_DIST = defs.h $(man_MANS)
 INCLUDES = -I../gnulib/lib -I$(top_srcdir)/lib -I$(top_srcdir)/gnulib/lib -I../intl -DLOCALEDIR=\"$(localedir)\"
-LDADD = ./libfindtools.a ../lib/libfind.a ../gnulib/lib/libgnulib.a @INTLLIBS@ @LIB_CLOCK_GETTIME@ @FINDLIBS@
+LDADD = ./libfindtools.a ../lib/libfind.a ../gnulib/lib/libgnulib.a @INTLLIBS@ @LIB_CLOCK_GETTIME@ @FINDLIBS@ @LIB_SELINUX@
 man_MANS = find.1
 SUBDIRS = . testsuite
 
diff --git a/find/defs.h b/find/defs.h
index 1708d83..4c4e1b1 100644
--- a/find/defs.h
+++ b/find/defs.h
@@ -48,6 +48,7 @@ Please stop compiling the program now
 #include <stdbool.h>		/* for bool/boolean */
 #include <stdint.h>		/* for uintmax_t */
 #include <sys/stat.h> /* S_ISUID etc. */
+#include <selinux/selinux.h>
 
 
 
@@ -315,6 +316,7 @@ struct predicate
     struct samefile_file_id samefileid; /* samefile */
     mode_t type;		/* type */
     struct format_val printf_vec; /* printf fprintf fprint ls fls print0 fprint0 print */
+    security_context_t scontext; /* scontext */
   } args;
 
   /* The next predicate in the user input sequence,
@@ -459,6 +461,7 @@ PREDICATEFUNCTION pred_used;
 PREDICATEFUNCTION pred_user;
 PREDICATEFUNCTION pred_writable;
 PREDICATEFUNCTION pred_xtype;
+PREDICATEFUNCTION pred_context;
 
 
 
@@ -601,6 +604,9 @@ struct options
    */
   int regex_options;
 
+  /* function used to get file context */
+  int (*x_getfilecon) ();
+
   /* Optimisation level.  One is the default. 
    */
   unsigned short optimisation_level;
diff --git a/find/find.1 b/find/find.1
index 25953fc..52c8017 100644
--- a/find/find.1
+++ b/find/find.1
@@ -933,6 +933,8 @@ if \fIc\fR is `l'.  In other words, for symbolic links,
 checks the type of the file that 
 .B \-type
 does not check.
+.IP "\-context \fIpattern\fR"
+(SELinux only) Security context of the file matches glob \fIpattern\fR.
 
 .SS ACTIONS
 .IP "\-delete\fR"
@@ -1354,6 +1356,8 @@ File's type (like in
 U=unknown type (shouldn't happen)
 .IP %Y
 File's type (like %y), plus follow symlinks: L=loop, N=nonexistent
+.IP %Z
+(SELinux only) file's security context.
 .PP
 A `%' character followed by any other character is discarded, but the
 other character is printed (don't rely on this, as further format
diff --git a/find/parser.c b/find/parser.c
index 7f404ba..4fc43f8 100644
--- a/find/parser.c
+++ b/find/parser.c
@@ -53,6 +53,8 @@
 #include <unistd.h> 
 #include <sys/stat.h>
 
+#include <selinux/selinux.h>
+
 #if ENABLE_NLS
 # include <libintl.h>
 # define _(Text) gettext (Text)
@@ -155,6 +157,7 @@ static boolean parse_noignore_race PARAMS((const struct parser_table*, char *arg
 static boolean parse_warn          PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
 static boolean parse_xtype         PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
 static boolean parse_quit          PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
+static boolean parse_context       PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
 
 boolean parse_print             PARAMS((const struct parser_table*, char *argv[], int *arg_ptr));
 
@@ -251,6 +254,7 @@ static struct parser_table const parse_table[] =
   PARSE_TEST       ("cmin",                  cmin),	     /* GNU */
   PARSE_TEST       ("cnewer",                cnewer),	     /* GNU */
   {ARG_TEST,       "ctime",                  parse_time, pred_ctime}, /* POSIX */
+  PARSE_TEST       ("context",               context),      /* GNU */
   PARSE_POSOPT     ("daystart",              daystart),	     /* GNU */
   PARSE_ACTION     ("delete",                delete), /* GNU, Mac OS, FreeBSD */
   PARSE_OPTION     ("d",                     d), /* Mac OS X, FreeBSD, NetBSD, OpenBSD, but deprecated  in favour of -depth */
@@ -347,6 +351,85 @@ static struct parser_table const parse_table[] =
 static const char *first_nonoption_arg = NULL;
 static const struct parser_table *noop = NULL;
 
+static int
+fallback_getfilecon (const char *name, security_context_t *p, int prev_rv)
+{
+  /* Our original getfilecon () call failed.  Perhaps we can't follow a
+   * symbolic link.  If that might be the problem, lgetfilecon () the link.
+   * Otherwise, admit defeat. */
+  switch (errno)
+    {
+      case ENOENT:
+      case ENOTDIR:
+#ifdef DEBUG_STAT
+	fprintf (stderr, "fallback_getfilecon(): getfilecon(%s) failed; falling "
+			"back on lgetfilecon()\n", name);
+#endif
+	return lgetfilecon (name, p);
+
+      case EACCES:
+      case EIO:
+      case ELOOP:
+      case ENAMETOOLONG:
+#ifdef EOVERFLOW
+      case EOVERFLOW:        /* EOVERFLOW is not #defined on UNICOS. */
+#endif
+      default:
+	return prev_rv;
+    }
+}
+
+/* optionh_getfilecon () implements the getfilecon operation when the
+ * -H option is in effect.
+ *
+ * If the item to be examined is a command-line argument, we follow
+ * symbolic links.  If the getfilecon () call fails on the command-line
+ * item, we fall back on the properties of the symbolic link.
+ *
+ * If the item to be examined is not a command-line argument, we
+ * examine the link itself. */
+int
+optionh_getfilecon (const char *name, security_context_t *p)
+{
+  int rv;
+  if (0 == state.curdepth)
+    {
+      /* This file is from the command line; dereference the link (if it is
+	 a link). */
+      rv = getfilecon (name, p);
+      if (0 == rv)
+	return 0;               /* success */
+      else
+	return fallback_getfilecon (name, p, rv);
+    }
+  else
+    {
+      /* Not a file on the command line; do not dereference the link. */
+      return lgetfilecon (name, p);
+    }
+}
+
+/* optionl_getfilecon () implements the getfilecon operation when the
+ * -L option is in effect.  That option makes us examine the thing the
+ * symbolic link points to, not the symbolic link itself. */
+int
+optionl_getfilecon (const char *name, security_context_t *p)
+{
+  int rv = getfilecon (name, p);
+  if (0 == rv)
+    return 0;                  /* normal case. */
+  else
+    return fallback_getfilecon (name, p, rv);
+}
+
+/* optionp_getfilecon () implements the stat operation when the -P
+ * option is in effect (this is also the default).  That option makes
+ * us examine the symbolic link itself, not the thing it points to. */
+int
+optionp_getfilecon (const char *name, security_context_t *p)
+{
+  return lgetfilecon (name, p);
+}
 
 void 
 check_option_combinations(const struct predicate *p)
@@ -450,11 +533,13 @@ set_follow_state(enum SymlinkOption opt)
 	{
 	case SYMLINK_ALWAYS_DEREF:  /* -L */
 	  options.xstat = optionl_stat;
+	  options.x_getfilecon = optionl_getfilecon;
 	  options.no_leaf_check = true;
 	  break;
 	  
 	case SYMLINK_NEVER_DEREF:	/* -P (default) */
 	  options.xstat = optionp_stat;
+	  options.x_getfilecon = optionp_getfilecon;
 	  /* Can't turn no_leaf_check off because the user might have specified 
 	   * -noleaf anyway
 	   */
@@ -462,6 +547,7 @@ set_follow_state(enum SymlinkOption opt)
 	  
 	case SYMLINK_DEREF_ARGSONLY: /* -H */
 	  options.xstat = optionh_stat;
+	  options.x_getfilecon = optionh_getfilecon;
 	  options.no_leaf_check = true;
 	}
     }
@@ -1127,8 +1213,10 @@ tests (N can be +N or -N or N): -amin N -anewer FILE -atime N -cmin N\n\
       -nouser -nogroup -path PATTERN -perm [+-]MODE -regex PATTERN\n\
       -readable -writable -executable\n\
       -wholename PATTERN -size N[bcwkMG] -true -type [bcdpflsD] -uid N\n\
-      -used N -user NAME -xtype [bcdpfls]\n"));
+      -used N -user NAME -xtype [bcdpfls]"));
   puts (_("\
+      -context CONTEXT\n"));
+  puts (_("\n\
 actions: -delete -print0 -printf FORMAT -fprintf FILE FORMAT -print \n\
       -fprint0 FILE -fprint FILE -ls -fls FILE -prune -quit\n\
       -exec COMMAND ; -exec COMMAND {} + -ok COMMAND ;\n\
@@ -2517,6 +2605,8 @@ parse_version (const struct parser_table* entry, char **argv, int *arg_ptr)
   printf("LEAF_OPTIMISATION ");
   ++features;
 #endif
+  printf ("SELINUX ");
+  ++features;
 
   flags = 0;
   if (is_fts_enabled(&flags))
@@ -2552,6 +2642,30 @@ parse_version (const struct parser_table* entry, char **argv, int *arg_ptr)
 }
 
 static boolean
+parse_context (const struct parser_table* entry, char **argv, int *arg_ptr)
+{
+  struct predicate *our_pred;
+
+  if ((argv == NULL) || (argv[*arg_ptr] == NULL))
+    return false;
+
+  if (is_selinux_enabled () <= 0)
+    {
+      error (1, 0, _("invalid predicate -context: SELinux is not enabled."));
+      return false;
+    }
+  our_pred = insert_primary (entry);
+  our_pred->need_stat = false;
+#ifdef DEBUG
+  our_pred->p_name = find_pred_name (pred_context);
+#endif /*DEBUG*/
+  our_pred->args.scontext = argv[*arg_ptr];
+
+  (*arg_ptr)++;
+  return true;
+}
+
+static boolean
 parse_xdev (const struct parser_table* entry, char **argv, int *arg_ptr)
 {
   options.stay_on_filesystem = true;
@@ -2802,7 +2916,7 @@ insert_fprintf (struct format_val *vec,
 	  if (*scan2 == '.')
 	    for (scan2++; ISDIGIT (*scan2); scan2++)
 	      /* Do nothing. */ ;
-	  if (strchr ("abcdDfFgGhHiklmMnpPsStuUyY", *scan2))
+	  if (strchr ("abcdDfFgGhHiklmMnpPsStuUyYZ", *scan2))
 	    {
 	      segmentp = make_segment (segmentp, format, scan2 - format,
 				       KIND_FORMAT, *scan2, 0,
@@ -2929,6 +3043,7 @@ make_segment (struct segment **segment,
     case 'h':			/* leading directories part of path */
     case 'p':			/* pathname */
     case 'P':			/* pathname with ARGV element stripped */
+    case 'Z':			/* SELinux security context */
       *fmt++ = 's';
       break;
 
diff --git a/find/pred.c b/find/pred.c
index a458803..2028807 100644
--- a/find/pred.c
+++ b/find/pred.c
@@ -48,6 +48,8 @@
 #include "error.h"
 #include "verify.h"
 
+#include <selinux/selinux.h>
+
 #if ENABLE_NLS
 # include <libintl.h>
 # define _(Text) gettext (Text)
@@ -230,6 +232,7 @@ struct pred_assoc pred_table[] =
   {pred_user, "user    "},
   {pred_writable, "writable "},
   {pred_xtype, "xtype   "},
+  {pred_context, "context"},
   {0, "none    "}
 };
 #endif
@@ -1054,6 +1057,22 @@ do_fprintf(struct format_val *dest,
 			     mode_to_filetype(stat_buf->st_mode & S_IFMT));
 	  }
 	  break;
+	case 'Z':               /* SELinux security context */
+	  {
+	    security_context_t scontext;
+	    int rv = (*options.x_getfilecon) (state.rel_pathname, &scontext);
+	    if (rv < 0)
+	      {
+		error (0, errno, "getfilecon: %s",
+		    safely_quote_err_filename (0, pathname));
+	      }
+	    else
+	      {
+		checked_fprintf (dest, segment->text, scontext);
+		freecon (scontext);
+	      }
+	  }
+	  break;
 	}
       /* end of KIND_FORMAT case */
       break;
@@ -1842,6 +1861,25 @@ pred_xtype (const char *pathname, struct stat *stat_buf, struct predicate *pred_
    */
   return (pred_type (pathname, &sbuf, pred_ptr));
 }
+
+
+boolean
+pred_context (const char *pathname, struct stat *stat_buf,
+	      struct predicate *pred_ptr)
+{
+  security_context_t scontext;
+  int rv = (*options.x_getfilecon) (state.rel_pathname, &scontext);
+  if (rv < 0)
+    {
+      error (0, errno, "getfilecon: %s", safely_quote_err_filename (0, pathname));
+      return false;
+    }
+
+  rv = (fnmatch (pred_ptr->args.scontext, scontext, 0) == 0);
+  freecon (scontext);
+  return rv;
+}
+
 
 /*  1) fork to get a child; parent remembers the child pid
     2) child execs the command requested
diff --git a/find/tree.c b/find/tree.c
index 7420c60..f71d829 100644
--- a/find/tree.c
+++ b/find/tree.c
@@ -953,7 +953,8 @@ static struct pred_cost_lookup costlookup[] =
     { pred_used      ,  NeedsStatInfo        },
     { pred_user      ,  NeedsStatInfo        },
     { pred_writable  ,  NeedsAccessInfo      },
-    { pred_xtype     ,  NeedsType            } /* roughly correct unless most files are symlinks */
+    { pred_xtype     ,  NeedsType            }, /* roughly correct unless most files are symlinks */
+    { pred_context   ,  NeedsNothing         }
   };
 static int pred_table_sorted = 0;
 
@@ -1434,6 +1435,7 @@ get_new_pred (const struct parser_table *entry)
   last_pred->need_stat = true;
   last_pred->need_type = true;
   last_pred->args.str = NULL;
+  last_pred->args.scontext = NULL;
   last_pred->pred_next = NULL;
   last_pred->pred_left = NULL;
   last_pred->pred_right = NULL;
diff --git a/import-gnulib.config b/import-gnulib.config
index 71c4d66..071e4c0 100644
--- a/import-gnulib.config
+++ b/import-gnulib.config
@@ -68,6 +68,7 @@ realloc
 regex
 rpmatch
 savedir
+selinux-h
 stat-macros
 stat-time
 stpcpy
-- 
1.5.4.3

Reply via email to