Auditing the C ‘for’ loop

I am reading on Source Code Auditing in the Shellcoder’s Handbook ed. 1 — Off-by-One vulnerabilities. in SPARC’s big-endian systems, they are not a real threat according to the handbook. They are still part of my research and apply to little endian systems. Inside the book, I came  across  a vulnerable For loop that belonged to an old version of the OpenBSD ftp daemon, and it made me question my entire understanding of just the basic for loop. I created a C program to house the example and diagnose my understanding: p.s. original for loop is on pg. 393 1st edition.

#include <stdio.h>
#define MAXPATHLEN 4

int main (int argc, char **argv)
{
  char npath[MAXPATHLEN];
  int i;
  char *name = argv[1];
  for (i=0; *name != '\0' && i < sizeof(npath) - 1; i++,name++)
  {
    npath[i] = *name;
    if (*name == '"')
      npath[++i] = '"';
  }

  npath[i] = '\0';

  printf ("i = %d\n", i);
  printf ("npath = %s\n", npath);
  return 0;
}

here are some possible ways to execute the program:

$ ./a.out aa
i = 2
npath = aa
$ ./a.out aaa
i = 3
npath = aaa
$ ./a.out aa\"
i = 4
npath = aa""

The main lesson was to take the time to analyze, along with the following website: http://www.tutorialspoint.com/cprogramming/c_for_loop.htm

The most important lesson learned from the For loop is that the condition is checked first, the body is executed, and then the increment rule happens ALWAYS after that, without further checking. I did not realize this strict order for years. And that is why the vulnerability exists. I am sure many like me had used to look at the for loop and just think “these rules look right” all is well, but no when you take into the account this interesting sequencing of the increment.. I digress.

Random but helpful: in gdb, use n or next to step the next C line of code, and si for the raw asm stuff. There is more power than just that though, from http://www.cs.mcgill.ca/~consult/info/gdb.html:

Stepping:

 

stepi or si Execute one machine instruction (follows a call).
step or s Execute one C-program statement (steps into functions).
stepi N Do N machine instructions.
nexti or ni Same as si but execute calls as one instructions.
next or n Same as ni but execute functions as one statement.

Posted in buffer overflow, C

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Skip to toolbar