First Assignment

Gets Worm

This is the kind of innocent program you should be trying to subvert:
#include <stdio.h>

void gets(char *s)
{ for (int i=0; 1; i+=1)
  { int c=getchar();
    if (c=='\n' || c==EOF) 
    { s[i]=0;
      break; }
    s[i]=c; } }

int answer_question(void)
{ char line[28];
  gets(line);
  int val1=0, val2=0, operator, ptr=0;
  while (line[ptr]>='0' && line[ptr]<='9')
  { val1=val1*10+line[ptr]-'0';
    ptr+=1; }
  operator=line[ptr];
  ptr+=1;
  while (line[ptr]>='0' && line[ptr]<='9')
  { val2=val2*10+line[ptr]-'0';
    ptr+=1; }
  switch (operator)
  { case '+': return val1+val2;
    case '-': return val1-val2;
    case '*': return val1*val2;
    case '/': return val1/val2; }
  return -1; }

void main(void)
{ printf("Enter a formula: ");
  int ans=answer_question();
  printf("The answer is %d\n", ans); }
You may use exactly that program if you like, or you may modify it in any way you like, or you may provide one of your own. The program must use a gets-like function to read input, and you must provide input that makes the program behave in a way that is obviously not intended by the writer. As you can see, the program above should only be capable of producing output something like The answer is 123, so your specially designed input should make it do something completely different, not just produce a wrong result. Maybe you can make it say a bad word, or maybe something more spectacular.

Remember, you are taking advantage of buffer over-runs. You might want to make the string "char line[28]" a bit bigger to suit your purposes. Of course your worm will be tailor made for the innocent program you are subverting. Don't expect one worm to work for other programs.



You don't want to have to type the hexadecimal codes for your worm input every time you try running it. A program like this:
#include <stdio.h>

unsigned char code[] = { 0x53, 0x75, 0x72, 0x70, 0x72, 0x69, 0x73, 0x65, 0x21, '\n' };
    // hex. ascii codes:  S     u     r     p     r     i     s     e     !
const int codesize=sizeof(code);

void main(void)
{ FILE *f=fopen("worm.txt", "w");
  for (int i=0; i<codesize; i+=1)
    fputc(code[i], f);
  fclose(f); }
Can be used to create a file containing the characters you want to send to the innocent gets-using program, and you can redirect the input to come from that file when the program runs, using the emulator command "infile 0 worm.txt".

To work out the hexadecimal codes for your worm program, you will need to pay some attention to the processor instruction set, and maybe use the assembler to produce the codes for you (asm -l filename produces hexadecimal codes interleaved with source assembly instructions), and maybe even trace or single step a running program in the emulator.