Search code examples
assemblyx86reverse-engineeringctf

What is the output of this program when the parameters 0x7 and 0x18


I have the following assembly program

asm2:
    <+0>:   push   ebp
    <+1>:   mov    ebp,esp
    <+3>:   sub    esp,0x10
    <+6>:   mov    eax,DWORD PTR [ebp+0xc]
    <+9>:   mov    DWORD PTR [ebp-0x4],eax
    <+12>:  mov    eax,DWORD PTR [ebp+0x8]
    <+15>:  mov    DWORD PTR [ebp-0x8],eax
    <+18>:  jmp    0x50c <asm2+31>
    <+20>:  add    DWORD PTR [ebp-0x4],0x1
    <+24>:  add    DWORD PTR [ebp-0x8],0xcc
    <+31>:  cmp    DWORD PTR [ebp-0x8],0x3937
    <+38>:  jle    0x501 <asm2+20>
    <+40>:  mov    eax,DWORD PTR [ebp-0x4]
    <+43>:  leave  
    <+44>:  ret    

From what I know, this runs a loop that checks if the second parameter is equal to 0x3937 (14647). If it's less than, then it adds 204 to the second parameter and adds 1 to the first parameter. I wrote a C program that does this, which is below, however when I take either of the parameters, convert them to hex, then submit it, it says it's wrong.

#include <stdio.h>

int main() {

  int i = 0;
  int a = 7;
  int b = 24;

  while(b < 14647) {
    a += 1;
    b += 204;
  }

  printf("%d %d", a, b);

  return 0;
}

Solution

  • asm2 does not print anything, it just writes the final value of b (in the program below) into eax and stops, which means that it returns b:

    int asm2(int a1, int b1) 
    {
      int a; //DWORD PTR [ebp-0x8]
      int b; //DWORD PTR [ebp-0x4]
    
      a = a1; // (a = b1 if arguments are pushed from left to right)
      b = b1; // (b = a1 if arguments are pushed from left to right)
    
      while(a <= 14647) {
        b += 1;
        a += 204;
      }
    
      return b;
    }  
    

    So if you invoke asm2(0x7, 0x18) and
    -if arguments are pushed from right to left, it returns 96
    -if arguments are pushed from left to right, it returns 79