<epigraph>
  <attribution>Doug Gwyn</attribution
  <para>
    Unix was not designed to stop people from doing stupid things,
    because that would also stop them from doing clever things.
  </para>
</epigraph>

<para>
  <xref linkend="evil-magic"> I declared the code generated by
  <command>gcc</command> to be unsuitable for a virus. And then
  rewrote the whole thing in assembly. A less drastic solution is
  to use inline assembly to correct only what's really necessary.
</para>

<sect2 id="system_calls" xreflabel="System calls">
  <title>System calls</title>

  <para>
    Have a look at the
    <link linkend="in_doubt_use_force">disassembly</link>
    of function <function>write</function>.
    That code checks the return value of the system call
    and sets variable <varname>errno</varname> on error.
    We don't need this. Actually we can't access global variables at all.
    And <link linkend="Target_infection">our code</link>
    does not care for the return code, anyway.
  </para>
  <para>
    It is also remarkable that the code loads only the four required
    registers. The sources of glibc make great effort to provide
    optimal code for every case. I find the macros in
    <filename>glibc-2.2.4/sysdeps/unix/sysv/linux/i386/sysdep.h</filename>
    quite interesting.
  </para>
  <para>
    For our needs a simple function will do. The line starting with a
    colon is a constraint. It somehow declares the value that
    <literal>eax</literal> has after the <literal>asm</literal> block
    to be the value of variable <varname>result</varname>.
    The following <literal>return</literal> statement would load the
    value of <varname>result</varname> into <literal>eax</literal>
    again, but fortunately <command>gcc</command> optimizes this correctly.
    Of course the code would work without constraint and
    <literal>return</literal>. But the compiler would issue warning
    <quote>no return statement in function returning non-void</quote>.
  </para>
  <para>
    RedHat's <command>gcc-2.96-98</command> produces weird code
    if the assembly statements are grouped in a single
    <literal>asm</literal> block. In that case
    <literal>mov ebp,esp</literal> (see the following disassembly)
    is done not on function entry, but after the <literal>asm</literal>.
  </para>
  <para>
    Note that we can't name our function plain
    <function>syscall</function>. There is already such a
    declaration in <filename>unistd.h</filename>.
  </para>

  <formalpara>
    <title>Source - do_syscall.inc</title>
    <para>
      <programlisting><inlinegraphic format="linespecific"
        fileref="../src/doing_it_in_c/do_syscall.inc"
      ></programlisting>
    </para>
  </formalpara>

  <para>
    The disassembly proves that the return statement is really
    optimized (though that really does not help the bloat).
  </para>

  <formalpara>
    <title>Output - do_syscall.gdb</title>
    <para>
      <programlisting><inlinegraphic format="linespecific"
        fileref="../out/doing_it_in_c/do_syscall.gdb"
      ></programlisting>
    </para>
  </formalpara>

