-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainPage.cs
227 lines (208 loc) · 9.07 KB
/
MainPage.cs
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Text;
using System.Windows.Forms;
namespace EazyFirewallBlockerGUI
{
public partial class MainPage : Form
{
public MainPage()
{
InitializeComponent();
fetchInfo();
}
/// <summary>
/// Name of the companion batch file that is required by the program to function
/// </summary>
const string BATCHFILENAME = "FirewallBlocker.bat";
/// <summary>
/// Store a boolean for the current checked state
/// </summary>
bool selected = false;
/// <summary>
/// Search for all the executables in the provided path and populate them into the checkbox list
/// </summary>
/// <param name="lookupPath"></param>
/// <returns></returns>
void populateExecutables(string lookupPath)
{
chkbFilesList.Items.Clear(); // clear the list for fresh data
// Name of the current executable
string curExeName = System.AppDomain.CurrentDomain.FriendlyName;
var executablesInDir = Directory.GetFiles(lookupPath, "*.exe", SearchOption.AllDirectories).
Where(path => Path.GetFileNameWithoutExtension(path) != Path.GetFileNameWithoutExtension(curExeName)).
ToArray();
//alert the user if no executables are found
if (executablesInDir.Count() == 0)
{
MessageBox.Show("No executables were found in " + "\"" + lookupPath + "\".", "Info");
return;
}
// add items to the checkbox list
for (int i = 0; i < executablesInDir.Count(); i++)
{
chkbFilesList.Items.Add(executablesInDir[i], CheckState.Checked);
}
}
/// <summary>
/// Fetch the executables in the directory
/// where the program is copied to
/// </summary>
private void fetchInfo()
{
// validate if the companion batch file exists or not
string curDir = Directory.GetCurrentDirectory();
string batchFilepath = curDir + "\\" + BATCHFILENAME;
if (!File.Exists(batchFilepath))
{
MessageBox.Show(string.Format("The batch process file \"{0}\" was not found.\r\nThe program will now exit!", batchFilepath), "Error");
Environment.Exit(0);
}
// populate the checkbox list
populateExecutables(curDir);
}
/// <summary>
/// select default directory button
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BtnSelectDir_Click(object sender, EventArgs e)
{
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
populateExecutables(fbd.SelectedPath);
}
}
}
/// <summary>
/// Block program in firewall execute button
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BtnBlkFirewall_Click(object sender, EventArgs e)
{
// return if no items are checked
if (chkbFilesList.CheckedItems.Count == 0)
{
MessageBox.Show("Please check files to block in the Windows Defender Firewall.", "Info");
return;
}
// get the list of
StringBuilder checkedExecList = new StringBuilder();
foreach (string executable in chkbFilesList.CheckedItems)
{
checkedExecList.Append("- " + Path.GetFileName(executable) + Environment.NewLine);
}
// confirm the action
DialogResult confirmation = MessageBox.Show(string.Format("Are you sure you want to block the following program/programs in Windows Defender Firewall?\r\n{0}", checkedExecList.ToString()), "Inquiry", MessageBoxButtons.YesNo);
if (confirmation == DialogResult.Yes)
{
StringBuilder executionResultList = new StringBuilder();
foreach (string executablePath in chkbFilesList.CheckedItems)
{
string executionResult = string.Empty;
bool OK = blockFirewall(executablePath, ref executionResult); // block the selected programs
if (!OK)
{
MessageBox.Show(executionResult, "Error");
Environment.Exit(0);
}
executionResultList.Append(executionResult);
}
// handle the batch script execution results
if (executionResultList.ToString() != string.Empty)
{
MessageBox.Show("Batch file executed successfully!", "Info");
DialogResult showResults = MessageBox.Show("Do you want to see the results of executing the batch file?", "Inquiry", MessageBoxButtons.YesNo);
if (showResults == DialogResult.Yes)
{
FileStream currentFileStream = null;
DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
string tempFilePath = Path.GetTempPath() + string.Format("temp_{0}.txt", (DateTime.UtcNow - UnixEpoch).TotalMilliseconds.ToString());
if (!File.Exists(tempFilePath)) // create file if file does not already exist
{
currentFileStream = File.Create(tempFilePath);
currentFileStream.Close(); // frees the file for editing/reading
}
File.WriteAllText(tempFilePath, executionResultList.ToString()); // overwrites all text in temp file
Process.Start(tempFilePath); // opens the file in the default text editor
}
}
}
}
/// <summary>
/// Close button
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BtnClose_Click(object sender, EventArgs e)
{
Environment.Exit(0);
}
/// <summary>
/// Adds a reference in the Windows Defender Firewall for both
/// incoming and outgoing connections for a specific program (executable)
/// </summary>
/// <param name="filePath"></param>
/// <param name="result"></param>
/// <returns>true: on successful execution of the batch script</returns>
private bool blockFirewall(string filePath, ref string outRes)
{
try
{
using (Runspace myRunSpace = RunspaceFactory.CreateRunspace())
{
myRunSpace.Open();
using (PowerShell powershell = PowerShell.Create())
{
// add the command to run the bat file
powershell.AddCommand(".\\" + BATCHFILENAME);
powershell.AddArgument(filePath); // first argument: file path for the file which is to be blocked
powershell.AddArgument(Path.GetFileName(filePath)); // second argument: filename of the file which is to be blocked
// execute the script
var results = powershell.Invoke();
powershell.Streams.ClearStreams();
powershell.Commands.Clear();
// convert the script result into a single string
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < results.Count() - 1; i++) // -1 to omit the final line as it is garbage
{
stringBuilder.AppendLine(results[i].ToString());
}
outRes = stringBuilder.ToString();
return true;
}
}
}
catch (Exception e)
{
outRes = e.Message;
return false;
}
}
/// <summary>
/// Select/unselect all button
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BtnToggleSelection_Click(object sender, EventArgs e)
{
if (chkbFilesList.Items.Count != 0)
{
for (int i = 0; i < chkbFilesList.Items.Count; i++)
{
chkbFilesList.SetItemChecked(i, selected);
}
selected = !selected;
}
}
}
}