<epigraph>
  <attribution>anonymous</attribution>
  <simpara>
    The C Programming Language - A language which combines the
    flexibility of assembly language with the power of assembly
    language.
  </simpara>
</epigraph>

<simpara>
  <xref linkend="language.of.evil"/> I declared the code
  generated by
  <citerefentry>
    <refentrytitle>gcc</refentrytitle>
    <manvolnum>1</manvolnum>
  </citerefentry> 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.
</simpara>

<sect2 id="system.calls" xreflabel="System calls">
  <title>System calls</title>

  <simpara>
    Have a look at the
    <link linkend="in.doubt.use.force">disassembly</link>
    of function <function>write</function> in glibc.
    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 <xref linkend="infection.1"/> does not care for the return code,
    anyway.
  </simpara>
  <simpara>
    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.
  </simpara>
  <simpara>
    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
    <citerefentry>
      <refentrytitle>gcc</refentrytitle>
      <manvolnum>1</manvolnum>
    </citerefentry> 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>.
  </simpara>
  <simpara>
    Red Hat's <application>gcc-2.96-98</application> produces weird code
    if the assembly statements are grouped in a single
    <literal>asm</literal> block. In that case
    <literal>mov ebp,esp</literal> is done not on function entry,
    but after the <literal>asm</literal>.
    See <xref linkend="all.together.now"/> for a disassembly.
    <function>do_syscall</function> is the last part.
  </simpara>
  <simpara>
    Note that we can't name our function plain
    <function>syscall</function>. There is already such a
    declaration in <filename>unistd.h</filename>.
  </simpara>

  <formalpara>
    <title>Source: src/doing_it_in_c/do_syscall.inc</title>
    <para>
      <programlisting><inlinemediaobject><imageobject><imagedata
        format="linespecific"
	fileref="../../src/doing_it_in_c/do_syscall.inc"
      /></imageobject></inlinemediaobject></programlisting>
    </para>
  </formalpara>

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

  <simpara>
    Previous examples needed 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).
  </simpara>
  <simpara>
    The crucial part are the lines in &yref.target.write.infection.1;
    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 patches.
    A more comfortable approach is to make the code position independent
    by calculating absolute addresses at run-time.
    Note that option <option>-fpic</option> of
    <citerefentry>
      <refentrytitle>gcc</refentrytitle>
      <manvolnum>1</manvolnum>
    </citerefentry>
    does not help the problem at all.
  </simpara>
  <blockquote>
    <simpara><option>-fpic</option></simpara>
    <simpara>
      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 <option>-fpic</option>
      does not work; in that case, recompile with <option>-fPIC</option>
      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.)
    </simpara>
  </blockquote>

  <simpara>
    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.
  </simpara>
  <simpara>
    In function we <function>get_relocate_ofs</function> we compare
    the actual value of <literal>IP</literal> with the location the
    linker had in mind when it built the original executable. 
    If 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. 
  </simpara>

  <formalpara>
    <title>Source: src/doing_it_in_c/get_relocate_ofs.inc</title>
    <para>
      <programlisting><inlinemediaobject><imageobject><imagedata
        format="linespecific"
	fileref="../../src/doing_it_in_c/get_relocate_ofs.inc"
      /></imageobject></inlinemediaobject></programlisting>
    </para>
  </formalpara>

  <simpara>
    A dump from
    <citerefentry>
      <refentrytitle>gdb</refentrytitle>
      <manvolnum>1</manvolnum>
    </citerefentry> 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.
  </simpara>
  
  <formalpara>
    <title>Command: src/doing_it_in_c/&config.ASM.STYLE;.sh</title>
    <para>
      <programlisting><inlinemediaobject><imageobject><imagedata
        format="linespecific"
	fileref="../../src/doing_it_in_c/&config.ASM.STYLE;.sh"
      /></imageobject></inlinemediaobject></programlisting>
    </para>
  </formalpara>

  <anchor id="output.get.relocate.ofs"/>
  <formalpara>
    <title>Output: &config.OUT;/doing_it_in_c/get_relocate_ofs.disasm</title>
    <para>
      <programlisting><inlinemediaobject><imageobject><imagedata
        format="linespecific"
	fileref="../../&config.OUT;/doing_it_in_c/get_relocate_ofs.disasm"
      /></imageobject></inlinemediaobject></programlisting>
    </para>
  </formalpara>

