<epigraph>
  <attribution>Donald J. Atwood, General Motors</attribution>
  <simpara
    >To take a significant step forward, you must make a series of finite 
    improvements.
  </simpara>
</epigraph>

<simpara
  >This chapter introduces a framework for scanners and first stage
  infectors, written in plain C. The code is split it into many parts
  that manipulate a central data structure. The idea is to replace
  some of these parts in later chapters to implement improvements and
  different infection methods. Here you will find only the most basic
  parts shared by all programs. A few functions common to all infectors
  are in <xref linkend="scratch"/>, the rest accompanies descriptions
  of infection methods in separate chapters.
</simpara>
<simpara
  >The code is not insertable itself. &yref.doing.it.in.c;
  describes what would be necessary. In the meantime the infectors
  insert and activate one chunk of code, an array of byte prepared
  by <xref linkend="dressing.up.binary.code"/>.
</simpara>
<simpara
  >Target file names are specified through <literal>stdin</literal>,
  not as command line arguments. This is required to scan crowded
  places like <filename>/usr/bin</filename> in one go.
  Anyway, <xref linkend="scanners"/> check executables for irregular
  layout, not signatures.
</simpara>
<simpara
  >Parts are shown in random order and without any
  <literal>#include</literal> statements or prototypes. Identifiers
  prefixed with <literal>TEVWH_</literal> are defined in generated file
  <filename>config.h</filename>. See &yref.verifying.installed.packages;.
  If you need full details I can only recommend a look into the sources
  of this document. <xref linkend="mirrors"/> shows where to get it.
</simpara>
<simpara
  >This code really wants to be C++. Some hardware I'm working on is
  just too slow for big compilers, though. The heavy use of macros
  is a consequence of not using C++, not the reason.
</simpara>

<sect2 id="print_errno" xreflabel="print_errno">
  <title>print_errno</title>

  <simpara
    >A simple replacement of 
    <citerefentry>
      <refentrytitle>perror</refentrytitle>
      <manvolnum>3</manvolnum>
    </citerefentry>.
    If the first argument is -1 instead of
    <citerefentry>
      <refentrytitle>errno</refentrytitle>
      <manvolnum>3</manvolnum>
    </citerefentry> the function works just like
    <citerefentry>
      <refentrytitle>printf</refentrytitle>
      <manvolnum>3</manvolnum>
    </citerefentry>.
  </simpara>

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

</sect2>
<sect2>
  <title>Conditional output</title>

  <simpara
    ><citerefentry>
      <refentrytitle>printf</refentrytitle>
      <manvolnum>3</manvolnum>
    </citerefentry> is a great debugging tool.
    I use it similar to
    <citerefentry>
      <refentrytitle>assert</refentrytitle>
      <manvolnum>3</manvolnum>
    </citerefentry>.
    A single pre-processor definition deactivates them all.
    Or rather groups of them.
    The conventional way to completely remove function calls through
    the pre-processor is to define a parameterized macro that evaluates
    to nothing. But then <literal>printf</literal> takes a variable
    number of arguments. Recent C99 standard provides a mechanism
    to handle this. The <application>gcc</application> extension for
    the same purpose is much older but different (pronounce as
    <quote>incompatible</quote>).
  </simpara>

  <formalpara>
    <title>Example: Macros with variable number of arguments</title>
    <para
      ><programlisting
>/* gcc extension */
#define eprintf(format, args...) fprintf(stderr, format , ## args)

/* new C99 standard */
#define eprintf(...)             fprintf(stderr, __VA_ARGS__)</programlisting
    ></para
  ></formalpara>

  <simpara>I chose obscure syntax instead.</simpara>
  <itemizedlist
    ><listitem><simpara
      >A type name surrounded by brackets is a cast. Casting an
      expression to <type>void</type> discards the result. It is
      not even evaluated if the expression is free of side effects
      and the compiler is reasonably smart.
    </simpara></listitem><listitem><simpara
      >A more common use of brackets is to surround an expression
      without changing its value.
    </simpara></listitem><listitem><simpara
      >Commas are also used for a lot of things. One of the strangest
      is as a comma operator. It evaluates both expression to the left
      and to the right, returning the value of the right.
      Because this is rarely a desired behavior
      <application>gcc</application> issues a special warning if either
      <option>-W</option> or <option>-Wall</option> is specified:
      <literal><errorname>warning: left-hand operand of comma expression
	has no effect</errorname></literal
    ></simpara></listitem
  ></itemizedlist>

  <formalpara>
    <title>Example:</title>
    <para
      ><programlisting
