\begin{exe} {More on setuid and Scripts}

   Suppose we have the following \textbf{C} program
   (\filelink{./writeit.c}) which attempts to overwrite a
   file in the current directory named \verb?afile?.
   This file can be extracted from your
   downloaded \verb?SOLUTIONS? file as \lablink{writeit.c}.

   \cfile[\texttt{writeit.c}]{labs/writeit.c}

   If the
   program is called \filelink{writeit.c}, it can be
   compiled simply by doing:

   \begin{cmd}
$ make writeit
   \end{cmd}
   or equivalently
   \begin{cmd}
$ gcc -o writeit writeit.c
   \end{cmd}

   If (as a normal user) you try to run this program on a
   file owned by root you'll get

   \begin{cmd}
$ sudo touch afile
$ ./writeit
   \end{cmd}
   \begin{response}
wrote -1 bytes
   \end{response}
   but if you run it as root:
   \begin{cmd}
$ sudo ./writeit
   \end{cmd}
   \begin{response}
wrote 15 bytes
   \end{response}
   Thus, the root user was able to overwrite the file it
   owned, but a normal user could not.

   Note that changing the owner of \textbf{writeit} to root
   does not help:

   \begin{cmd}
$ sudo chown root.root writeit
$ ./writeit
   \end{cmd}
   \begin{response}
wrote -1 bytes
   \end{response}
   because it still will not let you clobber \filelink{afile}.

   By setting the \textbf{setuid} bit you can make any normal
   user capable of doing it:

   \begin{cmd}
$ sudo chmod +s writeit
$ ./writeit
   \end{cmd}
   \begin{response}
wrote 15 bytes
   \end{response}

   \begin{info}

      You may be asking, why didn't we just write a script
      to do such an operation, rather than to write and
      compile an executable program?

      Under \textbf{Linux}, if you change the
      \textbf{setuid} bit on such an executable script, it won't
      do anything unless you actually change the
      \textbf{setuid} bit on the shell (such as
      \textbf{bash}) which would be a big mistake; anything
      running from then on would have escalated privilege!
   \end{info}

\end{exe}

