-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
714 lines (613 loc) · 22.3 KB
/
Copy pathProgram.cs
File metadata and controls
714 lines (613 loc) · 22.3 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
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using System.Management;
using System.Diagnostics;
using System.Collections.Generic;
namespace LaunchGuard;
internal static class Program
{
[STAThread]
static void Main()
{
Application.SetHighDpiMode(HighDpiMode.PerMonitorV2);
ApplicationConfiguration.Initialize();
AppConfig.Load();
Application.Run(new MainForm());
}
}
internal static class WindowsCredentialHelper
{
[DllImport("credui.dll", CharSet = CharSet.Unicode)]
private static extern uint CredUIPromptForWindowsCredentials(
ref CREDUI_INFO pUiInfo,
uint dwAuthError,
ref uint pulAuthPackage,
IntPtr pvInAuthBuffer,
uint ulInAuthBufferSize,
out IntPtr ppvOutAuthBuffer,
out uint pulOutAuthBufferSize,
ref bool pfSave,
CREDUIWIN_FLAGS dwFlags
);
[DllImport("credui.dll", CharSet = CharSet.Unicode)]
private static extern bool CredUnPackAuthenticationBuffer(
uint dwFlags,
IntPtr pAuthBuffer,
uint cbAuthBuffer,
StringBuilder pszUserName,
ref uint pcchMaxUserName,
StringBuilder pszDomainName,
ref uint pcchMaxDomainname,
StringBuilder pszPassword,
ref uint pcchMaxPassword
);
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool LogonUser(
string lpszUsername,
string lpszDomain,
string lpszPassword,
int dwLogonType,
int dwLogonProvider,
out IntPtr phToken
);
[DllImport("kernel32.dll")]
private static extern bool CloseHandle(IntPtr hObject);
[DllImport("ole32.dll")]
private static extern void CoTaskMemFree(IntPtr ptr);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct CREDUI_INFO
{
public int cbSize;
public IntPtr hwndParent;
public string pszMessageText;
public string pszCaptionText;
public IntPtr hbmBanner;
}
[Flags]
private enum CREDUIWIN_FLAGS : uint
{
CREDUIWIN_GENERIC = 0x1,
CREDUIWIN_ENUMERATE_CURRENT_USER = 0x200,
}
/// <summary>
/// Shows the native Windows credential prompt and validates the entered password.
/// Returns true if the user authenticated successfully.
/// </summary>
public static bool PromptAndValidate(IntPtr ownerHandle)
{
var info = new CREDUI_INFO
{
cbSize = Marshal.SizeOf(typeof(CREDUI_INFO)),
hwndParent = ownerHandle,
pszCaptionText = "Authentication Required",
pszMessageText = "Enter your Windows credentials to access Settings."
};
uint authPackage = 0;
bool save = false;
uint result = CredUIPromptForWindowsCredentials(
ref info, 0, ref authPackage,
IntPtr.Zero, 0,
out IntPtr outBuffer, out uint outBufferSize,
ref save,
CREDUIWIN_FLAGS.CREDUIWIN_ENUMERATE_CURRENT_USER
);
if (result != 0) return false; // User cancelled
var usernameSb = new StringBuilder(256);
var domainSb = new StringBuilder(256);
var passwordSb = new StringBuilder(256);
uint unLen = 256, dnLen = 256, pwLen = 256;
CredUnPackAuthenticationBuffer(
0, outBuffer, outBufferSize,
usernameSb, ref unLen,
domainSb, ref dnLen,
passwordSb, ref pwLen
);
CoTaskMemFree(outBuffer);
string username = usernameSb.ToString();
string password = passwordSb.ToString();
string domain = "."; // local machine by default
// Strip domain prefix if present
if (username.Contains('\\'))
{
var parts = username.Split('\\', 2);
domain = parts[0];
username = parts[1];
}
bool valid = LogonUser(
username, domain, password,
2, // LOGON32_LOGON_INTERACTIVE
0, // LOGON32_PROVIDER_DEFAULT
out IntPtr token
);
if (valid) CloseHandle(token);
return valid;
}
}
internal static class ProcessTreeKiller
{
public static string KillTree(int rootPid)
{
string execPath = string.Empty;
try
{
var root = Process.GetProcessById(rootPid);
execPath = root.MainModule?.FileName ?? string.Empty;
}
catch { }
var children = new Dictionary<int, List<int>>();
using var searcher = new ManagementObjectSearcher(
"SELECT ProcessId, ParentProcessId FROM Win32_Process");
foreach (ManagementObject obj in searcher.Get())
{
int pid = Convert.ToInt32(obj["ProcessId"]);
int parent = Convert.ToInt32(obj["ParentProcessId"]);
if (!children.ContainsKey(parent))
children[parent] = new List<int>();
children[parent].Add(pid);
}
KillSubtree(rootPid, children);
return execPath;
}
private static void KillSubtree(int pid, Dictionary<int, List<int>> children)
{
if (children.TryGetValue(pid, out var kids))
foreach (int child in kids)
KillSubtree(child, children);
try { Process.GetProcessById(pid).Kill(); }
catch { }
}
}
internal sealed class MainForm : Form
{
private readonly HashSet<string> approvedProcesses = new(StringComparer.OrdinalIgnoreCase);
private readonly HashSet<string> interceptionsInFlight = new();
private readonly ManagementEventWatcher processWatcher;
private readonly NotifyIcon trayIcon;
private readonly ContextMenuStrip trayMenu;
private readonly ToolStripMenuItem trayShowHideMenuItem;
private readonly ToolStripMenuItem trayDefensesMenuItem;
private bool exitRequested;
private readonly Button activateDefensesButton;
private readonly PictureBox protectionStatusIcon;
private readonly PictureBox aboutImagecontainer;
private readonly Label aboutLabel;
private readonly Label protectionStatusLabel;
private readonly Image? protectedShieldImage;
private readonly Image? unprotectedShieldImage;
private readonly Image? aboutImage;
private bool defensesActive = true;
private readonly List<ListViewItem> allProcessItems = new();
private ListView processListView = null!;
private TextBox filterBox = null!;
public MainForm()
{
defensesActive = AppConfig.LoadDefensesActiveState(defaultValue: true);
// Form properties
Text = "LaunchGuard";
StartPosition = FormStartPosition.CenterScreen;
AutoScaleMode = AutoScaleMode.Dpi;
AutoScaleDimensions = new SizeF(96, 96);
ClientSize = new Size(640, 360);
FormBorderStyle = FormBorderStyle.FixedSingle;
MaximizeBox = false;
Icon = ResourceHelper.LoadIcon("lock.ico");
trayMenu = new ContextMenuStrip();
trayShowHideMenuItem = new ToolStripMenuItem("Hide Window");
trayDefensesMenuItem = new ToolStripMenuItem();
trayIcon = new NotifyIcon
{
Text = "LaunchGuard",
Icon = Icon,
Visible = true,
ContextMenuStrip = trayMenu
};
trayShowHideMenuItem.Click += (_, _) =>
{
if (Visible)
HideToTray(showTip: false);
else
ShowFromTray();
};
trayDefensesMenuItem.Click += (_, _) => ToggleDefensesWithAuth();
var traySettingsMenuItem = new ToolStripMenuItem("Settings");
traySettingsMenuItem.Click += settingsButton_Click;
var trayAboutMenuItem = new ToolStripMenuItem("About");
trayAboutMenuItem.Click += AboutControl_Click;
var trayExitMenuItem = new ToolStripMenuItem("Exit");
trayExitMenuItem.Click += (_, _) =>
{
exitRequested = true;
Close();
};
trayMenu.Items.AddRange(new ToolStripItem[]
{
trayShowHideMenuItem,
trayDefensesMenuItem,
traySettingsMenuItem,
trayAboutMenuItem,
new ToolStripSeparator(),
trayExitMenuItem
});
trayIcon.DoubleClick += (_, _) => ShowFromTray();
Resize += (_, _) =>
{
if (WindowState == FormWindowState.Minimized)
HideToTray(showTip: true);
};
FormClosing += MainForm_FormClosing;
Label welcomeLabel = new Label()
{
Text = "Welcome to LaunchGuard!",
Font = new Font("Segoe UI", 10, FontStyle.Bold),
AutoSize = true,
Location = new Point(16, 20)
};
Controls.Add(welcomeLabel);
protectedShieldImage = TryLoadImage("green_shiled.png");
unprotectedShieldImage = TryLoadImage("red_shield.png");
protectionStatusIcon = new PictureBox()
{
Location = new Point(580, 14),
Size = new Size(40, 40),
SizeMode = PictureBoxSizeMode.Zoom,
BackColor = Color.Transparent
};
Controls.Add(protectionStatusIcon);
aboutLabel = new Label()
{
Location = new Point(480, 310),
Size = new Size(96, 20),
Text = "About",
Font = new Font("Segoe UI", 9, FontStyle.Bold),
TextAlign = ContentAlignment.MiddleRight,
Cursor = Cursors.Hand,
ForeColor = Color.FromArgb(0, 102, 204)
};
Controls.Add(aboutLabel);
aboutImage = TryLoadImage("info.png");
aboutImagecontainer = new PictureBox()
{
Location = new Point(580, 304),
Size = new Size(30, 30),
Image = aboutImage,
SizeMode = PictureBoxSizeMode.Zoom,
BackColor = Color.Transparent,
Cursor = Cursors.Hand
};
Controls.Add(aboutImagecontainer);
aboutLabel.Click += AboutControl_Click;
aboutImagecontainer.Click += AboutControl_Click;
protectionStatusLabel = new Label()
{
Location = new Point(480, 24),
Size = new Size(96, 20),
Font = new Font("Segoe UI", 9, FontStyle.Bold),
TextAlign = ContentAlignment.MiddleRight
};
Controls.Add(protectionStatusLabel);
filterBox = new TextBox()
{
Location = new Point(20, 50),
Size = new Size(200, 22),
PlaceholderText = "Filter processes..."
};
filterBox.TextChanged += (s, e) =>
{
string term = filterBox.Text.Trim();
processListView.BeginUpdate();
processListView.Items.Clear();
foreach (var it in allProcessItems)
if (string.IsNullOrEmpty(term) || it.Text.Contains(term, StringComparison.OrdinalIgnoreCase))
processListView.Items.Add(it);
processListView.EndUpdate();
};
filterBox.KeyDown += (s, e) =>
{
if (e.KeyCode == Keys.Escape) { filterBox.Clear(); e.SuppressKeyPress = true; }
};
Controls.Add(filterBox);
processListView = new ListView()
{
Location = new Point(20, 80),
Size = new Size(600, 200),
View = View.Details,
FullRowSelect = true,
GridLines = true,
Font = new Font("Segoe UI", 10, FontStyle.Regular)
};
processListView.Columns.Add("Process", 300);
processListView.Columns.Add("Started", 160);
processListView.Columns.Add("PID", processListView.ClientSize.Width - 480);
Controls.Add(processListView);
// Keep the filter box unfocused on startup so its placeholder text is visible.
Shown += (_, _) => processListView.Focus();
Button settingsButton = new Button()
{
Text = "Settings",
Location = new Point(20, 310),
Size = new Size(100, 30)
};
Controls.Add(settingsButton);
settingsButton.Click += settingsButton_Click;
activateDefensesButton = new Button()
{
Location = new Point(130, 310),
Size = new Size(120, 30),
Font = new Font("Segoe UI", 10, FontStyle.Bold),
FlatStyle = FlatStyle.Flat,
};
activateDefensesButton.FlatAppearance.BorderSize = 1;
Controls.Add(activateDefensesButton);
activateDefensesButton.Click += ActivateDefensesButton_Click;
UpdateGuardButtonAppearance();
//Software initialization watcher
var query = new WqlEventQuery(
"__InstanceCreationEvent",
new TimeSpan(0,0,1), //1 second polling interval
"TargetInstance ISA 'Win32_Process'"
);
processWatcher = new ManagementEventWatcher(query);
processWatcher.EventArrived += (sender,e) =>
{
var proc = (ManagementBaseObject)e.NewEvent["TargetInstance"];
string procName = proc["Name"]?.ToString() ?? "Unknown";
string pidStr = proc["ProcessId"]?.ToString() ?? "0";
BeginInvoke(() => HandleNewProcess(procName, pidStr, processListView));
};
processWatcher.Start();
UpdateTrayState();
}
private void MainForm_FormClosing(object? sender, FormClosingEventArgs e)
{
if (!exitRequested && e.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true;
HideToTray(showTip: true);
return;
}
try { processWatcher.Stop(); } catch { }
processWatcher.Dispose();
trayIcon.Visible = false;
trayIcon.Dispose();
trayMenu.Dispose();
}
private void HideToTray(bool showTip)
{
Hide();
ShowInTaskbar = false;
trayShowHideMenuItem.Text = "Show Window";
// Remove this section to add friction to the hiding/tamper attempts.
// WIP reenable with a "Don't show this again" checkbox if user feedback indicates balloon tips are too annoying.
// // if (showTip)
// {
// trayIcon.BalloonTipTitle = "LaunchGuard is still running";
// trayIcon.BalloonTipText = "Use the tray icon to reopen LaunchGuard.";
// trayIcon.ShowBalloonTip(2000);
// }
}
private void ShowFromTray()
{
Show();
ShowInTaskbar = true;
WindowState = FormWindowState.Normal;
Activate();
trayShowHideMenuItem.Text = "Hide Window";
}
private void AboutControl_Click(object? sender, EventArgs e)
{
var AboutForm = new About.AboutForm();
AboutForm.ShowDialog();
}
private void HandleNewProcess(string processName, string pidStr, ListView listView)
{
processName = processName.ToLowerInvariant();
if (approvedProcesses.Contains(processName))
return;
var item = new ListViewItem(processName);
item.SubItems.Add(DateTime.Now.ToString());
item.SubItems.Add(pidStr);
allProcessItems.Add(item);
string term = filterBox.Text.Trim();
if (string.IsNullOrEmpty(term) || processName.Contains(term, StringComparison.OrdinalIgnoreCase))
listView.Items.Add(item);
if (!AreDefensesActive())
return;
if (!AppConfig.LockedProcesses.TryGetValue(processName, out string? requiredPassword))
return;
if (!int.TryParse(pidStr, out int pid)) return;
// Nuke the whole thing
if (!interceptionsInFlight.Add(processName))
{
try { Process.GetProcessById(pid).Kill(); } catch { }
return;
}
string execPath = string.Empty;
try
{
var proc = Process.GetProcessById(pid);
execPath = proc.MainModule?.FileName ?? string.Empty;
}
catch { }
string capturedExecPath = execPath;
System.Threading.Tasks.Task.Delay(800).ContinueWith(_ =>
{
BeginInvoke(() =>
{
try
{
if (!AreDefensesActive())
return;
KillAllByName(processName);
if (!AreDefensesActive())
return;
if (ValidatePassword(processName, requiredPassword) && !string.IsNullOrEmpty(capturedExecPath))
{
approvedProcesses.Add(processName);
AppLauncher.Launch(capturedExecPath, processName);
}
}
finally
{
interceptionsInFlight.Remove(processName);
}
});
});
}
private bool AreDefensesActive()
{
return defensesActive;
}
private static void KillAllByName(string processName)
{
string name = processName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)
? processName[..^4]
: processName;
foreach (var proc in Process.GetProcessesByName(name))
{
try { ProcessTreeKiller.KillTree(proc.Id); }
catch { }
}
}
private static bool ValidatePassword(string processName, string requiredPassword)
{
string input = Microsoft.VisualBasic.Interaction.InputBox(
$"Enter password to allow {processName} to run:",
"Authentication Required"
);
if (input == requiredPassword) return true;
MessageBox.Show(
$"Incorrect password. {processName} will remain blocked.",
"Access Denied",
MessageBoxButtons.OK,
MessageBoxIcon.Warning
);
return false;
}
internal static class AppLauncher
{
private static readonly string WindowsAppsPath =
Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),
"WindowsApps"
).ToLowerInvariant();
private static readonly Dictionary<string, string> KnownUriSchemes = new(StringComparer.OrdinalIgnoreCase)
{
{ "spotify.exe", "spotify:" },
{ "discord.exe", "discord:" },
{ "ms-teams.exe", "msteams:" },
{ "whatsapp.exe", "whatsapp:" },
{ "slack.exe", "slack:" },
};
public static void Launch(string execPath, string processName)
{
if (execPath.ToLowerInvariant().StartsWith(WindowsAppsPath))
{
if (KnownUriSchemes.TryGetValue(processName, out string? uri))
{
Process.Start(new ProcessStartInfo(uri) { UseShellExecute = true });
return;
}
Process.Start(new ProcessStartInfo("explorer.exe", $"\"{execPath}\"")
{
UseShellExecute = true
});
return;
}
Process.Start(new ProcessStartInfo(execPath)
{
UseShellExecute = true
});
}
}
private void settingsButton_Click(object? sender, EventArgs e)
{
bool authenticated = WindowsCredentialHelper.PromptAndValidate(this.Handle);
if (!authenticated)
{
MessageBox.Show(
"Invalid credentials. Access denied.",
"Authentication Failed",
MessageBoxButtons.OK,
MessageBoxIcon.Warning
);
return;
}
var settingsForm = new Settings.SettingsForm();
settingsForm.ShowDialog();
}
private void ActivateDefensesButton_Click(object? sender, EventArgs e)
{
ToggleDefensesWithAuth();
}
private void ToggleDefensesWithAuth()
{
bool authenticated = WindowsCredentialHelper.PromptAndValidate(this.Handle);
if (authenticated)
{
defensesActive = !defensesActive;
approvedProcesses.Clear();
MessageBox.Show(
defensesActive
? "LaunchGuard defenses are now active. Protected apps will require authentication to run."
: "LaunchGuard defenses are now inactive. Protected apps can run without LaunchGuard authentication.",
defensesActive ? "Service Activated" : "Service Deactivated",
MessageBoxButtons.OK,
MessageBoxIcon.Information
);
UpdateGuardButtonAppearance();
AppConfig.SaveDefensesActiveState(defensesActive);
return;
}
else
{
MessageBox.Show(
defensesActive
? "Authentication was not successful. LaunchGuard defenses remain active."
: "Authentication was not successful. LaunchGuard defenses remain inactive.",
"Activation Failed",
MessageBoxButtons.OK,
MessageBoxIcon.Error
);
return;
}
}
private void UpdateGuardButtonAppearance()
{
if (defensesActive)
{
activateDefensesButton.Text = "Stop Guard";
activateDefensesButton.FlatAppearance.BorderColor = Color.FromArgb(198, 80, 80);
protectionStatusIcon.Image = protectedShieldImage;
protectionStatusLabel.Text = "Protected";
protectionStatusLabel.ForeColor = Color.FromArgb(53, 123, 65);
}
else
{
activateDefensesButton.Text = "Start Guard";
activateDefensesButton.FlatAppearance.BorderColor = Color.FromArgb(80, 160, 80);
protectionStatusIcon.Image = unprotectedShieldImage;
protectionStatusLabel.Text = "Unprotected";
protectionStatusLabel.ForeColor = Color.FromArgb(178, 63, 63);
}
UpdateTrayState();
}
private void UpdateTrayState()
{
trayDefensesMenuItem.Text = defensesActive ? "Disable Defenses" : "Enable Defenses";
trayIcon.Text = defensesActive ? "LaunchGuard (Protected)" : "LaunchGuard (Unprotected)";
}
private static Image? TryLoadImage(string resourceFileName)
{
try
{
return ResourceHelper.LoadImage(resourceFileName);
}
catch
{
return null;
}
}
}