>printf("The answer is %d\n", 42);
(void)("The answer is %d\n", 42);</programlisting
    ></para
  ></formalpara>

</sect2>
<sect2 id="trace.infector.h" xreflabel="trace_infector.h">
  <title>trace_infector.h</title>

  <formalpara>
    <title>Source: src/one_step_closer/trace_infector.h</title>
    <para>
      <programlisting><inlinemediaobject><imageobject><imagedata
	format="linespecific"
	fileref="../src/one_step_closer/trace_infector.h"
      /></imageobject></inlinemediaobject></programlisting>
    </para>
  </formalpara>

</sect2>
<sect2 id="trace_scanner.h" xreflabel="trace_scanner.h">
  <title>trace_scanner.h</title>

  <formalpara>
    <title>Source: src/one_step_closer/trace_scanner.h</title>
    <para>
      <programlisting><inlinemediaobject><imageobject><imagedata
        format="linespecific"
        fileref="../src/one_step_closer/trace_scanner.h"
      /></imageobject></inlinemediaobject></programlisting>
    </para>
  </formalpara>

</sect2>
<sect2 id="target.h" xreflabel="target.h">
  <title>target.h</title>

  <simpara
    >This is the central data structure used by all examples based on
    this framework. Not all struct members are used by all programs,
    though. And obviously scanners have no use for a byte array called
    <literal>infection</literal>.
  </simpara>

  <formalpara>
    <title>Source: src/one_step_closer/target.h</title>
    <para>
      <programlisting><inlinemediaobject><imageobject><imagedata
	format="linespecific"
	fileref="../src/one_step_closer/target.h"
      /></imageobject></inlinemediaobject></programlisting>
    </para>
  </formalpara>


</sect2>
<sect2 id="check.h" xreflabel="check.h">
  <title>check.h</title>

  <simpara
    >None of these programs are ready for end-users. They are intended
    as a base for experiments and have a tendency to accumulate weird
    bugs. If everything is well, terse output is efficient. And when things
    get rough, exact details, including location in the source, are more
    important than nice presentation.
  </simpara>
  <simpara
    >Macro <literal>CHECK</literal> evaluates an expression built
    from a relational operator and two operands. If this condition
    is false then a diagnostic message is written. The first argument
    of <literal>CHECK</literal> is prefixed with <literal>TRACE_</literal>
    to build the name of the function that actually writes the message.
    Expected effective values are either <literal>print_errno</literal> or
    <literal>(void)</literal>, just as defined by the
    <literal>TRACE_</literal> macros in <xref linkend="trace.infector.h"/>.
  </simpara>
  <simpara
    >The message itself consists of four lines, all prefixed with
    <quote>CHECK:</quote>. First comes the name of the target file.
    This relies on having a variable <literal>t</literal> point to
    a structure of type <literal>Target</literal>.
    This is followed by the source file and the line number of the
    <literal>CHECK</literal> statement that failed.
    The third line is the source code of the condition. And the fourth
    line shows the actual result of left and right operand, formatted
    both as <literal>%ld</literal> and <literal>%#lx</literal>.
    The operands are evaluated only once and then assigned to local
    variables of type <literal><type>long</type></literal> inside a
    separate block.
  </simpara>
  <simpara
    >In the body of a macro the character <literal>#</literal> works
    as <quote>stringification</quote> operator to macro arguments; it
    surrounds its operand with double quotes. Unfortunately
    <literal>#</literal> does not accept brackets around the operand.
    To maintain the precaution that arguments in macros are evaluated
    only inside brackets we need an intermediate macro,
    <literal>QUOTE_EXP</literal>.
  </simpara>
  <simpara
    >The predefined macro <literal>__LINE__</literal> evaluates
    to the current line number. Since <literal>#</literal> works
    only on macro arguments and not arbitrary definitions we need
    an intermediate macro again. Unfortunately a simple
    <literal>QUOTE_EXP(__LINE__)</literal> evaluates to
    <literal>"__LINE__"</literal>. The intended result requires another
    level of mediation through <literal>QUOTE_NUM</literal>.
    It is not possible to stringify the value of symbols declared
    through <literal>enum</literal> or <literal>const int</literal>.
  </simpara>

  <formalpara>
    <title>Source: src/one_step_closer/check.h</title>
    <para>
      <programlisting><inlinemediaobject><imageobject><imagedata
	format="linespecific"
	fileref="../src/one_step_closer/check.h"
      /></imageobject></inlinemediaobject></programlisting>
    </para>
  </formalpara>

