I can understand what a buffer overflow is and that it allows you to write in places of the memory that you shouldn't be able to. I can also grasp the concept that there may be other software vulnerabilities out there that work in some different way that allow you to place things you want in memory. I've also gained access to some old XP machines of mine using metasploit, which was fun.
But I cannot trully understand how you can get access to the remote system by having (for example) the buffer overflow vulnerability in mind.
There are some points that are not clear for me:
- Does the program that has the vulnerability need to run and to listen to a specific port on the victim machine (like a mini-server or something)? Can a program that is badly written be exploited remotely if it doesn't listen to a port?
- I assume that the program will read some input from that port and then write it to memory in some variable and maybe process it. Giving the program more data than it should read, and providing that it has the vulnerability, it is going to write to a location into the memory (specifically, exactly after the variable) whatever we want. How doesn't this crash the program 99.9% of the time? What if exactly after the place in memory where this variable is stored there is a pointer to some function that fails to execute and the program crashes?
- Providing that the program does not crash, how can we execute the code that we have injected into the memory? Do we need to place the code we want in a place inside the memory that we know it's going to be executed? How can some random part of the memory be executed? Almost never in my programs I execute some variable of mine, unless I want to run some other program, which is very rare and it shouldn't be the same as directly executing code from memory (which reminds me of eval()).
- Providing that point 2 assumes correctly that the vulnerability usually arises when the vulnerable program reads malicious input from a port and that this code is executed, how is the executed code able to get back to me, the attacker? Do I send in the malicious code my IP address in a variable or something?
- Programs generally cannot read or write in another program's memory. Does this mean that when the vulnerable program closes I will lost the connection to the open remote shell? Or does it spawn an independent subprocess once it executes and I am actually connected to it?
Can anyone give me a simple but yet realistic and thorough example of how the whole system works, from the program listening to some port till the attacker gaining a shell?