Skip to contentSkip to conversation

improvements to chcon.c

PATCH Colin Walters 3 participants 6 messages Jun 28, 2003 – Jun 30, 2003 SELinux security module

lore
Share & tools
lore
#0 lore raw

Hi,

I found that I almost always just wanted to change one component of a security contenxt, not the whole thing. For example, I wanted to recursively change the user of /var/www/verbum.org to "walters", while keeping the varied types such as httpd_user_content_t, httpd_user_script_exec_t, etc.

However chcon didn't really give me an easy way to do this.

With the attached patch, I can just say:
chcon -R -h -u walters /var/www/verbum.org

This is my first attempt at programming using the SELinux API, so please review the changes carefully. This patch is against the woody patch to coreutils.

src/chcon.c +192 -54
@@ -6,6 +6,7 @@
 #include <grp.h>
 #include <getopt.h>
 #include <fs_secure.h>
+#include <get_user_sid.h>
 
 #include "system.h"
 #include "error.h"
@@ -31,8 +32,7 @@
   V_off
 };
 
-static int change_dir_context PARAMS ((const char *dir, int sid,
-				       const struct stat *statp));
+static int change_dir_context PARAMS ((const char *dir, const struct stat *statp));
 
 /* The name the program was run with. */
 char *program_name;
@@ -50,8 +50,14 @@
 /* Level of verbosity.  */
 static enum Verbosity verbosity = V_off;
 
-/* The name of the context the file is being given. */
-static const char *contextname;
+/* The SID given. */
+static int specified_sid = -1;
+
+/* The security context components the file is being given. */
+static char *specified_user;
+static char *specified_role;
+static char *specified_type;
+static char *specified_level;
 
 /* The argument to the --reference option.  Use the context SID of this file.
    This file must exist.  */
@@ -72,47 +78,144 @@
   {"quiet", no_argument, 0, 'f'},
   {"reference", required_argument, 0, CHAR_MAX + 1},
   {"sid", required_argument, 0, CHAR_MAX + 2},
+  {"user", required_argument, 0, 'u'},
+  {"role", required_argument, 0, 'r'},      
+  {"type", required_argument, 0, 't'},
+  {"level", required_argument, 0, 'l'},    
   {"verbose", no_argument, 0, 'v'},
   {"help", no_argument, &show_help, 1},
   {"version", no_argument, &show_version, 1},
   {0, 0, 0, 0}
 };
 
+/* Hacked up utility function stolen from utils/newrole.c in SELinux,
+   see that file for docs. */
+int sid_to_dynamic_context(security_id_t sid, 
+			   security_context_t *scontextp,
+			   __u32 *lenp)
+{
+  security_context_t scontext;
+  int len;                
+
+  len = 256;  /* Initial guess. */
+  scontext = xmalloc (len);
+
+  if (security_sid_to_context (sid, scontext, &len))
+    {
+      scontext = xrealloc (scontext, len);
+      
+      if (security_sid_to_context (sid, scontext, &len))
+	return -1;
+    }
+  
+  *scontextp = scontext;
+  *lenp = len;
+  return 0;
+}
+
 /* Tell the user how/if the context of FILE has been changed.
    CHANGED describes what (if anything) has happened. */
-
 static void
