Skip to contentSkip to conversation

run_init and interactive scripts

PATCH Manoj Srivastava 3 participants 11 messages Jan 20, 2005 – Jan 21, 2005 SELinux security module

lore
Share & tools
lore
#0 lore raw

Hi,

run_init, as distributed, can run init scripts in the initrc
domain. However, if the forked process is an interactive one, it inherits the controlling tty, which is would mean that the controlling tty is the controlling tty of a sysadm_t process -- and this can be a problem, since a process that has a pty can insert characters and potentially take over a sysadm_t session. (If the process invokes a daemon that does not close file handles, then if exploited can be used to take over administrative sessions). (This also inhibits denials due to an initrc_exec_t process trying to write to a sysadm_devpts_t object).

The following patch makes run_init execute
/usr/sbin/open_init_pty (after using setexeccon to set the context appropriately). So, run_init does not execvp the command directly, Instead, it transitions the process into the initrc_t domain, execs open_init_tty. open_init_pty then spawns a new process, that gets a pty with context initrc_devpts_t (just execvp or using a exec(1) does not open a new pty; the process inherits the original controlling tty).

open_init_pty then sets up the psuedo terminal properly based
on the physical terminal attributes of the initial pty (temporarily setting the user's pty to RAW mode, taking care to reset it on exit), forks a child process that binds to the pseudo terminal. It then sits around and connects the physical terminal it was invoked upon with the pseudo terminal, passing keyboard input into to the child process, and passing the output of the child process to the physical terminal (using select).

I have included a manual page, and the corresponding changes
to the build system to build, install, and relabel the installed executables appropriately.

This has been tested with dselect on a SELinux UML.

manoj

* modified files

run_init/Makefile +8 -1
@@ -8,17 +8,23 @@
 
 CFLAGS = -Wall
 override CFLAGS += -DUSE_NLS -DUSE_PAM -DLOCALEDIR="\"$(LOCALEDIR)\"" -DPACKAGE="\"policycoreutils\""
-LDLIBS += -lselinux -ldl -lpam -lpam_misc
+LDLIBS += -lselinux -ldl -lpam -lpam_misc -lutil
 
 TARGETS=$(patsubst %.c,%,$(wildcard *.c))
 
 all: $(TARGETS)
 
+open_init_pty: open_init_pty.c
+	$(LINK.c) $^ -lutil -o $@
+
+
 install: all
 	test -d $(SBINDIR)      || install -m 755 -d $(SBINDIR)
 	test -d $(MANDIR)/man1 || install -m 755 -d $(MANDIR)/man1
 	install -m 555 run_init $(SBINDIR)
+	install -m 555 open_init_pty $(SBINDIR)
 	install -m 644 run_init.8 $(MANDIR)/man8/
+	install -m 644 open_init_pty.8 $(MANDIR)/man8/
 	install -m 644 run_init.pamd $(ETCDIR)/pam.d/run_init
 
 clean:
@@ -26,3 +32,4 @@
 
 relabel: install
 	setfilecon system_u:object_r:run_init_exec_t $(SBINDIR)/run_init
+	setfilecon system_u:object_r:initrc_exec_t $(SBINDIR)/open_init_pty
run_init/run_init.c +9 -1
@@ -376,7 +376,15 @@
        fprintf(stderr, _("Could not set exec context to %s.\n"), new_context);
        exit(-1);
   }
