Introduction
Quick post discussing the operational security considerations of the PowerShell Add-Type utility.
MSDN: “If you specify source code, Add-Type compiles the specified source code and generates an in-memory assembly that contains the new .NET Core types.”
Lets explore that!
In Memory?
Source code passed to Add-Type is saved to a temporary file “$env:USERPROFILE\AppData\Local\Temp\[random 8 characters].cmdline”, so much for in-memory.
The following image shows C# source code that has been added to the current PowerShell session via Add-Type.
Note: The “add-type.ps1” file is piped to the Out-String utility because Invoke-Expression expects a string as input.
When Add-Type is invoked, PowerShell calls the Win32 API CreateProcessW function to invoke both csc.exe and cvtres.exe.
The csc.exe process was created with the following lpCommandLineArgument:
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /noconfig /fullpaths @"C:\Users\rust\AppData\Local\Temp\0yv2gp2j.cmdline"
That temporary file will be scanned by Defender.
CSC
For fun lets see how csc.exe loads source code?
Opens the temporary file with CreateFileW and returns a HANDLE.
Get the file size with GetFileSize.
Allocate a block of memory on the heap with HeapAlloc. It allocates the file size + 1 byte.
Read the contents from the file HANDLE (returned from CreateFileW) into the newly allocated heap with ReadFile.
hmmmmmm interesting…
Conclusion
Rewrite your PowerShell to not rely on Add-Type.