While trying to compile Windows exploits from the Exploit Database (exploit-db.com) I quite often faced an error similar to the following:
2789.obj : error LNK2019: unresolved external symbol _closesocket@4 referenced in function _main
The message already clearly says what is going wrong: There is a missing external dependency. Most likely we simply need to link one or more external libraries. The big question is how to do that efficiently?
In this post I will show you how to fix these errors on the example of Exploit DB exploit #2789: Microsoft Windows – NetpManageIPCConnect Stack Overflow Exploit (MS06-070).
After downloading the exploit’s source and fixing all the syntax errors CL.exe is still unable to compile the exploit: (Hint: Don’t forget to use the Developer Command Prompt!)
As I already said, we are missing an external library. Therefore we have to identify which one we need and then we have to tell CL.exe to link it. The easiest way to find the right library is to search for the MSDN function description of the first missing symbol. Quite on the bottom of the MSDN page you then find a section called “Requirements”. Within this section the parent library is listed:
So we already solved the first problem: We now know that closesocket is provided by Winsock2 (Ws_32.lib). To finally link Ws_32.lib we simply have to add the following #pragma comment preprocessor directive within the exploit’s source code:
#pragma comment(lib, "Ws2_32.lib")
Although it should not matter where in the code it is placed, for readability reasons I really recommend to add it at the top of the file. After that the modified exploit can be successfully compiled:
Some exploits also need to be linked to more than one library so you may have to repeat the explained process several times. Based on my experience the two most linked libraries within Windows exploits are Winsock2 (Ws2_32.lib) and the Windows User component (user32.lib). A good trick – although for sure not any kind of best practise – is to always add those two after encountering an unresolved external symbol without any further thought. It already saved me quite some time.