-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathForm1.cs
More file actions
445 lines (400 loc) · 18.7 KB
/
Form1.cs
File metadata and controls
445 lines (400 loc) · 18.7 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
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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Management;
using System.Security.Principal;
using System.IO;
using ProcessPrivileges;
using System.Linq;
using System.Security.AccessControl;
namespace MBST_Lab_1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
const int Process_Query_Information = 0x0400;
const int Process_WM_Read = 0x0010;
//для ASLR
[DllImport("kernel32.dll")]
public static extern bool GetProcessMitigationPolicy(IntPtr hProcess,
Process_Mitigation_Policy mitigationPolicy,
ref Process_Mitigation_DEP_Policy lpBuffer,
int dwLength);
//для DEP
[DllImport("kernel32.dll")]
public static extern bool GetProcessMitigationPolicy(
IntPtr hProcess,
Process_Mitigation_Policy mitigationPolicy,
ref Process_Mitigation_Type_Policy lpBuffer,
int dwLength);
//для 64/32
[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsWow64Process([In] IntPtr process,
[Out] out bool wow64Process);
//64/32
public static bool Is64Bit(Process process)
{
if (!Environment.Is64BitOperatingSystem)
return false;
// if this method is not available in your version of .NET, use GetNativeSystemInfo via P/Invoke instead
bool isWow64;
if (!IsWow64Process(process.Handle, out isWow64))
throw new Win32Exception();
return !isWow64;
}
//integrity level процесса
public static string GetIntegrityLevel(Process process)
{
try
{
IntPtr hProcess = process.Handle;
IntPtr hToken;
if (!OpenProcessToken(hProcess, TokenAccessLevels.MaximumAllowed, out hToken))
return "error";
try
{
uint dwLengthNeeded;
if (GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenIntegrityLevel, IntPtr.Zero, 0, out dwLengthNeeded))
return "error";
uint dwError = (uint)Marshal.GetLastWin32Error();
if (dwError == ERROR_INSUFFICIENT_BUFFER)
{
IntPtr pTIL = Marshal.AllocHGlobal((int)dwLengthNeeded);
try
{
if (!GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenIntegrityLevel, pTIL, dwLengthNeeded, out dwLengthNeeded))
return "error";
//
TOKEN_MANDATORY_LABEL TIL = (TOKEN_MANDATORY_LABEL)Marshal.PtrToStructure(pTIL, typeof(TOKEN_MANDATORY_LABEL));
IntPtr SubAuthorityCount = GetSidSubAuthorityCount(TIL.Label.Sid);
IntPtr IntegrityLevelPtr = GetSidSubAuthority(TIL.Label.Sid, Marshal.ReadByte(SubAuthorityCount) - 1);
//
int dwIntegrityLevel = Marshal.ReadInt32(IntegrityLevelPtr);
if(dwIntegrityLevel < SECURITY_MANDATORY_LOW_RID)
return "untrusted";
else if (dwIntegrityLevel == SECURITY_MANDATORY_LOW_RID)
return "low";
else if (dwIntegrityLevel >= SECURITY_MANDATORY_MEDIUM_RID &&
dwIntegrityLevel < SECURITY_MANDATORY_HIGH_RID)
return "medium";
else if (dwIntegrityLevel >= SECURITY_MANDATORY_HIGH_RID &&
dwIntegrityLevel < SECURITY_MANDATORY_SYSTEM_RID)
return "high";
else if (dwIntegrityLevel >= SECURITY_MANDATORY_SYSTEM_RID)
return "system";
}
finally { Marshal.FreeHGlobal(pTIL); }
}
}
finally { CloseHandle(hToken); }
return "";
}
catch { return "system"; }
}
//получаем
public void GetProcessOwnerDepAslr(List<Proc_class> PROCESS_LIST)
{
string query = "Select * From Win32_Process";// Where ProcessID = " + processId;
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection processList = searcher.Get();
foreach (ManagementObject obj in processList)
{
int returnVal = -1, index = -1;
try
{
string[] argList = new string[] { string.Empty, string.Empty };
index = PROCESS_LIST.FindIndex((p) => { return p.MyProcess.Id.ToString().Equals(obj.Properties["Handle"].Value.ToString()); });
returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList));
if (returnVal == 0 && index > -1)
{
PROCESS_LIST[index].ProcessOwner = argList[0];
PROCESS_LIST[index].Is64Bit = Is64Bit(PROCESS_LIST[index].MyProcess);
//информация по DEP
bool success = GetProcessMitigationPolicy(PROCESS_LIST[index].MyProcess.Handle, Process_Mitigation_Policy.ProcessDEPPolicy, ref PROCESS_LIST[index].Dep, Marshal.SizeOf(PROCESS_LIST[index].Dep));
//информация по ASLR
success = GetProcessMitigationPolicy(PROCESS_LIST[index].MyProcess.Handle, Process_Mitigation_Policy.ProcessASLRPolicy, ref PROCESS_LIST[index].ASLR, Marshal.SizeOf(PROCESS_LIST[index].ASLR));
}
}
catch
{
if (index != -1)
PROCESS_LIST.RemoveAt(index);
}
}
return;
}
//начало работы формы
private void StartProcessExplorer(object sender, EventArgs e)
{
//получаем все процессы
Process[] ALL_PROCESSES = Process.GetProcesses();
List<Proc_class> PROCESS_LIST = new List<Proc_class>();
//проходимся, заполняем список процессами
foreach (var P in ALL_PROCESSES)
{
try
{
//для рабочего списка
var NEW_PROCESS = new Proc_class();
NEW_PROCESS.MyProcess = P;
NEW_PROCESS.ProcessParent = GetProcessParent(P);
NEW_PROCESS.IntegrityLevel = GetIntegrityLevel(P);
PROCESS_LIST.Add(NEW_PROCESS);
}
catch { }
}
/*получаем владельцев процессов*/
GetProcessOwnerDepAslr(PROCESS_LIST);
foreach (var P in PROCESS_LIST)
{
try
{
ListViewItem item1 = new ListViewItem(P.MyProcess.Id.ToString());
listView1.Items.Add(item1);
item1.SubItems.Add(P.MyProcess.ProcessName);
item1.SubItems.Add(P.MyProcess.MainModule.FileName);
item1.SubItems.Add(P.ProcessParent.ProcessName);
item1.SubItems.Add(P.ProcessParent.Id.ToString());
item1.SubItems.Add(P.ProcessOwner);
item1.SubItems.Add(P.Is64Bit ? "x64" : "x86");
item1.SubItems.Add(P.Dep.Enable.ToString() + P.ASLR.EnableBottomUpRandomization);
string Dlls = "";
for (int i = 0; i < P.MyProcess.Modules.Count; i++)
{
if (P.MyProcess.Modules[i].ModuleName.EndsWith(".dll"))
Dlls += P.MyProcess.Modules[i].ModuleName + "; ";
}
if (Dlls.Length > 0)
{
Dlls = Dlls.Substring(0, Dlls.Length - 1);
}
item1.SubItems.Add(Dlls);
item1.SubItems.Add(P.IntegrityLevel);
item1.SubItems.Add(GetProcessPriveleges(P.MyProcess));
}
catch
{ /**/ }
}
}
//действие при тычке на кнопку обновления
private void refresh_button_Click(object sender, EventArgs e)
{
//удаляем и заново запускаем
listView1.Items.Clear();
StartProcessExplorer(null, null);
}
//действие при тычке на кнопку проверки файла
private void check_button_Click(object sender, EventArgs e)
{
//очищаем таблички от данных
listView2.Items.Clear();
listView3.Items.Clear();
//если строчка с путем пустая, выходим
if (string.IsNullOrEmpty(file_path.Text))
return;
//находим SID и OWNER
var File_Security = File.GetAccessControl(file_path.Text);
var SID = File_Security.GetOwner(typeof(SecurityIdentifier));
var Owner = SID.Translate(typeof(NTAccount));
//находим уровень целостности
int IntegrityLevel_File = GetFileIntegrityLevel(file_path.Text);
string IntegrityLevel_File_str = "";
if (IntegrityLevel_File == 0)
IntegrityLevel_File_str = "untrusted";
else if (IntegrityLevel_File == 1)
IntegrityLevel_File_str = "low";
else if (IntegrityLevel_File == 2)
IntegrityLevel_File_str = "medium";
else if (IntegrityLevel_File == 3)
IntegrityLevel_File_str = "high";
else
IntegrityLevel_File_str = "system";
//находим запись ACL
DirectoryInfo dInfo = new DirectoryInfo(file_path.Text);
DirectorySecurity dSecurity = dInfo.GetAccessControl();
AuthorizationRuleCollection acl = dSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));
foreach (FileSystemAccessRule ace in acl)
{
//выводим ACL в отдельную табличку
ListViewItem item3 = new ListViewItem(ace.IdentityReference.Value.ToString());
listView3.Items.Add(item3);
item3.SubItems.Add(ace.AccessControlType.ToString());
item3.SubItems.Add(ace.FileSystemRights.ToString());
}
//выводим все (кроме ACL) в табличку
ListViewItem item2 = new ListViewItem(SID.ToString());
listView2.Items.Add(item2);
item2.SubItems.Add(Owner.ToString());
item2.SubItems.Add(IntegrityLevel_File_str);
return;
}
//получить привилегии процесса по идентификатору
public string GetProcessPriveleges(Process process)
{
string allPriv = "";
PrivilegeAndAttributesCollection privileges = process.GetPrivileges();
try
{
int maxPrivilegeLength = privileges.Max(privilege => privilege.Privilege.ToString().Length);
foreach (PrivilegeAndAttributes privilegeAndAttributes in privileges)
{
//получаем привилегию
Privilege privilege = privilegeAndAttributes.Privilege;
//получаем состояние привилегии
PrivilegeState privilegeState = privilegeAndAttributes.PrivilegeState;
//если привилегия активна, записываем ее в список
if (privilegeState.ToString() == "Enabled")
allPriv += privilege + "; ";
}
}
catch { }
return allPriv;
}
//получить родителя процесса по идентификатору
private Process GetProcessParent(Process process)
{
int parentPid = 0, processPid = process.Id;
uint TH32CS_SNAPPROCESS = 2;
//делаем снимок всех процессов
IntPtr hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot == IntPtr.Zero)
return null;
PROCESSENTRY32 procInfo = new PROCESSENTRY32();
procInfo.dwSize = (uint)Marshal.SizeOf(typeof(PROCESSENTRY32));
//читаем первый
if (Process32First(hSnapshot, ref procInfo) == false)
return null;
//проходим по снимку и ищем родителя
do
{
if (processPid == procInfo.th32ProcessID)
parentPid = (int)procInfo.th32ParentProcessID;
}
while (parentPid == 0 && Process32Next(hSnapshot, ref procInfo));
if (parentPid > 0)
return Process.GetProcessById(parentPid);
else
return null;
}
//действие при тычке на айди процесса
private void ListView1_SelectedIndexChanged(object sender, MouseEventArgs e)
{
//создаем форму2, передаем ей айди процесса, показываем
Form2 Form2 = new Form2();
Form2.Show();
Form2.start_check_privileges(listView1.SelectedItems[0].Text);
return;
}
//действие при тычке на кнопку изменения у файла
private void Change_button_Click(object sender, EventArgs e)
{
//если строчка с путем пуста, выходим
if (string.IsNullOrEmpty(file_path.Text))
return;
//создаем форму3, передаем ей путь, показываем
Form3 Form3 = new Form3();
Form3.Tag = file_path.Text;
Form3.Show();
return;
}
/**//**//**//**//**//**//**//**/
const uint ERROR_INSUFFICIENT_BUFFER = 122;
const long SECURITY_MANDATORY_LOW_RID = 0x00001000L;
const long SECURITY_MANDATORY_MEDIUM_RID = 0x00002000L;
const long SECURITY_MANDATORY_HIGH_RID = 0x00003000L;
const long SECURITY_MANDATORY_SYSTEM_RID = 0x00004000L;
enum TOKEN_INFORMATION_CLASS
{
TokenUser = 1,
TokenGroups = 2,
TokenPrivileges = 3,
TokenOwner = 4,
TokenPrimaryGroup = 5,
TokenDefaultDacl = 6,
TokenSource = 7,
TokenType = 8,
TokenImpersonationLevel = 9,
TokenStatistics = 10,
TokenRestrictedSids = 11,
TokenSessionId = 12,
TokenGroupsAndPrivileges = 13,
TokenSessionReference = 14,
TokenSandBoxInert = 15,
TokenAuditPolicy = 16,
TokenOrigin = 17,
TokenElevationType = 18,
TokenLinkedToken = 19,
TokenElevation = 20,
TokenHasRestrictions = 21,
TokenAccessInformation = 22,
TokenVirtualizationAllowed = 23,
TokenVirtualizationEnabled = 24,
TokenIntegrityLevel = 25,
TokenUIAccess = 26,
TokenMandatoryPolicy = 27,
TokenLogonSid = 28,
MaxTokenInfoClass = 29
}
[StructLayout(LayoutKind.Sequential)]
struct TOKEN_MANDATORY_LABEL
{
public SID_AND_ATTRIBUTES Label;
}
[StructLayout(LayoutKind.Sequential)]
struct SID_AND_ATTRIBUTES
{
public IntPtr Sid;
public int Attributes;
}
[DllImport("C:\\Users\\dzaga\\Desktop\\MBST_Lab_1\\IntegrityLevel.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
public static extern int GetFileIntegrityLevel(string FileName);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CloseHandle(IntPtr hObject);
[DllImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool OpenProcessToken(IntPtr ProcessHandle,
TokenAccessLevels DesiredAccess,
out IntPtr TokenHandle);
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool GetTokenInformation(IntPtr TokenHandle,
TOKEN_INFORMATION_CLASS TokenInformationClass,
IntPtr TokenInformation,
uint TokenInformationLength,
out uint ReturnLength);
[DllImport("kernel32.dll")]
static extern IntPtr LocalAlloc(uint uFlags, UIntPtr uBytes);
[DllImport("advapi32.dll", SetLastError = true)]
static extern IntPtr GetSidSubAuthority(IntPtr pSid, int nSubAuthority);
[DllImport("advapi32.dll", SetLastError = true)]
static extern IntPtr GetSidSubAuthorityCount(IntPtr pSid);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr CreateToolhelp32Snapshot(uint dwFlags, uint th32ProcessID);
[DllImport("kernel32.dll")]
private static extern bool Process32First(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
[DllImport("kernel32.dll")]
private static extern bool Process32Next(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
[StructLayout(LayoutKind.Sequential)]
private struct PROCESSENTRY32
{
public uint dwSize;
public uint cntUsage;
public uint th32ProcessID;
public IntPtr th32DefaultHeapID;
public uint th32ModuleID;
public uint cntThreads;
public uint th32ParentProcessID;
public int pcPriClassBase;
public uint dwFlags;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szExeFile;
}
}
}