-describe_change (const char *file, enum Change_status changed)
+describe_change (const char *file, security_id_t newsid, enum Change_status changed)
 {
-  const char *fmt;
+  char *context = NULL;
+  size_t len;
+  if (specified_sid < 0)
+    if (sid_to_dynamic_context (newsid, &context, &len) < 0)
+      {
+	error (0, 0, "couldn't convert sid %d to context", newsid);
+      return;
+      }
+
   switch (changed)
     {
     case CH_SUCCEEDED:
-      fmt = _("context of %s changed to %s\n");
+      if (specified_sid >= 0)
+	printf (_("sid of %s changed to %d\n"), file, specified_sid);
+      else
+	printf (_("context of %s changed to %s\n"), file, context);	
       break;
     case CH_FAILED:
-      fmt = _("failed to change context of %s to %s\n");
+      if (specified_sid >= 0)
+	printf (_("failed to change sid of %s to %d\n"), file, specified_sid);
+      else
+	printf (_("failed to change context of %s to %s\n"), file, context);	
       break;
     case CH_NO_CHANGE_REQUESTED:
-      fmt = _("context of %s retained as %s\n");
+      printf (_("context of %s retained as %s\n"), file, context);
       break;
     default:
       abort ();
     }
-  printf (fmt, file, contextname);
+  free (context);
+}
+
+static int
+compute_sid_from_mask (const char *file, security_id_t file_sid,
+		       security_id_t *new_sid)
+{
+  char *file_user = NULL, *file_role = NULL, *file_type = NULL, *file_level = NULL;
+  size_t len;
+  security_context_t file_context;
+  security_context_t new_context;
+
+  if (sid_to_dynamic_context (file_sid, &file_context, &len) < 0)
+	goto lose_errno;
+  if (!security_context_to_parts (file_context,
+				  &file_user, &file_role, &file_type, &file_level))
+    goto lose_unknown;
+  
+  if (specified_user)
+    {
+      free (file_user);
+      file_user = specified_user;
+    }
+  if (specified_role)
+    {
+      free (file_role);
+      file_role = specified_role;
+    }
+  if (specified_type)
+    {
+      free (file_type);
+      file_type = specified_type;
+    }
+  if (specified_level)
+    {
+      if (file_level) free (file_level);
+      file_level = specified_level;
+    }
+  
+  if (parts_to_security_context (file_user, file_role, file_type,
+				  file_level, &new_context) != 1)
+    goto lose_unknown;
+  if (security_context_to_sid (new_context, strlen (new_context) + 1, new_sid) < 0)
+    goto lose_errno;
+  free (file_context);  
+  free (new_context);
+  return 0;
+ lose_errno:
+  if (force_silent == 0)
+    {
+      error (0, errno, "%s", file);
+    }
+ lose_unknown:
+  return 1;
 }
 
-/* Change the context of FILE to SID CONTEXT.
+/* Change the context of FILE using globally
+   specified values.
    If it is a directory and -R is given, recurse.
    Return 0 if successful, 1 if errors occurred. */
 
 static int
-change_file_context (const char *file, int sid)
+change_file_context (const char *file)
 {
-  struct stat file_stats;
   security_id_t file_sid;
+  struct stat file_stats;
+  security_id_t new_sid;
   int errors = 0;
-
+  
   if (lstat_secure (file, &file_stats, &file_sid))
     {
       if (force_silent == 0)
@@ -120,35 +223,34 @@
       return 1;
     }
 
-  if (sid != file_sid)
+  if (specified_sid < 0)
+    {
+      if (compute_sid_from_mask (file, file_sid, &new_sid) != 0)
+	{
+	  return 1;
+	}
+    }
+  else
+    new_sid = specified_sid;
+  
+  if (new_sid != file_sid)
     {
       int fail;
-
       if (change_symlinks)
-      	fail = lchsid (file, sid);
+	fail = lchsid (file, new_sid);
       else
-      	fail = chsid (file, sid);
-
+	fail = chsid (file, new_sid);
+      
       if (verbosity == V_high || (verbosity == V_changes_only && !fail))
-	describe_change (file, (fail ? CH_FAILED : CH_SUCCEEDED));
-
-      if (fail)
-	{
-	  errors = 1;
-	  if (force_silent == 0)
-	    {
-	      error (0, errno, "%s", file);
-	    }
-	}
+	describe_change (file, new_sid, (fail ? CH_FAILED : CH_SUCCEEDED));
     }
   else if (verbosity == V_high)
     {
-      describe_change (file, CH_NO_CHANGE_REQUESTED);
+      describe_change (file, new_sid, CH_NO_CHANGE_REQUESTED);
     }
-
+  
   if (recurse && S_ISDIR (file_stats.st_mode))
-    errors |= change_dir_context (file, sid, &file_stats);
-
+    errors |= change_dir_context (file, &file_stats);
   return errors;
 }
 
@@ -158,7 +260,7 @@
    Return 0 if successful, 1 if errors occurred. */
 
 static int
-change_dir_context (const char *dir, int sid, const struct stat *statp)
+change_dir_context (const char *dir, const struct stat *statp)
 {
   char *name_space, *namep;
   char *path;			/* Full path of each entry to process. */
@@ -197,7 +299,7 @@
 	  path = xrealloc (path, pathlength);
 	}
       strcpy (path + dirlength, namep);