</sect2>
<sect2 id="target.write.infection.2">
  <title>target_write_infection #2</title>

  <simpara>
    We now have all parts to implement a position independent version
    of <function>target_write_infection</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 about <quote>exercise left to
      the reader</quote>?
  </simpara>
  <simpara>
    Compare this code with the first version,
    &yref.target.write.infection.1;.
    Instead of operating on a single variable,
    <xref linkend="infection.1"/>, we write every byte between the start
    of <varname>infection</varname> and function <function>end</function>.
    The prototypes are required by the code of <function>body</function>.
    For reasons explained below, <filename>infection.inc</filename>
    and <filename>body.inc</filename> must lie next to each other.
    Anyway, the highlight of this chapter is the character constant
    <varname>msg</varname>.
  </simpara>

  <formalpara>
    <title>Source: src/doing_it_in_c/write_infection.inc</title>
    <para>
      <programlisting><inlinemediaobject><imageobject><imagedata
        format="linespecific"
	fileref="../../src/doing_it_in_c/write_infection.inc"
      /></imageobject></inlinemediaobject></programlisting>
    </para>
  </formalpara>

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

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

  <formalpara>
    <title>Source: src/doing_it_in_c/addr.c</title>
    <para>
      <programlisting><inlinemediaobject><imageobject><imagedata
        format="linespecific"
	fileref="../../src/doing_it_in_c/addr.c"
      /></imageobject></inlinemediaobject></programlisting>
    </para>
  </formalpara>
  <formalpara>
    <title>Output: &config.OUT;/doing_it_in_c/addr</title>
    <para>
      <programlisting><inlinemediaobject><imageobject><imagedata
        format="linespecific"
	fileref="../../&config.OUT;/doing_it_in_c/addr"
      /></imageobject></inlinemediaobject></programlisting>
    </para>
  </formalpara>

  <simpara>
    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 the output of
    <citerefentry>
      <refentrytitle>readelf</refentrytitle>
      <manvolnum>1</manvolnum>
    </citerefentry> at <xref linkend="bashful.glance"/>.
  </simpara>
  <simpara>I see a few approaches to the problem.</simpara>
  <itemizedlist>
    <listitem>
      <simpara>
        Copy the complete code-segment as defined by the
	<acronym>ELF</acronym> header.
      </simpara>
    </listitem>
    <listitem>
      <simpara>
        Define <literal>begin</literal> and <literal>end</literal>
	for each section to copy.
      </simpara>
    </listitem>
    <listitem>
      <simpara>
        Put constant data into section <literal>.text</literal>.
      </simpara>
    </listitem>
  </itemizedlist>

  <simpara>
    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.
  </simpara>
  <simpara>
    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.
  </simpara>
  <simpara>
    In our trivial example <varname>infection</varname>
    holds stub code written in assembler and is never accessed as data.
    Anyway, here is the documentation of
    <citerefentry>
      <refentrytitle>gcc</refentrytitle>
      <manvolnum>1</manvolnum>
    </citerefentry> on the issue.
  </simpara>

  <blockquote>
    <simpara>section ("section-name")</simpara>
    <simpara>
      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.
    </simpara>
  </blockquote>

</sect2>
<sect2 id="the.stub" xreflabel="The stub">
  <title>The stub</title>

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

  <simpara>
    Calculating the offset to patch with the original entry point
    definitely requires a separate pass. But good design can make
    this pass constant. We can use the same stub, with the same offset,
    for every kind of infective code.
  </simpara>

  <simpara>
    The natural approach is to code the stub in a mixture of C and
    inline assembly and use 
    <citerefentry>
      <refentrytitle>ndisasm</refentrytitle>
      <manvolnum>1</manvolnum>
    </citerefentry>
    to check the offset. This has the disadvantage of limited control.
    Functions compiled by
    <citerefentry>
      <refentrytitle>gcc</refentrytitle>
      <manvolnum>1</manvolnum>
    </citerefentry> are decorated with entry and exit code.
    The disassembly of <xref linkend="address.of.main"/> is a fine example.
    I have no way to suppress the first two lines,
    <literal>push ebp</literal> and <literal>mov ebp,esp</literal>.
    Even worse, functions containing <literal>asm</literal> statements
    seem the defy all logic. Just see where <literal>mov ebp,esp</literal>
    is in the code of <link linkend="output.get.relocate.ofs"
      ><function>get_relocate_ofs</function></link>.
    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
    <citerefentry>
      <refentrytitle>gcc</refentrytitle>
      <manvolnum>1</manvolnum>
    </citerefentry> would still be there, but just not used.
  </simpara>

  <simpara>
    On the other hand the traditional way of mixing C and assembler
    code through separate <literal>.o</literal> files is not possible.
    Fortunately we have a tool that converts disassembly into a C style
    array constant: &yref.dressing.up.binary.code;
    This approach has one major problem, though. The assembly code
    is built independent of the C code. So the offset of the virus body
    (a plain C function) is not known during assembly of the stub.
    Patching the offset into the stub at run time is the obvious solution.
    Assuming a constant offset is the kind of black magic I prefer.
    But then my other hobby is selling innocent readers bull.
    The real motivation for the following hack is to recycle
    the framework from &yref.one.step.closer;.
    There are a lot of possible variations.
  </simpara>

  <simpara>
    The code below relies on prober alignment through the compiler.
    Because of the <literal>__attribute__</literal> clause the character
    array <varname>infection</varname> starts at an address
    that is a multiple of <constant>8</constant>. An assembler
    directive pads the stub with enough <literal>nop</literal>
    instruction to make its size a multiple of <constant>8</constant>.
    Which means that any object placed after the
    <varname>infection</varname> is also aligned on a multiple of
    <constant>8</constant>.
  </simpara>
  <simpara>
    On i386 the largest built-in type of C compilers is
    <type>double</type>. And
    <literal>sizeof(<type>double</type>)</literal> is
    <constant>8</constant>. So this number is typically
    the highest alignment used in a section. 
    Another school of thought uses higher alignment to put data
    on cache line boundaries. And sections themselves are usually
    aligned on paragraphs (16 bytes), a term known since the days
    of real mode.  
    But for our example there is no reason for compiler or assembler
    to insert padding bytes between <varname>infection</varname>
    and the following function, called <function>body</function>.
  </simpara>

  <formalpara>
    <title>Source: src/doing_it_in_c/i1/&config.ARCH;-&config.UNAME;.S</title>
    <para>
      <programlisting><inlinemediaobject><imageobject><imagedata
        format="linespecific"
	fileref="../../src/doing_it_in_c/i1/&config.ARCH;-&config.UNAME;.S"
      /></imageobject></inlinemediaobject></programlisting>
    </para>
  </formalpara>
  <formalpara>
    <title>Output = Source: &config.OUT;/doing_it_in_c/i1/infection.inc</title>
    <para>
      <programlisting><inlinemediaobject><imageobject><imagedata
        format="linespecific"
	fileref="../../&config.OUT;/doing_it_in_c/i1/infection.inc"
      /></imageobject></inlinemediaobject></programlisting>
    </para>
  </formalpara>

