Analysis of the bug =================== The `s` command allows the user to change the size of password, but the password buffer is not reallocated if it existed already. This means that the buffer can be overflown by first setting a password, then increasing the size, and finally by setting a new, larger password. Attack plan =========== The `c` command only allows alphanumeric characters, but the `p` command allows any character. The idea is then to exploit the overflow to overwrite the `last_file` buffer with a shell-injection payload (e.g., `x;sh`). Attack implementation ===================== The attack can be implemented by hand in a single `nc` session. First, we set the password a first time, to trigger the alllocation of the `pwd` buffer: ``` sh p1234567812345678 ``` Then we use the `c` command to trigger the allocation of `last_file`. The new chunk will be adjacent to the `pwd` one: ``` sh cbanner ``` Now we can increase the size of the password and set the password again. The new password must fill the the `pwd` chunk and then overwite the header of the next chunk and finally the `banner` string with our payload. Either by counting, or by using the debugger, we can see that the `banner` string starts 32 bytes after the start of password. Note that we have to completely overwrite the `banner` string, otherwise part of the string will end up into our payload, mangling the command that we want to execute. Therefore we need a size of 32+6 (where 6 is length of `banner`): ``` sh s8 p12345678123456781234567812345678xxx;sh ``` finally, we can use the `r` command to trigger the execution of ``` sh cat xxx;sh ``` Note that if we don't pass an argument to `cat`, it will start reading stdin until it sees an EOF. In this case, however, `cat`'s stdin is a TCP/IP socket connected to our `nc` process, and the only way to trigger an EOF is to close our side of the connection. Of course, if we just want to see the contents of a file (e.g., a flag), we can reuse the exising `cat` an just overwrite `last_file` with the path we need. Suggested fix ============= When the `s` command changes the size of the password, the `pwd` buffer should be reallocated (e.g., with `realloc()`). As a general security measure, privileged programs and servers should avoid using `system()`. In this particular case, even invoking `ls` and `cat` is unnecessary and should be replaced by the relevant system calls.