-  if ( execvp(argv[1], argv + 1) ) {
+  /*
+   * Do not execvp the command directly from run_init; since it would run
+   * under with a pty under sysadm_devpts_t. Instead, we call open_init_tty,
+   * which transitions us into initrc_t, which then spawns a new
+   * process, that gets a pty with context initrc_devpts_t. Just
+   * execvp or using a exec(1) recycles pty's, and does not open a new
+   * one. 
+   */
+  if ( execvp("/usr/sbin/open_init_pty", argv) ) {
     perror("execvp");
     exit(-1);
   }
open_init_pty.8 new file +48 -0

48 lines not on this page · raw message

open_init_pty.c new file +361 -0

361 lines not on this page · raw message

Signature · 6 lines
-- 
When we understand knowledge-based systems, it will be as before --
except our fingertips will have been singed.  -- Epigrams in
Programming, ACM SIGPLAN Sept. 1982
Manoj Srivastava   <[email protected]>    <[email protected]> 
1024D/BF24424C print 4966 F272 D093 B493 410B  924B 21BA DABB BF24 424C
#1 lore raw
Quoted 10 lines · Manoj Srivastava

run_init, as distributed, can run init scripts in the initrc
domain. However, if the forked process is an interactive one, it inherits the controlling tty, which is would mean that the controlling tty is the controlling tty of a sysadm_t process -- and this can be a problem, since a process that has a pty can insert characters and potentially take over a sysadm_t session. (If the process invokes a daemon that does not close file handles, then if exploited can be used to take over administrative sessions). (This also inhibits denials due to an initrc_exec_t process trying to write to a sysadm_devpts_t object).

Just to clarify, the current SELinux security module rechecks access to the controlling tty and to any open file descriptors upon a context-changing exec, and will automatically revoke access if denied by policy. Hence, without any change, it should already be the case that unless the daemon is explicitly granted permissions to the pty, all access should be revoked upon the transition into the daemon's domain. If you have a daemon running in initrc_t, you have other problems. I'm not opposed to this patch (we did merge a version of open_init_pty from Russell a long time ago, but reverted it due to some problems with its implementation/dependency on expect), but wanted to clarify this point...

Quoted 2 lines

______________________________________________________________________

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
In reply to Manoj Srivastava
Quoted 8 lines · Manoj Srivastava

open_init_pty then sets up the psuedo terminal properly based
on the physical terminal attributes of the initial pty (temporarily setting the user's pty to RAW mode, taking care to reset it on exit), forks a child process that binds to the pseudo terminal. It then sits around and connects the physical terminal it was invoked upon with the pseudo terminal, passing keyboard input into to the child process, and passing the output of the child process to the physical terminal (using select).

Prior to your patch:

# /usr/sbin/run_init /etc/init.d/sshd restart
Authenticating root.
Password:
Stopping sshd:                                             [  OK  ]
Starting sshd:                                             [  OK  ]

After your patch:

# /usr/sbin/run_init /etc/init.d/sshd restart
Authenticating root.
Password:
Stopping sshd:                                             [  OK  ]
Starting sshd:#

Need to flush stderr in open_init_pty?

BTW, Red Hat / Fedora is not presently using run_init at all, although I still think it is a good idea if you can get users to use it. The policy allows direct transitions for init script and daemon execution unless you disable the direct_sysadm_daemon tunable. It would help if we could enforce its usage in policy when that tunable is disabled, i.e. prevent direct execution of sshd entirely by sysadm_t so that it doesn't get left in sysadm_t by accident.

________________________________________________________________________

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.
#3 lore raw
Quoted 1 line · Stephen Smalley

Need to flush stderr in open_init_pty?

Done. I have now inserted flush statements along all the exit
points in the function. Tested with /etc/init.d/mimedefand, /etc/init.d/bind9, emacs, and aptitude.

Quoted 2 lines
Quoted 1 line

______________________________________________________________________

-- Stephen Smalley <[email protected]> National Security Agency

Quoted 9 lines · Stephen Smalley
Quoted 2 lines · Manoj Srivastava

Here is the man page for the other script without a man page in policycoreutils.

Thanks. Two suggested changes:
- Update both the script comment and the man page to use 500 rather than 100 for the default STARTING_UID, as that is what the code uses presently (in the absence of a UID_MIN definition in /etc/login.defs),

Done.

Quoted 4 lines

- Start with an abstract description of the purpose, e.g. this script is to generate file context configuration entries for user home directories based on their default roles and is run when building the policy.

Done.

Quoted 1 line

________________________________________________________________________

What follows is an incremental patch relative to the changes
already accepted.

manoj

run_init/open_init_pty.c +38 -13
@@ -4,9 +4,9 @@
  * Created On       : Fri Jan 14 10:48:28 2005
  * Created On Node  : glaurung.internal.golden-gryphon.com
  * Last Modified By : Manoj Srivastava
- * Last Modified On : Fri Jan 14 19:06:19 2005
+ * Last Modified On : Thu Jan 20 23:50:04 2005
  * Last Machine Used: glaurung.internal.golden-gryphon.com
- * Update Count     : 85
+ * Update Count     : 89
  * Status           : Unknown, Use with caution!
  * HISTORY          : 
  * Description      : 
@@ -168,13 +168,13 @@
      /* get terminal parameters associated with stdout */
      if(tcgetattr(fileno(stdout), &tty_attr) < 0)
       {
-        perror("Error determining terminal characteristics");
+        perror("tcgetattr:");
         exit(EX_OSERR);
       } /* end of if(tcsetattr(&tty_attr)) */
 
      /* get window size */
      if( ioctl(fileno(stdout), TIOCGWINSZ, &window_size) < 0 ) {
-       perror("Error determining window size: ioctl stdout TIOCGWINSZ");
+       perror("ioctl stdout:");
        exit(1);
      }
 
@@ -187,7 +187,9 @@
 
   if(child_pid < 0)
    {
-     perror("Error forking process");
+     perror("Fork:");
+     fflush(stdout);
+     fflush(stderr);
      exit(EX_OSERR);
    } /* end of if(child_pid < 0) */
   if(child_pid == 0)
@@ -197,6 +199,8 @@
      if(tcgetattr(fileno(stdin), &s_tty_attr))
       {
         perror("Child:");
+        fflush(stdout);
+        fflush(stderr);
         exit(EXIT_FAILURE);
       }
      /* Turn off echo */
@@ -210,14 +214,16 @@
       }
 
      if ( execvp(argv[1], argv + 1) ) {
-       perror("Error executing child");
+       perror("Exec:");
+       fflush(stdout);
+       fflush(stderr);
        exit(EXIT_FAILURE);
      }
    } /* end of if(child_pid == 0) */
 
   /* 
    * OK. Prepare to handle IO from the child. We need to transfer
-   * everything from the shilds stdout to ours.
+   * everything from the child's stdout to ours.
    */
 
   FD_ZERO(&readfds);
