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
|
// Copyright (c) .NET Foundation and contributors. All rights reserved. Licensed under the Microsoft Reciprocal License. See LICENSE.TXT file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management;
using System.Text;
using Microsoft.Win32;
namespace TestExe
{
public abstract class Task
{
public string data;
public Task(string Data)
{
data = Data;
}
public abstract void RunTask();
}
public class ExitCodeTask : Task
{
public ExitCodeTask(string Data) : base(Data) { }
public override void RunTask()
{
// this task does nothing. Just stores data about what exit code to return.
}
}
public class SleepTask : Task
{
public SleepTask(string Data) : base(Data) { }
public override void RunTask()
{
int milliseconds = int.Parse(this.data);
Console.WriteLine("Starting to sleep for {0} milliseconds", milliseconds);
System.Threading.Thread.Sleep(milliseconds);
}
}
public class SleepRandomTask : Task
{
public SleepRandomTask(string Data) : base(Data) { }
public override void RunTask()
{
int low = int.Parse(data.Split(new string[] { ":" }, 2, StringSplitOptions.None)[0]);
int high = int.Parse(data.Split(new string[] { ":" }, 2, StringSplitOptions.None)[1]);
Random r = new Random();
int milliseconds = r.Next(high - low) + low;
Console.WriteLine("Starting to sleep for {0} milliseconds", milliseconds);
System.Threading.Thread.Sleep(milliseconds);
}
}
public class LogTask : Task
{
string[] argsUsed;
public LogTask(string Data, string[] args)
: base(Data)
{
argsUsed = args;
}
public override void RunTask()
{
string logFile = "";
string argsUsedString = "";
foreach (string a in argsUsed)
{
argsUsedString += a + " ";
}
try
{
logFile = System.Environment.ExpandEnvironmentVariables(data);
Console.WriteLine("creating log file: " + logFile);
StreamWriter textFile = File.CreateText(logFile);
textFile.WriteLine("This is a log file created by TestExe.exe");
textFile.WriteLine("Args used: " + argsUsedString);
textFile.Close();
}
catch
{
Console.WriteLine("creating a log file failed for: {0}", logFile);
}
}
}
public class ProcessInfoTask : Task
{
public ProcessInfoTask(string Data) : base(Data) { }
public override void RunTask()
{
try
{
string processInfoXml = "";
// Get information about the process and who is running it
Process thisProc = Process.GetCurrentProcess();
string username = thisProc.StartInfo.EnvironmentVariables["username"].ToString();
int parentProcId = GetParentProcess(thisProc.Id);
Process parentProc = Process.GetProcessById(parentProcId);
string parentUsername = parentProc.StartInfo.EnvironmentVariables["username"].ToString();
int grandparentProcId = GetParentProcess(parentProc.Id);
Process grandparentProc = Process.GetProcessById(grandparentProcId);
string grandparentUsername = grandparentProc.StartInfo.EnvironmentVariables["username"].ToString();
processInfoXml += "<ProcessInfo>";
processInfoXml += " <ProcessName>" + thisProc.ProcessName + "</ProcessName>";
processInfoXml += " <Id>" + thisProc.Id.ToString() + "</Id>";
processInfoXml += " <SessionId>" + thisProc.SessionId.ToString() + "</SessionId>";
processInfoXml += " <MachineName>" + thisProc.MachineName + "</MachineName>";
// this stuff isn't set since we didn't start the process and tell it what to use. So don't bother
//processInfoXml += " <StartInfo>";
//processInfoXml += " <FileName>" + thisProc.StartInfo.FileName + "</FileName>";
//processInfoXml += " <UserName>" + thisProc.StartInfo.UserName + "</UserName>";
//processInfoXml += " <WorkingDirectory>" + thisProc.StartInfo.WorkingDirectory + "</WorkingDirectory>";
//processInfoXml += " <Arguments>" + thisProc.StartInfo.Arguments + "</Arguments>";
//processInfoXml += " </StartInfo>";
processInfoXml += " <StartTime>" + thisProc.StartTime.ToString() + "</StartTime>";
processInfoXml += " <Username>" + username + "</Username>";
processInfoXml += " <ParentProcess>";
processInfoXml += " <ProcessName>" + parentProc.ProcessName + "</ProcessName>";
processInfoXml += " <Id>" + parentProc.Id.ToString() + "</Id>";
processInfoXml += " <StartTime>" + parentProc.StartTime.ToString() + "</StartTime>";
processInfoXml += " <Username>" + parentUsername + "</Username>";
processInfoXml += " </ParentProcess>";
processInfoXml += " <GrandparentProcess>";
processInfoXml += " <ProcessName>" + grandparentProc.ProcessName + "</ProcessName>";
processInfoXml += " <Id>" + grandparentProc.Id.ToString() + "</Id>";
processInfoXml += " <StartTime>" + grandparentProc.StartTime.ToString() + "</StartTime>";
processInfoXml += " <Username>" + grandparentUsername + "</Username>";
processInfoXml += " </GrandparentProcess>";
processInfoXml += "</ProcessInfo>";
string logFile = System.Environment.ExpandEnvironmentVariables(data);
Console.WriteLine("Creating Process Info data file: " + logFile);
StreamWriter textFile = File.CreateText(logFile);
textFile.WriteLine(processInfoXml);
textFile.Close();
}
catch (Exception eX)
{
Console.WriteLine("Creating Process Info data file failed");
Console.WriteLine(eX.Message);
}
}
private static int GetParentProcess(int Id)
{
int parentPid = 0;
using (ManagementObject mo = new ManagementObject("win32_process.handle='" + Id.ToString() + "'"))
{
mo.Get();
parentPid = Convert.ToInt32(mo["ParentProcessId"]);
}
return parentPid;
}
}
public class FileExistsTask : Task
{
public FileExistsTask(string Data) : base(Data) { }
public override void RunTask()
{
string fileToExist = System.Environment.ExpandEnvironmentVariables(data);
if (!String.IsNullOrEmpty(fileToExist))
{
Console.WriteLine("Waiting for this file to exist: \"" + fileToExist + "\"");
while (!System.IO.File.Exists(fileToExist))
{
System.Threading.Thread.Sleep(250);
}
Console.WriteLine("Found: \"" + fileToExist + "\"");
}
}
}
/// <summary>
/// Task class that will create a registry key and write a name and value in it
/// </summary>
public class RegistryWriterTask : Task
{
private string hive;
private string keyPath;
private string[] keyPathArray;
private string name;
private RegistryValueKind regValueKind;
private object value;
public RegistryWriterTask(string Data) : base(Data) { }
public override void RunTask()
{
if (parseRegKeyNameTypeValue(System.Environment.ExpandEnvironmentVariables(data)))
{
RegistryKey rk = Registry.LocalMachine;
if (hive == "HKCU") rk = Microsoft.Win32.Registry.CurrentUser;
if (hive == "HKCC") rk = Microsoft.Win32.Registry.CurrentConfig;
if (hive == "HKLM") rk = Microsoft.Win32.Registry.LocalMachine;
foreach (string key in keyPathArray)
{
rk = rk.CreateSubKey(key, RegistryKeyPermissionCheck.ReadWriteSubTree);
}
rk.SetValue(name, value, regValueKind);
Console.WriteLine("Created registry key: '{0}' name: '{1}' value: '{2}' of type: '{3}'",
hive + "\\" + keyPath,
name,
value.ToString(),
regValueKind.ToString());
}
else
{
Console.WriteLine("Unable to write registry key.");
}
}
private bool parseRegKeyNameTypeValue(string delimittedData)
{
string[] splitString = delimittedData.Split(new string[] { "," }, StringSplitOptions.None);
if (splitString.Length != 4)
{
Console.WriteLine("Invalid regkey. Unable to parse key,name,type,value from: \"" + delimittedData + "\"");
return false;
}
else
{
keyPath = splitString[0];
name = splitString[1];
string datatype = splitString[2];
if (datatype == "DWord")
{
value = UInt32.Parse(splitString[3]);
}
else if (datatype == "QWord")
{
value = UInt64.Parse(splitString[3]);
}
else
{
value = splitString[3];
}
if (keyPath.ToUpper().StartsWith("HKLM\\"))
{
hive = "HKLM";
keyPath = keyPath.Replace("HKLM\\", "");
}
else if (keyPath.ToUpper().StartsWith("HKCC\\"))
{
hive = "HKCC";
keyPath = keyPath.Replace("HKCC\\", "");
}
else if (keyPath.ToUpper().StartsWith("HKCU\\"))
{
hive = "HKCU";
keyPath = keyPath.Replace("HKCU\\", "");
}
else
{
Console.WriteLine("Invalid regkey. Unable to determin hive. regkey must start with either: [HKLM], [HKCU], or [HKCC]");
return false;
}
keyPathArray = keyPath.Split(new string[] { "\\" }, StringSplitOptions.None);
try
{
regValueKind = (RegistryValueKind)System.Enum.Parse(typeof(RegistryValueKind), datatype);
}
catch (Exception ex)
{
Console.WriteLine("Invalid datatype. It must be: String, DWord, or QWord (case sensitive)");
Console.WriteLine(ex.Message);
return false;
}
}
return true;
}
}
/// <summary>
/// Task class that will delete a registry key value or registry key and all of its children
/// </summary>
public class RegistryDeleterTask : Task
{
private string hive;
private string keyPath;
private string[] keyPathArray;
private string name;
public RegistryDeleterTask(string Data) : base(Data) { }
public override void RunTask()
{
if (parseRegKeyName(System.Environment.ExpandEnvironmentVariables(data)))
{
try
{
RegistryKey rk = Registry.LocalMachine;
if (hive == "HKCU") rk = Microsoft.Win32.Registry.CurrentUser;
if (hive == "HKCC") rk = Microsoft.Win32.Registry.CurrentConfig;
if (hive == "HKLM") rk = Microsoft.Win32.Registry.LocalMachine;
RegistryKey rkParent = null;
foreach (string key in keyPathArray)
{
rkParent = rk;
rk = rk.OpenSubKey(key, true);
}
if (String.IsNullOrEmpty(name))
{
// delete the key and all of its children
string subkeyToDelete = keyPathArray[keyPathArray.Length - 1];
rkParent.DeleteSubKeyTree(subkeyToDelete);
Console.WriteLine("Deleted registry key: '{0}'", hive + "\\" + keyPath);
}
else
{
// just delete this value
rk.DeleteValue(name);
Console.WriteLine("Deleted registry key: '{0}' name: '{1}'", hive + "\\" + keyPath, name);
}
}
catch (Exception ex)
{
Console.WriteLine("Unable to delete registry key: '{0}'", hive + "\\" + keyPath);
Console.WriteLine(ex.Message);
}
}
else
{
Console.WriteLine("Unable to delete registry key.");
}
}
private bool parseRegKeyName(string delimittedData)
{
string[] splitString = delimittedData.Split(new string[] { "," }, StringSplitOptions.None);
if (splitString.Length > 2)
{
Console.WriteLine("Unable to parse registry key and name.");
return false;
}
keyPath = splitString[0];
if (splitString.Length == 2)
{
name = splitString[1];
}
if (keyPath.ToUpper().StartsWith("HKLM\\"))
{
hive = "HKLM";
keyPath = keyPath.Replace("HKLM\\", "");
}
else if (keyPath.ToUpper().StartsWith("HKCC\\"))
{
hive = "HKCC";
keyPath = keyPath.Replace("HKCC\\", "");
}
else if (keyPath.ToUpper().StartsWith("HKCU\\"))
{
hive = "HKCU";
keyPath = keyPath.Replace("HKCU\\", "");
}
else
{
Console.WriteLine("Invalid regkey. Unable to determine hive. regkey must start with either: [HKLM], [HKCU], or [HKCC]");
return false;
}
keyPathArray = keyPath.Split(new string[] { "\\" }, StringSplitOptions.None);
return true;
}
}
public class TaskParser
{
public static List<Task> ParseTasks(string[] args)
{
List<Task> tasks = new List<Task>();
try
{
// for invalid args. return empty list
if (args.Length % 2 == 0)
{
Task t;
for (int i = 0; i < args.Length; i += 2)
{
switch (args[i].ToLower())
{
case "/ec":
t = new ExitCodeTask(args[i + 1]);
tasks.Add(t);
break;
case "/s":
t = new SleepTask(args[i + 1]);
tasks.Add(t);
break;
case "/sr":
t = new SleepRandomTask(args[i + 1]);
tasks.Add(t);
break;
case "/log":
t = new LogTask(args[i + 1], args);
tasks.Add(t);
break;
case "/pinfo":
t = new ProcessInfoTask(args[i + 1]);
tasks.Add(t);
break;
case "/fe":
t = new FileExistsTask(args[i + 1]);
tasks.Add(t);
break;
case "/regw":
t = new RegistryWriterTask(args[i + 1]);
tasks.Add(t);
break;
case "/regd":
t = new RegistryDeleterTask(args[i + 1]);
tasks.Add(t);
break;
default:
Console.WriteLine("Error: Invalid switch specified.");
return new List<Task>();
}
}
}
}
catch
{
Console.WriteLine("Error: Invalid switch data specified. Couldn't parse the data.");
return new List<Task>();
}
return tasks;
}
}
}
|