-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
401 lines (282 loc) · 16.1 KB
/
Program.cs
File metadata and controls
401 lines (282 loc) · 16.1 KB
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using Microsoft.Win32;
using System.Security.Principal;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.IO;
namespace DetectiveService {
internal static class Program {
// where windows keeps service definitions
private static readonly string REG_PATH = @"SYSTEM\CurrentControlSet\Services";
private static readonly Regex LuidSuffixRegex = new Regex(@"^(?<base>.+?)_[0-9a-fA-F]{3,}$", RegexOptions.Compiled);
private static void Main(string[] args) {
// we need elevated privs to enumerate properly
if (!IsElevated()) {
Console.WriteLine("[-] This tool must be run from an elevated console.");
Environment.Exit(1);
}
// scanning and filetering out noise. basically we compare what blue teamer would see using sc query with what we have in the registry
Console.WriteLine("[*] Scanning registry for per-user *template* services (Type = 0x50 / 0x60)");
HashSet<string> perUserTemplates = GetPerUserTemplateNames();
Console.WriteLine($" → {perUserTemplates.Count} per-user templates detected");
Console.WriteLine("[*] Grabbing services via sc.. (sc.exe query type= service state= all) …");
HashSet<string> scm = GetScQueryWin32ServiceNames(perUserTemplates);
Console.WriteLine($" → {scm.Count} entries visible via sc.exe");
Console.WriteLine("[*] Grabbing Win32 service blobs straight from the registry (filtering out drivers and per-user templates)");
HashSet<string> reg = GetRegistryEntriesSkippingDriversAndUserTemplates();
Console.WriteLine($" → {reg.Count} sub-keys considered");
var hidden = reg.Except(scm, StringComparer.OrdinalIgnoreCase).ToList();
Console.WriteLine();
Console.WriteLine("====== POSSIBLE HIDDEN SERVICES ======");
if (hidden.Count == 0) {
Console.WriteLine("[+] No shady stuff detected! :)");
return;
}
foreach (string svc in hidden.OrderBy(s => s, StringComparer.OrdinalIgnoreCase)) {
Console.WriteLine($"[!] You should investigate {svc}");
PrintServicePathInfo(svc);
// these are standart service permissions, so if you run this service should be visible with sc query, sc qc commands and etc. You should also be able to stop the service now
Console.WriteLine("[*] To unhide this service try running:");
Console.WriteLine($"[*] sc sdset {svc} D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)" +
"(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)" +
"(A;;CCLCSWLOCRRC;;;IU)" +
"(A;;CCLCSWLOCRRC;;;SU)" +
"S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)");
Console.WriteLine();
}
}
private static bool IsElevated() {
using (WindowsIdentity id = WindowsIdentity.GetCurrent()) {
WindowsPrincipal principal = new WindowsPrincipal(id);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
}
private static HashSet<string> GetScmEntries() {
var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (ServiceController sc in ServiceController.GetServices())
set.Add(sc.ServiceName);
return set;
}
private static HashSet<string> GetScQueryWin32ServiceNames(HashSet<string> perUserTemplates) {
var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
try {
var psi = new ProcessStartInfo { FileName = "sc.exe", Arguments = "query type= service state= all", UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true };
using (Process p = Process.Start(psi)) {
if (p == null)
throw new InvalidOperationException("Failed to start sc.exe");
string output = p.StandardOutput.ReadToEnd();
string error = p.StandardError.ReadToEnd();
p.WaitForExit();
foreach (Match m in Regex.Matches(output, @"SERVICE_NAME:\s+([^\r\n]+)")) {
string name = m.Groups[1].Value.Trim();
if (!string.IsNullOrWhiteSpace(name))
set.Add(name);
}
if (set.Count == 0 && !string.IsNullOrWhiteSpace(error))
Console.WriteLine($"[!] sc.exe returned no services, stderr:\n{error}");
}
}
catch (Exception ex) {
Console.WriteLine($"[!] Failed to enumerate with sc.exe (falling back to ServiceController): {ex.Message}");
set = GetScmEntries();
}
var toAdd = new List<string>();
foreach (string name in set) {
Match m = LuidSuffixRegex.Match(name);
if (m.Success) {
string baseName = m.Groups["base"].Value;
if (perUserTemplates.Contains(baseName))
toAdd.Add(baseName);
}
}
foreach (string baseName in toAdd)
set.Add(baseName);
return set;
}
private static HashSet<string> GetPerUserTemplateNames() {
var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
using (RegistryKey root = Registry.LocalMachine.OpenSubKey(REG_PATH, false)) {
if (root == null) return set;
foreach (string sub in root.GetSubKeyNames()) {
using (RegistryKey k = root.OpenSubKey(sub, false)) {
if (k == null) continue;
object typeObj = k.GetValue("Type");
if (!(typeObj is int typeVal)) continue;
const int SERVICE_USER_OWN_PROCESS = 0x00000050;
const int SERVICE_USER_SHARE_PROCESS = 0x00000060;
if (typeVal == SERVICE_USER_OWN_PROCESS || typeVal == SERVICE_USER_SHARE_PROCESS)
set.Add(sub);
}
}
}
return set;
}
private static HashSet<string> GetRegistryEntriesSkippingDriversAndUserTemplates() {
var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
using (RegistryKey root = Registry.LocalMachine.OpenSubKey(REG_PATH, false)) {
if (root == null) return set;
foreach (string sub in root.GetSubKeyNames()) {
using (RegistryKey k = root.OpenSubKey(sub, false)) {
if (k == null) continue;
object typeObj = k.GetValue("Type");
if (!(typeObj is int typeVal)) continue;
const int SERVICE_KERNEL_DRIVER = 0x00000001;
const int SERVICE_FILE_SYSTEM_DRIVER = 0x00000002;
const int SERVICE_WIN32_OWN_PROCESS = 0x00000010;
const int SERVICE_WIN32_SHARE_PROCESS = 0x00000020;
const int SERVICE_USER_OWN_PROCESS = 0x00000050;
const int SERVICE_USER_SHARE_PROCESS = 0x00000060;
bool isDriver = (typeVal & (SERVICE_KERNEL_DRIVER | SERVICE_FILE_SYSTEM_DRIVER)) != 0;
if (isDriver) continue;
bool isWin32Like = (typeVal & (SERVICE_WIN32_OWN_PROCESS | SERVICE_WIN32_SHARE_PROCESS)) != 0;
if (!isWin32Like) continue;
if (typeVal == SERVICE_USER_OWN_PROCESS || typeVal == SERVICE_USER_SHARE_PROCESS)
continue;
object imagePath = k.GetValue("ImagePath");
object serviceDll = null;
using (RegistryKey parameters = k.OpenSubKey("Parameters", false)) {
if (parameters != null)
serviceDll = parameters.GetValue("ServiceDll");
}
if (imagePath == null && serviceDll == null)
continue;
if (k.GetValue("DeleteFlag") != null)
continue;
set.Add(sub);
}
}
}
return set;
}
private static void PrintServicePathInfo(string serviceName) {
using (RegistryKey root = Registry.LocalMachine.OpenSubKey(REG_PATH, false)) {
if (root == null) {
Console.WriteLine(" [paths] (registry not accessible)");
return;
}
using (RegistryKey k = root.OpenSubKey(serviceName, false)) {
if (k == null) {
Console.WriteLine(" [paths] (service key not found)");
return;
}
object imagePathObj = null;
object serviceDllObj = null;
try {
imagePathObj = k.GetValue("ImagePath", null, RegistryValueOptions.DoNotExpandEnvironmentNames);
}
catch {
imagePathObj = k.GetValue("ImagePath");
}
using (RegistryKey parameters = k.OpenSubKey("Parameters", false)) {
if (parameters != null) {
try {
serviceDllObj = parameters.GetValue("ServiceDll", null, RegistryValueOptions.DoNotExpandEnvironmentNames);
}
catch {
serviceDllObj = parameters.GetValue("ServiceDll");
}
}
}
string imagePathExpanded = NormalizeAndExpandCommandLine(imagePathObj?.ToString());
string serviceDllExpanded = NormalizeAndExpandPath(serviceDllObj?.ToString());
string executableFromImagePath = ExtractExecutableFromCommandLine(imagePathExpanded);
bool exeExists = !string.IsNullOrWhiteSpace(executableFromImagePath) && File.Exists(executableFromImagePath);
bool dllExists = !string.IsNullOrWhiteSpace(serviceDllExpanded) && File.Exists(serviceDllExpanded);
if (!string.IsNullOrWhiteSpace(executableFromImagePath))
Console.WriteLine(" [bin] " + executableFromImagePath + (exeExists ? " [exists]" : " [missing]"));
if (!string.IsNullOrWhiteSpace(imagePathExpanded) && HasArgs(imagePathExpanded))
Console.WriteLine(" [cmd] " + imagePathExpanded);
if (!string.IsNullOrWhiteSpace(serviceDllExpanded))
Console.WriteLine(" [dll] " + serviceDllExpanded + (dllExists ? " [exists]" : " [missing]"));
}
}
}
private static string NormalizeAndExpandPath(string path) {
if (string.IsNullOrWhiteSpace(path))
return null;
string s = path.Trim();
try { s = Environment.ExpandEnvironmentVariables(s); } catch { }
if (s.StartsWith(@"\\?\", StringComparison.OrdinalIgnoreCase))
s = s.Substring(4);
if (s.StartsWith(@"\??\", StringComparison.OrdinalIgnoreCase))
s = s.Substring(4);
string sysRoot = Environment.GetEnvironmentVariable("SystemRoot");
if (!string.IsNullOrEmpty(sysRoot)) {
if (s.StartsWith(@"\SystemRoot\", StringComparison.OrdinalIgnoreCase))
s = Path.Combine(sysRoot, s.Substring(@"\SystemRoot\".Length));
else if (s.StartsWith(@"SystemRoot\", StringComparison.OrdinalIgnoreCase))
s = Path.Combine(sysRoot, s.Substring(@"SystemRoot\".Length));
}
if (s.Length >= 2 && s.StartsWith("\"") && s.EndsWith("\"") && s.Count(c => c == '"') == 2)
s = s.Substring(1, s.Length - 2);
string sysDir = Environment.SystemDirectory;
if (!string.IsNullOrEmpty(sysDir)) {
if (s.StartsWith(@"system32\", StringComparison.OrdinalIgnoreCase) || s.StartsWith(@"System32\", StringComparison.OrdinalIgnoreCase)) {
s = Path.Combine(sysDir, s.Substring("system32\\".Length));
}
}
return s;
}
private static string NormalizeAndExpandCommandLine(string commandLine) {
if (string.IsNullOrWhiteSpace(commandLine))
return null;
string s = commandLine.Trim();
try { s = Environment.ExpandEnvironmentVariables(s); } catch { }
if (s.StartsWith(@"\\?\", StringComparison.OrdinalIgnoreCase))
s = s.Substring(4);
if (s.StartsWith(@"\??\", StringComparison.OrdinalIgnoreCase))
s = s.Substring(4);
string sysRoot = Environment.GetEnvironmentVariable("SystemRoot");
if (!string.IsNullOrEmpty(sysRoot)) {
if (s.StartsWith(@"\SystemRoot\", StringComparison.OrdinalIgnoreCase))
s = Path.Combine(sysRoot, s.Substring(@"\SystemRoot\".Length));
else if (s.StartsWith(@"SystemRoot\", StringComparison.OrdinalIgnoreCase))
s = Path.Combine(sysRoot, s.Substring(@"SystemRoot\".Length));
}
string sysDir = Environment.SystemDirectory;
if (!string.IsNullOrEmpty(sysDir)) {
if (s.StartsWith(@"system32\", StringComparison.OrdinalIgnoreCase) || s.StartsWith(@"System32\", StringComparison.OrdinalIgnoreCase)) {
s = Path.Combine(sysDir, s.Substring("system32\\".Length));
}
}
return s;
}
private static string ExtractExecutableFromCommandLine(string commandLine) {
if (string.IsNullOrWhiteSpace(commandLine))
return null;
string cl = commandLine.Trim();
if (cl.StartsWith("\"")) {
int endQuote = cl.IndexOf('"', 1);
if (endQuote > 1)
return cl.Substring(1, endQuote - 1);
}
int spaceIdx = cl.IndexOfAny(new[] { ' ', '\t' });
if (spaceIdx > 0)
return cl.Substring(0, spaceIdx);
return cl;
}
private static bool HasArgs(string commandLine) {
if (string.IsNullOrWhiteSpace(commandLine))
return false;
string cl = commandLine.Trim();
if (cl.StartsWith("\"")) {
int endQuote = cl.IndexOf('"', 1);
if (endQuote > 1) {
if (cl.Length > endQuote + 1)
return !string.IsNullOrWhiteSpace(cl.Substring(endQuote + 1));
return false;
}
return false;
}
else {
int spaceIdx = cl.IndexOfAny(new[] { ' ', '\t' });
if (spaceIdx > 0)
return cl.Length > spaceIdx + 1 && !string.IsNullOrWhiteSpace(cl.Substring(spaceIdx + 1));
return false;
}
}
}
}