@@ -230,12 +236,16 @@
   retval=fcntl(pty_master,F_GETFL);
   if(retval<0) {
     perror("fcntl_get");
+    fflush(stdout);
+    fflush(stderr);
     exit(EX_IOERR);
   }
 
   /* Set the connection to be non-blocking */
   if(fcntl(pty_master,F_SETFL, retval | O_NONBLOCK) < 0) {
     perror("fcnt_setFlag_nonblock:");
+    fflush(stdout);
+    fflush(stderr);
     exit(1);
   }
 
@@ -247,10 +257,14 @@
      if(tty_raw(fileno(stdin)) < 0)
       {
         perror("Error: settingraw mode:");
+        fflush(stdout);
+        fflush(stderr);
       } /* end of if(tty_raw(fileno(stdin)) < 0) */
      if(atexit(tty_atexit) < 0)
       {
         perror("Atexit setup:");
+        fflush(stdout);
+        fflush(stderr);
       } /* end of if(atexit(tty_atexit) < 0) */
    }
 
@@ -280,6 +294,8 @@
        if( retval < 0 ) {
          if(errno != EAGAIN) {
            perror("sigtimedwait");
+           fflush(stdout);
+           fflush(stderr);
            exit(EX_IOERR);
          }
          else
@@ -293,6 +309,8 @@
                &interval) < 0)
      {
        perror("Select:");
+       fflush(stdout);
+       fflush(stderr);
        exit (EX_IOERR);
      }
 
@@ -302,9 +320,10 @@
        if(retval < 0)
         {
           if(errno != EINTR && errno != EAGAIN) 
-           {
-             perror("Done?");
-             exit (EX_IOERR);
+           {                    /* Nothing left to read?  */
+             fflush(stdout);
+             fflush(stderr);
+             exit (EXIT_SUCCESS);
            } /* end of else */
         } /* end of if(retval < 0) */
        else
@@ -313,6 +332,8 @@
            {
              if(++err_count > 5)
               {                 /* child closed connection */
+                fflush(stdout);
+                fflush(stderr);
                 exit (EXIT_SUCCESS);
               }
            } /* end of if(retval == 0) */
@@ -331,9 +352,10 @@
           if(retval < 0)
            {
              if(errno != EINTR && errno != EAGAIN)
-              {
-                perror("Done?");
-                exit (EX_IOERR);
+              {                 /* Nothing left to read?  */
+                fflush(stdout);
+                fflush(stderr);
+                exit (EXIT_SUCCESS);
               } /* end of else */
            } /* end of if(retval < 0) */
           else
@@ -342,6 +364,8 @@
               {
                 if(++err_count > 5)
                  {              /* lost controlling tty */
+                   fflush(stdout);
+                   fflush(stderr);
                    exit (EXIT_SUCCESS);
                  }
               } /* end of if(retval == 0) */
@@ -356,6 +380,7 @@
   } /* Loop */
 
   fflush(stdout);
+  fflush(stderr);
 
   exit(EXIT_SUCCESS);
 } /* end of main() */
scripts/genhomedircon +6 -3
@@ -3,8 +3,11 @@
 # see file 'COPYING' for use and warranty information
 
 #
-# genhomedircon - Replace HOME_ROOT, HOME_DIR, and ROLE macros in .fc files
-#  with generic and user-specific values.
+# genhomedircon - this script is used to generate file context
+# configuration entries for user home directories based on their
+# default roles and is run when building the policy. Specifically, we
+# replace HOME_ROOT, HOME_DIR, and ROLE macros in .fc files with
+# generic and user-specific values.
 #
 # Based off original script by Dan Walsh, <[email protected]>
 #
