Add-Type Compilation
As we discussed previously,
the Add-Type keyword lets us use the .NET framework to compile C# code
containing Win32 API declarations and then call them.
This compilation process is performed by the Visual C# Command-Line Compiler or csc
During this process, both the C# source code
and the compiled C# assembly are temporarily written to disk.
Let’s demonstrate this with our prior PowerShell MessageBox example.
We’ll use Process Monitor from SysInternals to monitor file writes.
To start monitoring file writes, we must first open Process Monitor
and navigate to Filter > Filter.
In the new dialog window, we can create filter rules.
We’ll create a filter for the powershell ise process.
and Add and Apply the filter.
Next, we’ll open the 32-bit version of PowerShell ISE
and clear any old events in processmon by pressing ctrl x.
before running the code to launch the MessageBox
Let’s review the results.
After executing the PowerShell code, Process Monitor lists many events
including CreateFile, WriteFile, and CloseFile operations.
These API calls are used for file operations,
and the file names used in the operations,
such as these .cs and .dll files, are especially interesting.
While the filename itself is randomly generated,
the file extension suggest that both the C# code,
and the compiled code have been written to the hard drive.
If our suspicion is correct,
then the .dll assembly should be loaded into the PowerShell ISE process.
We can list loaded assemblies using the GetAssemblies method
on the CurrentDomain object.
This method is invoked through the static AppDomain class.
We improve the readbility of the output by piping it into the Sort-Object cmdlet,
which sort it by name as supplied with the -Property option.
Finally, we pipe the result of the sort into the Format-Table cmdlet
to list the ouptut as a table.
Based on the list of loaded assemblies,
the dll file is indeed loaded into the process.
Our investigation reveals that PowerShell writes a .cs C# source code file
to the hard drive, which is compiled into assembly and then loaded into the process.
The Add-Type code will likely be flagged by endpoint antivirus,
which will halt our attack.
We’ll need to rebuild our PowerShell shellcode runner to avoid this.