</sect2>
<sect2 id="main" xreflabel="main">
  <title>main</title>

  <simpara
    >The differences between infectors and scanners show in
    <xref linkend="target.action.1"/> and <xref linkend="print.summary.1"/>,
    but not in <literal>main</literal>.
    On success each implementation of <literal>action</literal> will
    output a single line per target. The file name used in that case
    is a bit simplified. If the value of environment variable
    <literal>TEVWH_TMP</literal> is the prefix of a target file
    name then this prefix is cut off from success reports.
    Anyway, this is relevant only to scanners.
  </simpara>
  <simpara
    >Array <literal>stat</literal> is an ugly hack to gather
    arbitrary statistics without having to define a different
    interface for every program.
  </simpara>

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

</sect2>
<sect2 id="target.open.src">
  <title>target_open_src</title>

  <simpara
    >Modifying a file in place, as opposed to writing a copy,
    is possible but difficult. And between first and final
    modification contents of the target is invalid.
    Imagine a worst-case scenario of a virus infecting
    <filename>/bin/sh</filename> being interrupted through a power
    failure (or emergency shutdown of a hectic admin).
  </simpara>
  <para
    >There are a few approaches to change a file while copying.
    <itemizedlist>
      <listitem>
	<simpara>Use
	  <citerefentry>
	    <refentrytitle>lseek</refentrytitle>
	    <manvolnum>2</manvolnum>
	  </citerefentry>,
	  <citerefentry>
	    <refentrytitle>read</refentrytitle>
	    <manvolnum>2</manvolnum>
	  </citerefentry>
	  and
	  <citerefentry>
	    <refentrytitle>write</refentrytitle>
	    <manvolnum>2</manvolnum>
	  </citerefentry>
	  to load pieces of the source into memory,
	  patch them, and write them to destination.
	  A lot of work. Can be really inefficient.
	</simpara>
      </listitem>
      <listitem>
	<simpara>Use
	  <citerefentry>
	    <refentrytitle>read</refentrytitle>
	    <manvolnum>2</manvolnum>
	  </citerefentry>
	  to get the whole source file in one go. Requires more memory.
	  But then even the largest executable files have only a few MB.
	</simpara>
      </listitem>
      <listitem>
	<simpara>Use 
	  <citerefentry>
	    <refentrytitle>mmap</refentrytitle>
	    <manvolnum>2</manvolnum>
	  </citerefentry>.
	  In my humble opinion obviously the best way.
	</simpara>
      </listitem>
    </itemizedlist>
    Using <constant>MAP_PRIVATE</constant> for argument
    <parameter>flags</parameter> of 
    <citerefentry>
      <refentrytitle>mmap</refentrytitle>
      <manvolnum>2</manvolnum>
    </citerefentry>
    activates copy-on-write semantics. You can read and write
    as if you had chosen the read-in-one-go method, but the implementation
    is more efficient. Unmodified pages are loaded directly from
    the file.  On low memory conditions these pages can be discarded
    without saving them in swap-space. 
  </para>

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

</sect2>
<sect2 id="target.close">
  <title>target_close</title>

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

</sect2>
<sect2 id="target.is.elf">
   <title>target_is_elf</title>

  <simpara
    >A visible virus is a dead virus. Breaking things is quite the
    opposite of invisibility. So before you even think about polymorphism
    and stealth mechanisms you should go sure your code does nothing
    unexpected.
    On the other hand exhaustive checks of target files will severely
    increase code size. And verifying signatures and other constant
    values is likely to make the virus code itself a constant signature.
    A better approach is to compare the target with the host executable
    currently running the virus. <literal>SELF</literal> is defined
    in <xref linkend="target.h"/>.
  </simpara>
  <simpara
    >Finding a meaningful set of tests is an art in it itself.
    For example some executables of Red Hat 8.0 have an additional
    program header of type <literal>GNU_EH_FRAME</literal>.
    This means that <varname>e_phnum</varname> can differ between
    infector and target.
  </simpara>

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

</sect2>
<sect2 id="get.seg" xreflabel="target_get_seg">
  <title>target_get_seg</title>

  <simpara
    >Finding code and data segment in a loop is really overkill.
    But this way we can do some general checks. See &yref.readelf;
    for details.
  </simpara>

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

</sect2>