</sect2>
<sect2 id="all.together.now" xreflabel="All together now">
  <title>All together now</title>

  <simpara>
    The only missing piece is the actual infection body.
    We use another piece of magic, built-in functions.
    From the documentation of
    <citerefentry>
      <refentrytitle>gcc</refentrytitle>
      <manvolnum>1</manvolnum>
    </citerefentry>:
  </simpara>
  <blockquote>
    <simpara>
      GCC normally generates special code to handle certain built-in
      functions more efficiently; for instance, calls to
      <function>alloca</function> may become single instructions that
      adjust the stack directly, and calls to <function>memcpy</function>
      may become inline copy loops.  The resulting code is often both
      smaller and faster, but since the function calls no longer appear
      as such, you cannot set a breakpoint on those calls, nor can you
      change the behavior of the functions by linking with a different
      library.
    </simpara>
    <simpara>
      Currently, the functions affected include
      <function>abort</function>, <function>abs</function>,
      <function>alloca</function>, <function>cos</function>,
      <function>cosf</function>, <function>cosl</function>,
      <function>exit</function>, <function>_exit</function>,
      <function>fabs</function>, <function>fabsf</function>,
      <function>fabsl</function>, <function>ffs</function>,
      <function>labs</function>, <function>memcmp</function>,
      <function>memcpy</function>, <function>memset</function>,
      <function>sin</function>, <function>sinf</function>,
      <function>sinl</function>, <function>sqrt</function>,
      <function>sqrtf</function>, <function>sqrtl</function>,
      <function>strcmp</function>, <function>strcpy</function>
       and <function>strlen</function>.
    </simpara>
  </blockquote>

  <formalpara>
    <title>Source: src/doing_it_in_c/body.inc</title>
    <para>
      <programlisting><inlinemediaobject><imageobject><imagedata
        format="linespecific"
	fileref="../../src/doing_it_in_c/body.inc"
      /></imageobject></inlinemediaobject></programlisting>
    </para>
  </formalpara>

  <simpara>
    And a disassembly, just to go sure.
    It consists of <varname>infection</varname>,
    <function>body</function>, <function>get_relocate_ofs</function>
    and <function>do_syscall</function>, in that order.
    This is not all inserted code.
    The character constant <varname>msg</varname> is not shown.
  </simpara>

  <formalpara>
    <title>Output: &config.OUT;/doing_it_in_c/e3i1.disasm</title>
    <para>
      <programlisting><inlinemediaobject><imageobject><imagedata
        format="linespecific"
	fileref="../../&config.OUT;/doing_it_in_c/e3i1.disasm"
      /></imageobject></inlinemediaobject></programlisting>
    </para>
  </formalpara>

</sect2>
<sect2 id="off.we.go.again">
  <title>Off we go again</title>

  <formalpara>
    <title>Output: &config.OUT;/doing_it_in_c/e3i1/cc</title>
    <para>
      <programlisting><inlinemediaobject><imageobject><imagedata
        format="linespecific"
	fileref="../../&config.OUT;/doing_it_in_c/e3i1/cc"
      /></imageobject></inlinemediaobject></programlisting>
    </para>
  </formalpara>

  <formalpara>
    <title>Output: &config.OUT;/doing_it_in_c/test-e3i1</title>
    <para>
      <programlisting><inlinemediaobject><imageobject><imagedata
        format="linespecific"
	fileref="../../&config.OUT;/doing_it_in_c/test-e3i1"
      /></imageobject></inlinemediaobject></programlisting>
    </para>
  </formalpara>

</sect2>
