Level 5 Username : narnia5 Password : faimahchiy SSH : narnia.labs.overthewire.org:2226
To solve this level, we first ssh into the narnia server using the credentials provided above. Let’s have a look at the executable for this level and its source code.
As we can see above, the executable sets the value of a variable i to 1. There is a clause within the code that lets us access the shell if the value for i has been changed to 500. The exdcutable copies the value from the argument to the variable buffer by using the sprintf function with size bounds. Therefore, we cannot overflow it to change the value of i to 500. We need to find another way.
After spending a considerable amount of time working on this, I learned that some functions are vulnerable to Format String Vulnerability and sprintf function is one of them. I followed the following documents and I hope they help you too. Link 1, Link 2.
Let’s see what’s on the stack and learn more about this vulnerability.
As we can see above, the executable is vulnerable to Format String Vulnerability and we can see the stack contents. Let’s verify this in gdb to gain a better understanding.
As we can see, the executable is indeed printing the stack contents. Let’s follow the documents above and try to insert our value in the address of variable i.
As we can see, the executable prints our argument ‘ABCD’ on the fifth iteration of %08x. Instead of using the %08x format specifier the fifth time, I decided to use the %n format specifier and pass the address of variable i to it. By using the %n format specifier, we can see that the value at the address that we have passed changes to 40. A %n specifier is used as a reference to the number of bytes written so far. Let’s dissect why the application printed 40 in this case. As we can see, we have 4 bytes of the address in little-endian form, 8 bytes of %x specifier printed 4 times consuming 32 bytes and 1 byte of . symbol printed 4 times totaling 4 bytes. 32+4+4=40 and that is the reason why the number was overwritten to 40 at variable i. Let’s now use the %u specifier to increase the width of the output thus tricking the %n specifier. The number we are writing — the count of characters written by the format function — is dependent on the format string. Since we control the format string, we can at least take influence on this counter, by writing more or less bytes. By using a dummy parameter ‘%nu’ we are able to control the counter written by ‘%n’, at least a bit. As we already have 40 bytes using our previous shellcode. Let’s increase it to change the value of i to 500.
As we can see above, after changing the width of the shellcode, the value of i is changed to 500.
Level 6 Username : narnia6 Password : neezocaeng SSH : narnia.labs.overthewire.org:2226