-      errors |= change_file_context (path, sid);
+      errors |= change_file_context (path);
     }
   free (path);
   free (name_space);
@@ -214,10 +316,11 @@
     {
       printf (_("\
 Usage: %s [OPTION]... CONTEXT FILE...\n\
+  or:  %s [OPTION]... [-u USER] [-t TYPE] [-r ROLE] [-l LEVEL] FILE...\n\
   or:  %s [OPTION]... --reference=RFILE FILE...\n\
   or:  %s [OPTION]... --sid=SID FILE...\n\
 "),
-	program_name, program_name, program_name);
+	program_name, program_name, program_name, program_name);
       printf (_("\
 Change the security context of each FILE to CONTEXT.\n\
 \n\
@@ -227,6 +330,10 @@
   -f, --silent, --quiet  suppress most error messages\n\
       --reference=RFILE  use RFILE's group instead of using a CONTEXT value\n\
       --sid=SID          use context corresponding to SID for CONTEXT value\n\
+  -u, --user=USER        set user USER in the target security context\n\
+  -r, --role=ROLE        set role ROLE in the target security context\n\
+  -t, --type=TYPE        set type TYPE in the target security context\n\
+  -l, --level=LEVEL      set level LEVEL in the target security context\n\
   -R, --recursive        change files and directories recursively\n\
   -v, --verbose          output a diagnostic for every file processed\n\
       --help             display this help and exit\n\
@@ -240,7 +347,6 @@
 int
 main (int argc, char **argv)
 {
-  int sid = -1;
   int errors = 0;
   int optc;
   
@@ -251,21 +357,33 @@
 
   recurse = force_silent = 0;
   
-  while ((optc = getopt_long (argc, argv, "Rcfhv", long_options, NULL)) != -1)
+  while ((optc = getopt_long (argc, argv, "Rcfhvu:r:t:l:", long_options, NULL)) != -1)
   {
 	  switch (optc)
 	  {
 	  case 0:
 		  break;
+	  case 'u':
+		  specified_user = optarg;
+		  break;
+	  case 'r':
+		  specified_role = optarg;
+		  break;
+	  case 't':
+		  specified_type = optarg;
+		  break;
+	  case 'l':
+		  specified_level = optarg;
+		  break;
 	  case CHAR_MAX + 1:
 		  reference_file = optarg;
 		  break;
 	  case CHAR_MAX +2:
-	          sid = (int)strtol( optarg, (char **)NULL, 10);
+	          specified_sid = (int)strtol( optarg, (char **)NULL, 10);
 		  /* We use an int to represent sids so we can use -1 for *
 		   * an error condition.  All valid sids are positive.    *
 		   * Check for an invalid sid.                            */
-                  if( ( errno == ERANGE ) || ( sid <= 0 ) ) {  
+                  if( ( errno == ERANGE ) || ( specified_sid <= 0 ) ) {  
 		    error( 1, 0, _("invalid sid"));
 		  }
 	          break;
@@ -298,12 +416,26 @@
 
   if (show_help)
     usage (0);
+  
+  if ((reference_file && (specified_sid > 0
+			  || specified_user || specified_role
+			  || specified_type || specified_level))
+      || (specified_sid > 0
+	  && (specified_user || specified_role
+	      || specified_type || specified_level)))
+    {
+      error (0, 0, _("conflicting security context specifiers given"));
+      usage (1);
+    }
 
-  if (argc - optind + ( (reference_file || ( sid > 0 ) ) ? 1 : 0) <= 1)
-  {
-     error (0, 0, _("too few arguments"));
-     usage (1);
-  }
+  if (!(((reference_file || specified_sid > 0
+	  || specified_user || specified_role || specified_type || specified_level)
+	 && (argc - optind > 0))
+	|| (argc - optind > 1)))
+    {
+      error (0, 0, _("too few arguments"));
+      usage (1);
+    }
   
   if (reference_file)
     {
@@ -312,22 +444,28 @@
       if (stat_secure (reference_file, &ref_stats, &ref_sid))
 	error (1, errno, "%s", reference_file);
 
-      sid = ref_sid;
+      specified_sid = ref_sid;
     }
-  else if( sid <= 0 )  /* sid > 0 means sid already set by --sid above */
+ /* specified_sid > 0 means sid already set by --sid above */  
+  else if(specified_sid <= 0 && !(specified_user || specified_role
+				  || specified_type || specified_level))
    {
-     contextname = argv[optind++];
+     char *specified_context = argv[optind++];
 
-     if (*contextname == '\0')
+     if (*specified_context == '\0')
        error (1, 0, _("can not change to null context"));
 
-     if (security_context_to_sid (contextname, strlen (contextname) + 1, &sid))
-       error (1, errno, "%s", contextname);
+  if (!security_context_to_parts (specified_context, &specified_user, &specified_role, &specified_type,
+				  &specified_level))
+    {
+      error (1, 0, _("couldn't parse context %s"), specified_context);
+      goto exit;
+    }
    }
 
   for (; optind < argc; ++optind)
-     errors |= change_file_context (argv[optind], sid);
-
+     errors |= change_file_context (argv[optind]);
+ exit:
   if (verbosity != V_off)
     close_stdout ();
   exit (errors);
#1 lore raw
Quoted 6 lines · Colin Walters

I found that I almost always just wanted to change one component of a security contenxt, not the whole thing. For example, I wanted to recursively change the user of /var/www/verbum.org to "walters", while keeping the varied types such as httpd_user_content_t, httpd_user_script_exec_t, etc.

Quoted 8 lines

However chcon didn't really give me an easy way to do this.

With the attached patch, I can just say:
chcon -R -h -u walters /var/www/verbum.org

This is my first attempt at programming using the SELinux API, so please review the changes carefully. This patch is against the woody patch to coreutils.

Thanks for implementing this ability. However, a couple of notes:
(1) The SELinux API has been overhauled as part of preparing for mainline Linux 2.5 integration, and the new API is being back ported to the 2.4-based SELinux (although this back port won't be ready for the next public release), so the old coreutils patch will soon be obsolete. See http://www.nsa.gov/selinux/lk/coreutils-selinux.patch.gz for a snapshot of the new coreutils patch. See the PORTING file in
http://www.nsa.gov/selinux/lk/selinux-doc-1.0.tgz for discussion of the API changes.
(2) The omission of the ability to manipulate individual fields of the
security context from the utility patches was intentional. The goal is
to minimize and centralize the set of code that has awareness of the internal structure of the security context so that it can be easily altered (e.g. adding or removing security attributes) with minimal impact to the rest of the system. SELinux seeks to provide policy flexibility not only in the ability to configure the policy, but also in the ability to drop in significantly revised or even completely new security models in place of the example security server. Hence, it would be preferable to encapsulate this logic further within a library.
(3) The context_* functions defined by context.h are intended to be used to easily split up a security context, get or set its individual components, and reconstitute it into a complete string.

Signature · 8 lines
Stephen Smalley <[email protected]>
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 2 lines · Stephen Smalley

(2) The omission of the ability to manipulate individual fields of the
security context from the utility patches was intentional. The goal is

I was expecting you to say that.

However the patch that Colin has written solves some real needs. Changing the type of files is a routine administration task which should be as easy as possible. Imagine if the "chown" command required that you specify user:group every time!

Steve, if you are totally convinced that the chcon program should not have such functionality then I think that perhaps we should have a Debian-specific program similar to chcon which offers it. We can advise the users in the documentation that you don't recommend it and that future developments may break it, but I'm sure that most people will be happy to use it in the mean-time.

Also I have been thinking that the "-h" option to chcon should become the default. It seems that most times I run it I want that, and that having it change symlinks rather than their destination is usually the safest option (CF a symlink to /etc/passwd).

Also for situations such as relabelling files under /tmp and for relabelling home directories it would be good to have an option to chcon to specify a source and a destination type/identity.

So relabelling a home directory would involve relabelling user_home_netscape_rw_t to staff_home_netscape_rw_t etc. As programs such as Netscape use a very large number of files which constantly change such that the definitions in the file_contexts file are almost certainly out of date it seems that specifying source and destination components of the file is the only safe way to do it.

So for safe operation chcon would open a file, read the current context, determine how to change it, and then write the context back before closing the file. Unfortunately it doesn't seem possible to do the same for sym-links.

NB These same issues apply to chown/chgrp/chmod. So a patch for this would best be written in a generic manner to solve the issue for all three. The problems of "chown -R" etc are well known for many years...

Signature · 10 lines
http://www.coker.com.au/selinux/   My NSA Security Enhanced Linux packages
http://www.coker.com.au/bonnie++/  Bonnie++ hard drive benchmark
http://www.coker.com.au/postal/    Postal SMTP/POP benchmark
http://www.coker.com.au/~russell/  My home page


--
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.
#3 lore raw
Quoted 6 lines · Russell Coker

Steve, if you are totally convinced that the chcon program should not have such functionality then I think that perhaps we should have a Debian-specific program similar to chcon which offers it. We can advise the users in the documentation that you don't recommend it and that future developments may break it, but I'm sure that most people will be happy to use it in the mean-time.

I'm not fundamentally opposed to having such functionality in chcon (or mkdir), but I would like to have it implemented in a manner that provides as much policy flexibility as possible. It may be that there isn't much more that can be done than just making sure that we use the context_* functions from libsecure/libselinux when manipulating the fields and reconstituting the full context so that there aren't any hardcoded assumptions about the layout, although this still leaves hardcoded assumptions about specific fields existing.

Signature · 8 lines
Stephen Smalley <[email protected]>
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.
#4 lore raw
In reply to Russell Coker
Quoted 4 lines · Russell Coker

Also I have been thinking that the "-h" option to chcon should become the default. It seems that most times I run it I want that, and that having it change symlinks rather than their destination is usually the safest option (CF a symlink to /etc/passwd).

Wholeheartedly agreed.

Quoted 3 lines

NB These same issues apply to chown/chgrp/chmod. So a patch for this would best be written in a generic manner to solve the issue for all three. The problems of "chown -R" etc are well known for many years...

Honestly I didn't even realize until now that chown followed symlinks by default. I think I'm going to write a little zsh function that wraps chown/chcon and warns me if I use -R without -h.

Actually, I just did, in case anyone's interested:

function chown () {
cw-dangerous-command "/bin/chown" $@
}

function chcon () {
cw-dangerous-command "/usr/bin/chcon" $@
}

function cw-dangerous-command () {
    cmd=$1
    shift
    R_seen=
    h_seen=
    for arg in $@; do
        if test "$arg" = "-R" || test "$arg" = "--recursive"; then
	    R_seen=yes
	fi
        if test "$arg" = "-h" || test "$arg" = "--no-dereference"; then
	    h_seen=yes
	fi
    done
    if test -n "$R_seen" && test -z "$h_seen"; then
	printf "recursive \"%s\" without -h is dangerous; continue? (y/n) " "$cmd"
	read ans
	case "$ans" in
	    y*|Y*) $cmd "$@" ;;
	    *) ;;
	esac
    else
        $cmd "$@"
    fi
}

--
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.

#5 lore raw
In reply to Stephen Smalley
Quoted 3 lines · Stephen Smalley

Thanks for implementing this ability. However, a couple of notes:
(1) The SELinux API has been overhauled as part of preparing for mainline Linux 2.5 integration,

Yeah, I noticed this not long after posting the patch while I was going through the list archives.

Quoted 2 lines

and the new API is being back ported to
the 2.4-based SELinux

Ok, that should make things a lot easier than trying to maintain two separate sets of patches.

Quoted 6 lines

(although this back port won't be ready for the
next public release), so the old coreutils patch will soon be obsolete. See http://www.nsa.gov/selinux/lk/coreutils-selinux.patch.gz for a snapshot of the new coreutils patch. See the PORTING file in
http://www.nsa.gov/selinux/lk/selinux-doc-1.0.tgz for discussion of the API changes.

Sounds good then, I'll try to update the patch.

Quoted 2 lines

(2) The omission of the ability to manipulate individual fields of the security context from the utility patches was intentional. [...]

That's a good goal I think, but it shouldn't stop us from making this specific security model easier to use.

Quoted 2 lines

Hence, it
would be preferable to encapsulate this logic further within a library.

Makes sense.

Quoted 3 lines

(3) The context_* functions defined by context.h are intended to be used to easily split up a security context, get or set its individual components, and reconstitute it into a complete string.

Ok, cool, I'll take a look.

Thanks for your comments!

--
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.