Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How this obfuscated C line prints "EMIL"? [closed]

Can you explain how does the following code work?

main(O){10<putchar(4^--O?77-(15&5128>>4*O):10)&&main(2+O);}

Output:

EMIL

You can test it on Ideone. I have found this line on unwind's profile.

like image 280
Adam Stelmaszczyk Avatar asked Sep 01 '25 05:09

Adam Stelmaszczyk


1 Answers

Deobfuscation can easily be done in a step-by-step basis.

White-space always helps:

main(O)
{
  10 < putchar(4 ^ --O ? 77 - (15 & 5128 >> 4 * O)
                       : 10)
  && main(2+O);
}

Add a variable:

main(O)
{
  int i = 4 ^ --O ? 77 - (15 & 5128 >> 4 * O)
                  : 10;
  i = putchar(i);
  10 < i && main(2+O);
}

Replace ?: with if-else:

main(O)
{
  int i;
  if (4 ^ --O)
    i = 77 - (15 & 5128 >> 4 * O)
  else
    i = 10;
  i = putchar(i);
  10 < i && main(2 + O);
}

Replace && with if:

main(O)
{
  int i;
  if (4 ^ --O)
    i = 77 - (15 & 5128 >> 4 * O)
  else
    i = 10;
  i = putchar(i);
  if (10 < i)
    main(2 + O);
}

Brackets for clarity:

main(O)
{
  int i;
  if (4 ^ --O)
    i = 77 - (15 & (5128 >> (4 * O)))
  else
    i = 10;
  i = putchar(i);
  if (10 < i)
    main(2 + O);
}

From here it's a simple case of applying basic C knowledge of operators.

Run through the code: (initial parameter of main is 1, we can check this)

main(1)
  4 ^ 0 = 4 = true
    5128 >> 4 * 0 = 5128
    15 & 5128 = 8
    i = 77 - 8 = 69
  putchar(69) -> 'E'
  10 < 69
    call main(2+0)
main(2)
  ...

How whomever wrote it came up with it? Well, to my knowledge, that's mostly a mystery when it comes to obfuscated code.

like image 147
Bernhard Barker Avatar answered Sep 02 '25 21:09

Bernhard Barker