@@ -17,7 +20,7 @@
 #  the user's home dir will be found in one of the HOME_ROOTs.
 #
 # "Real" users (as opposed to system users) are those whose UID is greater than
-#  or equal STARTING_UID (usually 100) and whose login is not a member of
+#  or equal STARTING_UID (usually 500) and whose login is not a member of
 #  EXCLUDE_LOGINS.  Users who are explicitly defined in FILECONTEXTDIR/users
 #  are always "real" (including root, in the default configuration).
 #
scripts/genhomedircon.8 +5 -3
@@ -24,7 +24,7 @@
 .\"
 .TH GENHOMEDIRCON "8" "January 2005" "Security Enhanced Linux" NSA
 .SH NAME
-genhomedircon \- expand HOME_ROOT, HOME_DIR, and ROLE macros in .fc files
+genhomedircon \- generate file context configuration entries for user home directories 
 .SH SYNOPSIS
 .B genhomedircon
 .RI POLICYSOURCEDIR FILE_CONTEXTS 
@@ -34,7 +34,9 @@
 Print a short usage message
 .SH DESCRIPTION
 .PP
-This utility replaces the
+This utility is used to generate file context configuration entries
+for user home directories based on their default roles and is run when
+building the policy.  Specifically, it replaces the
 .B HOME_ROOT, HOME_DIR,
 and 
 .B ROLE
@@ -55,7 +57,7 @@
 only considers real users. "Real" users (as opposed
 to system users) are those whose UID is greater than or equal 
 .I STARTING_UID
-(usually 100) and whose login shell is not "/sbin/nologin", or
+(default 500) and whose login shell is not "/sbin/nologin", or
 "/bin/false". Users who are explicitly defined in 
 .I <<FILECONTEXTDIR>>/users
 are always "real" (including root, in the default configuration).
Signature · 4 lines
-- 
So little time, so little to do. Oscar Levant
Manoj Srivastava   <[email protected]>    <[email protected]> 
1024D/BF24424C print 4966 F272 D093 B493 410B  924B 21BA DABB BF24 424C
#4 lore raw
Quoted 2 lines · Manoj Srivastava

What follows is an incremental patch relative to the changes
already accepted.

BTW, this was merged into sourceforge CVS as of policycoreutils 1.21.2, including the audit2allow man page, revised genhomedircon script and man page, and the open_init_pty helper for run_init (with stderr flushing, but not the latest patch that introduced erratic output).

Quoted 2 lines

______________________________________________________________________

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.
#5 lore raw
In reply to Manoj Srivastava
Quoted 9 lines · Manoj Srivastava

The following patch makes run_init execute
/usr/sbin/open_init_pty (after using setexeccon to set the context appropriately). So, run_init does not execvp the command directly, Instead, it transitions the process into the initrc_t domain, execs open_init_tty. open_init_pty then spawns a new process, that gets a pty with context initrc_devpts_t (just execvp or using a exec(1) does not open a new pty; the process inherits the original controlling tty).

Quoted 8 lines

open_init_pty then sets up the psuedo terminal properly based
on the physical terminal attributes of the initial pty (temporarily setting the user's pty to RAW mode, taking care to reset it on exit), forks a child process that binds to the pseudo terminal. It then sits around and connects the physical terminal it was invoked upon with the pseudo terminal, passing keyboard input into to the child process, and passing the output of the child process to the physical terminal (using select).

It seems like this functionality (or something similar) could be useful in other situations, e.g. for su(1) and sudo(8).

Quoted 2 lines

______________________________________________________________________

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.
#6 lore raw

Hi,

[Sent to Stephen directly in error; Stephen, I apologize for the
duplicate]

Quoted 2 lines · Stephen Smalley

It seems like this functionality (or something similar) could be useful in other situations, e.g. for su(1) and sudo(8).

Hmm. I had been mostly testing open_init_pty with full screen
curses based applications like aptitude and dselect, and not things like restarting sshd. Looking at sshd restarts, I noticed ladder artifacts like:
======================================================================
Shutting down mimedefang: [ OK ]
Shutting down mimedefang-multiplexor:[ OK ]
....
======================================================================

This is because I was putting the users terminal into raw
mode, and that also turns off output processing. So, in the following patch I introduce a function called tty_semi_raw, which is just like raw mode, except we retain output processing. This is still fine for things like aptitude and dselect, and makes the non-curses applicationss look OK (like so)
======================================================================
Shutting down mimedefang: [ OK ]
Shutting down mimedefang-multiplexor: [ OK ]
....
======================================================================

This is an incremental patch in addition to the one I sent 12
hours or so ago, which had the fflush stderr fixes. Please apply.

manoj

run_init/open_init_pty.c +43 -1
@@ -113,6 +113,48 @@
   return 0;
 }
 