</sect2>
<sect2>
  <title>Position independent code</title>

  <para>
    Previous examples required a separate pass to build the insertable
    code. Output of the first pass is one chunk of bytes. 
    The only interface to the infector is the place to patch with
    the original entry address (4 bytes at offset 1).
  </para>
  <para>
    The crucial part are the lines in <xref linkend="writeInfection">
    where we pass the address of the chunk of bytes to  
    <citerefentry>
      <refentrytitle>write</refentrytitle>
      <manvolnum>2</manvolnum>
    </citerefentry>.
    In a real virus these lines will also be part of inserted code.
    The naive approach is to patch these instructions on infection.
    But this again leads to a two-pass process.
    The first is required to find the offset of required patches.
    A more comfortable approach is to make the code position independent
    by calculating absolute addresses at run-time.
    Note that <command>gcc</command>'s option <literal>-fpic</literal>
    does not help this problem at all.
  </para>
  <blockquote>
    <para><literal>-fpic</literal></para>
    <para>
     Generate position-independent code (PIC) suitable for use in a
     shared library, if supported for the target machine.  Such code
     accesses all constant addresses through a global offset table
     (GOT).  The dynamic loader resolves the GOT entries when the
     program starts (the dynamic loader is not part of GCC; it is part
     of the operating system).  If the GOT size for the linked
     executable exceeds a machine-specific maximum size, you get an
     error message from the linker indicating that <literal>-fpic</literal>
     does not work; in that case, recompile with <literal>-fPIC</literal>
     instead.  (These maximums are 16k on the m88k, 8k on the Sparc,
     and 32k on the m68k and RS/6000.  The 386 has no such limit.)
    </para>
  </blockquote>

  <para>
    The instruction pointer is a register that holds the address of
    the next instruction to execute. Unlike <quote>real</quote>
    registers there is no direct way to retrieve its value.
    A <literal>call</literal> pushes the current value of
    <literal>IP</literal> onto the stack and adds a relative offset
    to it. Offset 0 just continues with the following instruction.
    And if that instruction is a <literal>pop</literal> we load
    the the address of the <literal>pop</literal> instruction itself
    in a regular register.
  </para>
  <para>
    We can compare the actual value of <literal>IP</literal>
    with the location the linker had in mind when it built the
    original executable. 
    If the following code is executed at the exact location the linker
    gave it in the original file, then <literal>eax</literal> will
    be exactly the address of label <literal>delta</literal> after
    the <literal>pop</literal>. And the following <literal>sub</literal>
    instruction will then set <literal>eax</literal> to zero. 
  </para>

  <formalpara>
    <title>Source - get_relocate_ofs.inc</title>
    <para>
      <programlisting><inlinegraphic format="linespecific"
        fileref="../src/doing_it_in_c/get_relocate_ofs.inc"
      ></programlisting>
    </para>
  </formalpara>

  <para>
    A dump from <command>gdb</command> is not enough to demonstrate
    this function. I want to show that the last four bytes
    of the opcode of the <literal>call</literal> instruction are
    really zero.
  </para>
  
  <formalpara>
    <title>Command - ndisasm.sh</title>
    <para>
      <programlisting><inlinegraphic format="linespecific"
        fileref="../src/doing_it_in_c/ndisasm.sh"
      ></programlisting>
    </para>
  </formalpara>

  <formalpara>
    <title>Output - get_relocate_ofs.ndisasm</title>
    <para>
      <programlisting><inlinegraphic format="linespecific"
        fileref="../out/doing_it_in_c/get_relocate_ofs.ndisasm"
      ></programlisting>
    </para>
  </formalpara>

</sect2>
<sect2>
  <title>writeInfection</title>

  <para>
    We now have all parts to implement a position independent version
    of <function>Target::writeInfection</function>. This code works
    as part of a first stage infector. Output to prove it is at the
    end of this chapter. It should also work as part of an infection.
    But do you remember the paragraph in <xref linkend="intro"> about 
    <quote>exercise left to the reader</quote>?
  </para>
  <para>
    Compare this code with
    <link linkend="writeInfection">the first version</link>.
    Instead of operating on a single variable,
    <xref linkend="Target_infection">,
    we write every byte between the start of
    <varname>infection</varname> and  function <function>end</function>.
    Making sure that certain functions and constant data build a
    consecutive region requires little more than discipline and
    dirty tricks.
  </para>

  <formalpara>
    <title>Source - write_infection.inc</title>
    <para>
      <programlisting><inlinegraphic format="linespecific"
        fileref="../src/doing_it_in_c/write_infection.inc"
      ></programlisting>
    </para>
  </formalpara>

