However, I found an excellent example of how to do this in a much better way while working on the Insomnihack CTF Teaser.
This code spawns a new process for each connection, like apache, and it's really simple! This particular service builds a bash command and executes it, so students can exploit a C program with a buffer overflow in it.
It builds a couple of filenames from the incoming IP address and port so they are unique.
Now many students can use my server at once :)
If you want to exploit a simple code injection vulnerability, execute this command:
nc attack32.samsclass.info 1055
#!/usr/bin/env python
import SocketServer as ss
import struct, os
class Handler(ss.StreamRequestHandler):
def handle(self):
put = self.wfile.write
put('Welcome to the Command Injection Lab!\nWhat is your name?')
nm = self.rfile.readline().strip()
rip = self.client_address[0]
rport = self.client_address[1]
tempfile = "/tmp/p1x-1055-" + rip + str(rport)
tempfile2 = tempfile + "out"
with open(tempfile, "w") as f:
f.write(nm)
f.close()
cmd = "cat " + tempfile + "| /usr/bin/p1x > " + tempfile2
os.system(cmd)
with open(tempfile2, "r") as f:
for line in f:
put(line)
class ReusableTCPServer(ss.ForkingMixIn, ss.TCPServer):
allow_reuse_address = True
if __name__ == '__main__':
HOST, PORT = ('0.0.0.0', 1055)
ss.TCPServer.allow_reuse_address = True
server = ReusableTCPServer((HOST, PORT), Handler)
server.serve_forever()