+static int
+tty_semi_raw(int fd)
+{
+  struct termios buf;
+
+  if(tty_state == RESET)
+   {
+     if(tcgetattr(fd, &saved_termios) < 0)
+      {
+        return -1;
+      }
+   }
+
+  buf             = saved_termios;
+  /*
+   * echo off, canonical mode off, extended input processing off,
+   * signal chars off
+   */
+  buf.c_lflag    &= ~(ECHO | ICANON | IEXTEN | ISIG);
+  /*
+   * no SIGINT on break, CR-to-NL off, input parity check off, do not
+   * strip 8th bit on input,output flow control off
+   */
+  buf.c_iflag    &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
+  /* Clear size bits, parity checking off */
+  buf.c_cflag    &= ~(CSIZE | PARENB);
+  /* set 8 bits/char */
+  buf.c_cflag    |= CS8;
+  /* Output processing off 
+  buf.c_oflag    &= ~(OPOST); */
+
+  buf.c_cc[VMIN]  = 1;             /* one byte at a time, no timer */
+  buf.c_cc[VTIME] = 0;
+  if(tcsetattr(fd, TCSANOW, &buf) < 0)
+   {
+     return -1;
+   } /* end of if(tcsetattr(fileno(stdin), TCSANOW, &buf) < 0) */
+  tty_state = RAW;
+  saved_fd = fd;
+  return 0;
+}
+
 void
 tty_atexit(void)
 {
@@ -254,7 +296,7 @@
   FD_SET(fileno(stdin), &readfds);
   if(isatty(fileno(stdin)))
    {
-     if(tty_raw(fileno(stdin)) < 0)
+     if(tty_semi_raw(fileno(stdin)) < 0)
       {
         perror("Error: settingraw mode:");
         fflush(stdout);
Signature · 5 lines
-- 
Paradise is exactly like where you are right now ... only much, much
better. Laurie Anderson
Manoj Srivastava   <[email protected]>    <[email protected]> 
1024D/BF24424C print 4966 F272 D093 B493 410B  924B 21BA DABB BF24 424C
#7 lore raw
Quoted 12 lines · Manoj Srivastava

This is because I was putting the users terminal into raw
mode, and that also turns off output processing. So, in the following patch I introduce a function called tty_semi_raw, which is just like raw mode, except we retain output processing. This is still fine for things like aptitude and dselect, and makes the non-curses applicationss look OK (like so)
======================================================================
Shutting down mimedefang: [ OK ]
Shutting down mimedefang-multiplexor: [ OK ]
....
======================================================================

Quoted 2 lines

This is an incremental patch in addition to the one I sent 12
hours or so ago, which had the fflush stderr fixes. Please apply.

Hmmm...I now get erratic behavior, sometimes only getting the first line of output (Stopping sshd: [ OK ]), sometimes getting the first line and the prefix of the second line, but still not the complete output. And this behavior occurs under permissive mode as well, so it isn't related to any permissions. Reverting this latest patch, I at least get consistent output, only losing the final OK status.

Quoted 2 lines

______________________________________________________________________

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.
#8 lore raw

BTW, this also requires removing the ifdef(`distro_debian') conditional in initrc.fc for open_init_pty to ensure proper labeling by setfiles/restorecon/rpm.

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.
#9 lore raw
In reply to Stephen Smalley
Quoted 15 lines · Stephen Smalley
Quoted 11 lines · Manoj Srivastava

This is because I was putting the users terminal into raw mode, and that also turns off output processing. So, in the following patch I introduce a function called tty_semi_raw, which is just like raw mode, except we retain output processing. This is still fine for things like aptitude and dselect, and makes the non-curses applicationss look OK (like so)
======================================================================
Shutting down mimedefang: [ OK ] Shutting down
mimedefang-multiplexor: [ OK ] ....
======================================================================

Quoted 2 lines

This is an incremental patch in addition to the one I sent 12 hours or so ago, which had the fflush stderr fixes. Please apply.

Quoted 6 lines

Hmmm...I now get erratic behavior, sometimes only getting the first line of output (Stopping sshd: [ OK ]), sometimes getting the first line and the prefix of the second line, but still not the complete output. And this behavior occurs under permissive mode as well, so it isn't related to any permissions. Reverting this latest patch, I at least get consistent output, only losing the final OK status.

That is strange, seeing that the only changes in that patch
were _adding_ fflush statements.

This is on a non-Se-Linux machine, I did this 5 times in a row
======================================================================
__> open_init_pty /etc/init.d/mimedefang restart

Shutting down mimedefang:                                   [  OK  ]
Shutting down mimedefang-multiplexor:                       [  OK  ]
Waiting for daemons to exit.......
Starting mimedefang-multiplexor:                            [  OK  ]
Starting mimedefang:                                        [  OK  ]
__> open_init_pty /etc/init.d/mimedefang restart
Shutting down mimedefang:                                   [  OK  ]
Shutting down mimedefang-multiplexor:                       [  OK  ]
Waiting for daemons to exit.....
Starting mimedefang-multiplexor:                            [  OK  ]
Starting mimedefang:                                        [  OK  ]

======================================================================

I am attaching the full open_init_pty.c file below; I've
tested this as extensively as I can on a number of Debian machines.

manoj

/* -*- Mode: C -*-
* open_init_pty.c ---

 * Author           : Manoj Srivastava ( [email protected] ) 
 * Created On       : Fri Jan 14 10:48:28 2005
 * Created On Node  : glaurung.internal.golden-gryphon.com
 * Last Modified By : Manoj Srivastava
 * Last Modified On : Thu Jan 20 23:50:04 2005
 * Last Machine Used: glaurung.internal.golden-gryphon.com
 * Update Count     : 89
 * Status           : Unknown, Use with caution!
 * HISTORY          : 
 * Description      : 

*
* Distributed under the terms of the GNU General Public License v2 *
* open_init_pty
*
* SYNOPSIS:
*
* This program allows a systems administrator to execute daemons
* which need to work in the initrc domain, and which need to have
* pty's as system_u:system_r:initrc_t
*
* USAGE:
*
* * arch-tag: a5583d39-72b9-4cdf-ba1b-5678ea4cbe20
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>

#include <sysexits.h>

#include <pty.h> /* for openpty and forkpty */
#include <utmp.h> /* for login_tty */
#include <termios.h>
#include <fcntl.h>

#include <sys/select.h>

static struct termios saved_termios;
static int saved_fd = -1;
static enum { RESET, RAW, CBREAK } tty_state = RESET;

static int
tty_cbreak(int fd)
{
struct termios buf;

  if(tty_state == RESET)
   {
     if(tcgetattr(fd, &saved_termios) < 0)
      {
        return -1;
      }
   }

buf = saved_termios;
buf.c_lflag &= ~(ECHO | ICANON); /* echo off, canonical mode off */
buf.c_cc[VMIN] = 1; /* one byte at a time, no timer */
buf.c_cc[VTIME] = 0;
if(tcsetattr(fd, TCSANOW, &buf) < 0)

   {
     return -1;

} /* end of if(tcsetattr(fileno(stdin), TCSANOW, &buf) < 0) */
tty_state = CBREAK;
saved_fd = fd;
return 0;
}

static int
tty_raw(int fd)
{
struct termios buf;

  if(tty_state == RESET)
   {
     if(tcgetattr(fd, &saved_termios) < 0)
      {
        return -1;
      }
   }

  buf             = saved_termios;
  /*
   * echo off, canonical mode off, extended input processing off,
   * signal chars off
   */
  buf.c_lflag    &= ~(ECHO | ICANON | IEXTEN | ISIG);
  /*
   * no SIGINT on break, CR-to-NL off, input parity check off, do not
   * strip 8th bit on input,output flow control off
   */
  buf.c_iflag    &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
  /* Clear size bits, parity checking off */
  buf.c_cflag    &= ~(CSIZE | PARENB);
  /* set 8 bits/char */
  buf.c_cflag    |= CS8;
  /* Output processing off */
  buf.c_oflag    &= ~(OPOST);

buf.c_cc[VMIN] = 1; /* one byte at a time, no timer */
buf.c_cc[VTIME] = 0;
if(tcsetattr(fd, TCSANOW, &buf) < 0)

   {
     return -1;

} /* end of if(tcsetattr(fileno(stdin), TCSANOW, &buf) < 0) */
tty_state = RAW;
saved_fd = fd;
return 0;
}

static int
tty_semi_raw(int fd)
{
struct termios buf;

  if(tty_state == RESET)
   {
     if(tcgetattr(fd, &saved_termios) < 0)
      {
        return -1;
      }
   }

buf = saved_termios;
/*
* echo off, canonical mode off, extended input processing off,
* signal chars off
*/
buf.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
/*
* no SIGINT on break, CR-to-NL off, input parity check off, do not
* strip 8th bit on input,output flow control off
*/
buf.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
/* Clear size bits, parity checking off */
buf.c_cflag &= ~(CSIZE | PARENB);
/* set 8 bits/char */
buf.c_cflag |= CS8;
/* Output processing off
buf.c_oflag &= ~(OPOST); */

buf.c_cc[VMIN] = 1; /* one byte at a time, no timer */
buf.c_cc[VTIME] = 0;
if(tcsetattr(fd, TCSANOW, &buf) < 0)

   {
     return -1;

} /* end of if(tcsetattr(fileno(stdin), TCSANOW, &buf) < 0) */
tty_state = RAW;
saved_fd = fd;
return 0;
}

void
tty_atexit(void)
{
if(tty_state != CBREAK && tty_state != RAW)

   {
     return;

}

if(tcsetattr(saved_fd, TCSANOW, &saved_termios) < 0)

   {
     return;

} /* end of if(tcsetattr(fileno(stdin), TCSANOW, &buf) < 0) */
tty_state = RESET;
return;
}

int
main(int argc, char *argv[])
{
pid_t child_pid;
struct termios tty_attr;
struct winsize window_size;
int pty_master;
int retval = 0;

/* for select */
fd_set readfds;
fd_set writefds;
fd_set exceptfds;

  int err_count = 0;

  /* for sigtimedwait() */
  struct timespec timeout;
  char buf[16384];

sigset_t signal_set;
siginfo_t signalinfo;

/* set up SIGCHLD */
sigemptyset(&signal_set); /* no signals */
sigaddset(&signal_set, SIGCHLD); /* Add sig child */ sigprocmask(SIG_BLOCK, &signal_set, NULL); /* Block the signal */

  /* Set both to 0, so sigtimed wait just does a poll */
  timeout.tv_sec=0;
  timeout.tv_nsec=0;

  if(isatty(fileno(stdin)))
   {
     /* get terminal parameters associated with stdout */
     if(tcgetattr(fileno(stdout), &tty_attr) < 0)
      {
        perror("tcgetattr:");
        exit(EX_OSERR);
      } /* end of if(tcsetattr(&tty_attr)) */
     /* get window size */
     if( ioctl(fileno(stdout), TIOCGWINSZ, &window_size) < 0 ) {
       perror("ioctl stdout:");
       exit(1);
     }

     child_pid = forkpty(&pty_master, NULL, &tty_attr, &window_size);
   } /* end of if(isatty(fileno(stdin))) */
  else
   {                            /* not interactive */
     child_pid = forkpty(&pty_master, NULL, NULL, NULL);

}

  if(child_pid < 0)
   {
     perror("Fork:");
     fflush(stdout);
     fflush(stderr);
     exit(EX_OSERR);
   } /* end of if(child_pid < 0) */
  if(child_pid == 0)
   {
     /* in the child */
     struct termios s_tty_attr;
     if(tcgetattr(fileno(stdin), &s_tty_attr))
      {
        perror("Child:");
        fflush(stdout);
        fflush(stderr);
        exit(EXIT_FAILURE);
      }
     /* Turn off echo */
     s_tty_attr.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
     /* Also turn of NL to CR?LF on output */
     s_tty_attr.c_oflag &= ~(ONLCR);
     if(tcsetattr(fileno(stdin), TCSANOW, &s_tty_attr))
      {
        perror("Child:");
        exit(EXIT_FAILURE);
      }
     if ( execvp(argv[1], argv + 1) ) {
       perror("Exec:");
       fflush(stdout);
       fflush(stderr);
       exit(EXIT_FAILURE);
     }

} /* end of if(child_pid == 0) */

/*
* OK. Prepare to handle IO from the child. We need to transfer
* everything from the child's stdout to ours.
*/

  FD_ZERO(&readfds);
  FD_ZERO(&writefds);
  FD_ZERO(&exceptfds);

  /*
   * Read current file descriptor flags, preparing to do non blocking reads
   */
  retval=fcntl(pty_master,F_GETFL);
  if(retval<0) {
    perror("fcntl_get");
    fflush(stdout);
    fflush(stderr);
    exit(EX_IOERR);
  }

  /* Set the connection to be non-blocking */
  if(fcntl(pty_master,F_SETFL, retval | O_NONBLOCK) < 0) {
    perror("fcnt_setFlag_nonblock:");
    fflush(stdout);
    fflush(stderr);
    exit(1);
  }

  FD_SET(pty_master, &readfds);
  FD_SET(pty_master, &writefds);
  FD_SET(fileno(stdin), &readfds);
  if(isatty(fileno(stdin)))
   {
     if(tty_semi_raw(fileno(stdin)) < 0)
      {
        perror("Error: settingraw mode:");
        fflush(stdout);
        fflush(stderr);
      } /* end of if(tty_raw(fileno(stdin)) < 0) */
     if(atexit(tty_atexit) < 0)
      {
        perror("Atexit setup:");
        fflush(stdout);
        fflush(stderr);
      } /* end of if(atexit(tty_atexit) < 0) */
   }

/* while no signal, we loop around */

  while(1) {
    struct timeval interval;
    fd_set t_readfds;
    fd_set t_writefds;
    fd_set t_exceptfds;

    interval.tv_sec  = 0;
    interval.tv_usec = 100;

    t_readfds   = readfds;
    t_writefds  = writefds;
    t_exceptfds = exceptfds;

    /* check for the signal */
    retval = sigtimedwait(&signal_set, &signalinfo,&timeout);

    if( retval == SIGCHLD ) {
      /* child terminated */
      break;
    }
    else
     {
       if( retval < 0 ) {
         if(errno != EAGAIN) {
           perror("sigtimedwait");
           fflush(stdout);
           fflush(stderr);
           exit(EX_IOERR);
         }
         else
          {
            /* No signal in set was delivered within the timeout period specified */
          }
       }
     } /* end of else */

    if(select (pty_master + 1, &t_readfds, &t_writefds, &t_exceptfds, 
               &interval) < 0)
     {
       perror("Select:");
       fflush(stdout);
       fflush(stderr);
       exit (EX_IOERR);
     }

    if(FD_ISSET(pty_master, &t_readfds))
     {
       retval = read(pty_master, buf, (unsigned int)16384);
       if(retval < 0)
        {
          if(errno != EINTR && errno != EAGAIN) 
           {                    /* Nothing left to read?  */
             fflush(stdout);
             fflush(stderr);
             exit (EXIT_SUCCESS);
           } /* end of else */
        } /* end of if(retval < 0) */
       else
        {
          if(retval == 0)
           {
             if(++err_count > 5)
              {                 /* child closed connection */
                fflush(stdout);
                fflush(stderr);
                exit (EXIT_SUCCESS);
              }
           } /* end of if(retval == 0) */
          else
           {
             write(fileno(stdout), buf, (unsigned int)retval);
             fflush(stdout);
           } /* end of else */
        } /* end of else */
     }
    if(FD_ISSET(fileno(stdin), &t_readfds))
     {
       if(FD_ISSET(pty_master, &t_writefds))
        {
          retval = read(fileno(stdin), buf, (unsigned int)16384);
          if(retval < 0)
           {
             if(errno != EINTR && errno != EAGAIN)
              {                 /* Nothing left to read?  */
                fflush(stdout);
                fflush(stderr);
                exit (EXIT_SUCCESS);
              } /* end of else */
           } /* end of if(retval < 0) */
          else
           {
             if(retval == 0)
              {
                if(++err_count > 5)
                 {              /* lost controlling tty */
                   fflush(stdout);
                   fflush(stderr);
                   exit (EXIT_SUCCESS);
                 }
              } /* end of if(retval == 0) */
             else
              {
                write(pty_master, buf, (unsigned int)retval);
                fflush(stdout);
              } /* end of else */
           } /* end of else */
        } /* end of if(FD_ISSET(pty_master, &writefds)) */
     }    /* something to read on stdin */

} /* Loop */

  fflush(stdout);
  fflush(stderr);

exit(EXIT_SUCCESS);
} /* end of main() */

Signature · 5 lines
-- 
It may be bad manners to talk with your mouth full, but it isn't too
good either if you speak when your head is empty.
Manoj Srivastava   <[email protected]>    <[email protected]> 
1024D/BF24424C print 4966 F272 D093 B493 410B  924B 21BA DABB BF24 424C
#10 lore raw
Quoted 2 lines · Manoj Srivastava

That is strange, seeing that the only changes in that patch
were _adding_ fflush statements.

No, I'm referring to the tty semi raw patch. With it applied, I get erratic output on sshd restart, always losing at least the last OK status but sometimes losing the entire final line. With it reverted (but including the fflush patch), I get stable output, but it always clips the last OK status.

Quoted 2 lines

I am attaching the full open_init_pty.c file below; I've
tested this as extensively as I can on a number of Debian machines.

Yes, this matches what I would have if I apply the tty semi raw patch to what is already committed, which induces the erratic output. I'm using FC3 here.

Quoted 2 lines

______________________________________________________________________

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.