</sect2>
<sect2 id="a_section_called_text" xreflabel="A section called .text">
  <title>A section called .text</title>

  <para>
    It is very difficult to persuade the linker to arrange
    object files in a specific order. But by putting all definitions
    into a single compilation unit (a <filename>.c</filename> that
    ends up in a <filename>.o</filename>) we are quite safe on that
    front. And though it is nowhere specified, most compilers will write
    definitions in the order they read them. So the <quote>only</quote>
    remaining problem is implementation specific classification of
    definitions. A small test program illustrates the problem.
  </para>

  <formalpara>
    <title>Source - addr.c</title>
    <para>
      <programlisting><inlinegraphic format="linespecific"
        fileref="../src/doing_it_in_c/addr.c"
      ></programlisting>
    </para>
  </formalpara>
  <formalpara>
    <title>Output</title>
    <para>
      <programlisting><inlinegraphic format="linespecific"
        fileref="../out/doing_it_in_c/addr"
      ></programlisting>
    </para>
  </formalpara>

  <para>
    Functions are ordered intuitively. However, constant data is
    put in a separate section called <literal>.rodata</literal>.
    And sections are ordered as whole. See the section-to-segment
    mapping in <command>readelf</command>'s output at 
    <xref linkend="bashful_glance">.
  </para>
  <para>
    I see a few approaches to the problem.
  </para>
  <itemizedlist>
    <listitem>
      <para>
        Copy the complete code-segment as defined by the ELF header.
      </para>
    </listitem>
    <listitem>
      <para>
        Define <literal>begin</literal> and <literal>end</literal>
	for each section to copy.
      </para>
    </listitem>
    <listitem>
      <para>
        Put constant data into section <literal>.text</literal>.
      </para>
    </listitem>
  </itemizedlist>

  <para>
    Anyway, the real problem is accessing these bytes in a position
    independent fashion. For code this is more or less default.
    <literal>call</literal> and <literal>jmp</literal> work
    with relative offsets. Large contiguous <literal>switch</literal>
    blocks could get optimized as a lookup tables, but this is easy
    to work around. Explicit function pointers can be corrected
    manually with <function>get_relocate_ofs</function>.
    The same be could be done with items in virtual method tables.
    But then the table itself is accessed by compiler-generated code
    which is hard to correct.
  </para>
  <para>
    However, every data access requires explicit calculation through
    <function>get_relocate_ofs</function>. This includes innocent
    looking string literals. Basically you always have to look at
    the disassembly of your C code to go sure.
  </para>
  <para>
    In our trivial example <varname>Target::infection</varname>
    holds stub code written in assembler and is never accessed as data.
    Anyway, here is <command>gcc</command>'s documentation on the issue.
  </para>

  <blockquote>
    <para>section ("section-name")</para>
    <para>
      Normally, the compiler places the objects it generates in sections
      like <quote>data</quote> and <quote>bss</quote>.
      Sometimes, however, you need additional sections, or you need
      certain particular variables to appear in special sections,
      for example to map to special hardware.  The <quote>section</quote>
      attribute specifies that a variable (or function) lives
      in a particular section.
    </para>
  </blockquote>

</sect2>
<sect2 id="the_stub" xreflabel="The stub">
  <title>The stub</title>

  <para>
    This is the link between regular C code and unsuspecting host.
  </para>
  <itemizedlist>
    <listitem>
      <para>
	The new entry point is at a constant offset inside
	inserted code. Preferred value is 0.
      </para>
    </listitem>
    <listitem>
      <para>
	The original entry address is patched into the inserted code
	at a constant offset. Previous examples used 1.
      </para>
    </listitem>
    <listitem>
      <para>
	We need a mechanism to activate host code again.
	Ideally we should leave no trace of our existence,
	but unmodified registers (especially <literal>esp</literal>)
	will suffice.
      </para>
    </listitem>
  </itemizedlist>

  <para>
    The code below relies on prober alignment through the compiler.
    Through an <literal>__attribute__</literal> clause the character
    array <varname>Target::infection</varname> starts at an address
    that is a multiple of 16. An assembler directive pads the stub
    with enough <literal>nop</literal> instruction to make its
    size a multiple of 16. Which means that any object placed
    after the <varname>infection</varname> is also aligned on
    a multiple of 16. And 16 is typically the highest possible
    alignment for i386 compilers.
  </para>
  <para>
    There is absolutely no reason for compiler or assembler
    to insert padding bytes between <varname>infection</varname>
    and the following function, called <function>core</function>.
  </para>

  <formalpara>
    <title>Source - infection.asm</title>
    <para>
      <programlisting><inlinegraphic format="linespecific"
        fileref="../src/doing_it_in_c/infection.asm"
      ></programlisting>
    </para>
  </formalpara>
  <formalpara>
    <title>Source - infection.inc</title>
    <para>
      <programlisting><inlinegraphic format="linespecific"
        fileref="../out/doing_it_in_c/infection.inc"
      ></programlisting>
    </para>
  </formalpara>

  <para>
    If you consider above code too much vodoo, think about the alternative.
    Functions compiled by <command>gcc</command> are decorated with
    entry and exit code. The dump at the end of
    <xref linkend="system_calls"> is the next best example.
    I have no way to supress that <literal>push ebp</literal>.
    And I also don't see how to put code between
    <literal>pop ebp</literal> and <literal>ret</literal>.
    So we would have to build our own exit code using inline
    assembly. Basically a <literal>pop ebp</literal> and some kind
    of <literal>jmp</literal>. The exit code generated by
    <command>gcc</command> would still be there, but just not used.
  </para>

</sect2>
<sect2>
  <title>All together now</title>

  <formalpara>
    <title>Output - build</title>
    <para>
      <programlisting><inlinegraphic format="linespecific"
        fileref="../out/doing_it_in_c/three/cc"
      ></programlisting>
    </para>
  </formalpara>

</sect2>
