-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBlockFolderWindowsFirewall.ps1
More file actions
389 lines (334 loc) · 15 KB
/
BlockFolderWindowsFirewall.ps1
File metadata and controls
389 lines (334 loc) · 15 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
<#PSScriptInfo
.VERSION 1.1.0
.GUID c7a7f36d-3d4f-4e2e-9bec-336ec8a0eb16
.AUTHOR asherto
.COMPANYNAME asheroto
.TAGS PowerShell Windows exe block allow unblock firewall folder directory recursive
.PROJECTURI https://github.com/asheroto/BlockFolderWindowsFirewall
.RELEASENOTES
[Version 0.0.1] - Initial Release.
[Version 0.0.2] - Added recurse option.
[Version 0.0.3] - Updated code signing certificate.
[Version 1.0.0] - Major improvements. Added -Version, -Help, -CheckForUpdate. Added inbound/outbound option (will do both if not specified).
[Version 1.0.1] - Added additional line breaks, changed first line to warning, and added PowerShell gallery info to -CheckForUpdate
[Version 1.0.2] - Added UpdateSelf function, fixed CheckForUpdate function.
[Version 1.1.0] - Added -Allow parameter, merged Block/Allow into Set-ExeFirewallRule, refactored main loop.
#>
<#
.SYNOPSIS
Block, allow, or unblock all EXEs in a specified folder in Windows Firewall.
.DESCRIPTION
This script provides functionalities to manage (block/allow/unblock) executables (EXEs) in specified directories via Windows Firewall. The operation can be targeted at individual directories or recursively applied to subdirectories as well.
By default, both Inbound and Outbound connections will be affected, but the scope can be controlled via the -Inbound or -Outbound switches.
Here are key switches to guide the script's behavior:
-Path to specify the target directory.
-Recurse switch will include all subdirectories in the operation.
-UnblockInstead switch changes the operation mode from blocking to unblocking (removes existing Block rules).
-Allow switch creates Allow firewall rules instead of Block rules.
-Inbound switch will only affect Inbound connections.
-Outbound switch will only affect Outbound connections.
Additional utilities include:
-Version switch displays the current version of the script.
-Help switch brings up the help information for the script usage.
-CheckForUpdate switch verifies if the current script version is up-to-date.
Special care should be taken when using this script due to its potentially broad impact. Blocking EXEs indiscriminately may disrupt applications depending on these executables.
.EXAMPLE
BlockFolderWindowsFirewall -Path "C:\Folder\Subfolder"
This command will block both inbound and outbound traffic for all EXEs in the specified folder.
.EXAMPLE
BlockFolderWindowsFirewall -Path "C:\Folder\Subfolder" -Recurse
This command will block both inbound and outbound traffic for all EXEs in the specified folder and all its subfolders.
.EXAMPLE
BlockFolderWindowsFirewall -Path "C:\Folder\Subfolder" -Inbound
This command will block only inbound traffic for all EXEs in the specified folder.
.EXAMPLE
BlockFolderWindowsFirewall -Path "C:\Folder\Subfolder" -UnblockInstead
This command will unblock both inbound and outbound traffic for all EXEs in the specified folder.
.EXAMPLE
BlockFolderWindowsFirewall -Path "C:\Folder\Subfolder" -Recurse -UnblockInstead
This command will unblock both inbound and outbound traffic for all EXEs in the specified folder and all its subfolders.
.EXAMPLE
BlockFolderWindowsFirewall -Path "C:\Folder\Subfolder" -Outbound -UnblockInstead
This command will unblock only outbound traffic for all EXEs in the specified folder.
.EXAMPLE
BlockFolderWindowsFirewall -Path "C:\Folder\Subfolder" -Allow
This command will create Allow rules for both inbound and outbound traffic for all EXEs in the specified folder.
.EXAMPLE
BlockFolderWindowsFirewall -Path "C:\Folder\Subfolder" -Allow -Recurse
This command will create Allow rules for both inbound and outbound traffic for all EXEs in the specified folder and all its subfolders.
.EXAMPLE
BlockFolderWindowsFirewall -Path "C:\Folder\Subfolder" -Allow -Inbound
This command will create Allow rules for only inbound traffic for all EXEs in the specified folder.
.EXAMPLE
BlockFolderWindowsFirewall -Path "C:\Folder\Subfolder" -Allow -Outbound
This command will create Allow rules for only outbound traffic for all EXEs in the specified folder.
.PARAMETER Path
The directory path to target for the operation.
.PARAMETER Recurse
Include all subdirectories in the operation.
.PARAMETER UnblockInstead
Change the operation mode from blocking to unblocking (removes existing Block rules).
.PARAMETER Allow
Create Allow firewall rules instead of Block rules. Cannot be used with -UnblockInstead.
.PARAMETER Inbound
Only affect Inbound connections.
.PARAMETER Outbound
Only affect Outbound connections.
.PARAMETER CheckForUpdate
Verify if the current script version is up-to-date.
.PARAMETER UpdateSelf
Updates the script to the latest version on PSGallery.
.PARAMETER Version
Display the current version of the script.
.PARAMETER Help
Bring up the help information for the script usage.
.NOTES
Version : 1.1.0
Created by : asheroto
.LINK
Project Site: https://github.com/asheroto/BlockFolderWindowsFirewall
#>
#Requires -RunAsAdministrator
[CmdletBinding()]
param (
[String]$Path,
[Switch]$Outbound,
[Switch]$Inbound,
[Switch]$Recurse,
[Switch]$UnblockInstead,
[Switch]$Allow,
[switch]$CheckForUpdate,
[switch]$UpdateSelf,
[switch]$Version,
[switch]$Help
)
# Version
$CurrentVersion = '1.1.0'
$RepoOwner = 'asheroto'
$RepoName = 'BlockFolderWindowsFirewall'
$PowerShellGalleryName = 'BlockFolderWindowsFirewall'
# Display version if -Version is specified
if ($Version.IsPresent) {
$CurrentVersion
exit 0
}
# Help
if ($Help) {
Get-Help -Name $MyInvocation.MyCommand.Source -Full
exit 0
}
function Get-GitHubRelease {
<#
.SYNOPSIS
Fetches the latest release information of a GitHub repository.
.DESCRIPTION
This function uses the GitHub API to get information about the latest release of a specified repository, including its version and the date it was published.
.PARAMETER Owner
The GitHub username of the repository owner.
.PARAMETER Repo
The name of the repository.
.EXAMPLE
Get-GitHubRelease -Owner "asheroto" -Repo "winget-install"
This command retrieves the latest release version and published datetime of the winget-install repository owned by asheroto.
#>
[CmdletBinding()]
param (
[string]$Owner,
[string]$Repo
)
try {
$url = "https://api.github.com/repos/$Owner/$Repo/releases/latest"
$response = Invoke-RestMethod -Uri $url -ErrorAction Stop
$latestVersion = $response.tag_name
$publishedAt = $response.published_at
# Convert UTC time string to local time
$UtcDateTime = [DateTime]::Parse($publishedAt, [System.Globalization.CultureInfo]::InvariantCulture, [System.Globalization.DateTimeStyles]::RoundtripKind)
$PublishedLocalDateTime = $UtcDateTime.ToLocalTime()
[PSCustomObject]@{
LatestVersion = $latestVersion
PublishedDateTime = $PublishedLocalDateTime
}
} catch {
Write-Error "Unable to check for updates.`nError: $_"
exit 1
}
}
function CheckForUpdate {
param (
[string]$RepoOwner,
[string]$RepoName,
[version]$CurrentVersion,
[string]$PowerShellGalleryName
)
$Data = Get-GitHubRelease -Owner $RepoOwner -Repo $RepoName
Write-Output ""
Write-Output ("Repository: {0,-40}" -f "https://github.com/$RepoOwner/$RepoName")
Write-Output ("Current Version: {0,-40}" -f $CurrentVersion)
Write-Output ("Latest Version: {0,-40}" -f $Data.LatestVersion)
Write-Output ("Published at: {0,-40}" -f $Data.PublishedDateTime)
if ($Data.LatestVersion -gt $CurrentVersion) {
Write-Output ("Status: {0,-40}" -f "A new version is available.")
Write-Output "`nOptions to update:"
Write-Output "- Download latest release: https://github.com/$RepoOwner/$RepoName/releases"
if ($PowerShellGalleryName) {
Write-Output "- Run: $RepoName -UpdateSelf"
Write-Output "- Run: Install-Script $PowerShellGalleryName -Force"
}
} else {
Write-Output ("Status: {0,-40}" -f "Up to date.")
}
exit 0
}
function UpdateSelf {
try {
# Get PSGallery version of script
$psGalleryScriptVersion = (Find-Script -Name $PowerShellGalleryName).Version
# If the current version is less than the PSGallery version, update the script
if ($CurrentVersion -lt $psGalleryScriptVersion) {
Write-Output "Updating script to version $psGalleryScriptVersion..."
# Install NuGet PackageProvider if not already installed
if (-not (Get-PackageProvider -Name NuGet -ErrorAction SilentlyContinue)) {
Install-PackageProvider -Name "NuGet" -Force
}
# Trust the PSGallery if not already trusted
$psRepoInstallationPolicy = (Get-PSRepository -Name 'PSGallery').InstallationPolicy
if ($psRepoInstallationPolicy -ne 'Trusted') {
Set-PSRepository -Name 'PSGallery' -InstallationPolicy Trusted | Out-Null
}
# Update the script
Install-Script $PowerShellGalleryName -Force
# If PSGallery was not trusted, reset it to its original state
if ($psRepoInstallationPolicy -ne 'Trusted') {
Set-PSRepository -Name 'PSGallery' -InstallationPolicy $psRepoInstallationPolicy | Out-Null
}
Write-Output "Script updated to version $psGalleryScriptVersion."
exit 0
} else {
Write-Output "Script is already up to date."
exit 0
}
} catch {
Write-Output "An error occurred: $_"
exit 1
}
}
function Set-ExeFirewallRule {
param(
[String]$FileName,
[String]$FilePath,
[ValidateSet('Allow', 'Block')]
[String]$Action,
[Switch]$Inbound,
[Switch]$Outbound
)
$verb = if ($Action -eq 'Allow') { 'Allowing' } else { 'Blocking' }
if ($Inbound.IsPresent -eq $false -and $Outbound.IsPresent -eq $false) {
Write-Output "$verb Inbound and Outbound $FilePath..."
New-NetFirewallRule -DisplayName $FileName -Direction Inbound -Program $FilePath -Action $Action | Out-Null
New-NetFirewallRule -DisplayName $FileName -Direction Outbound -Program $FilePath -Action $Action | Out-Null
} elseif ($Inbound.IsPresent) {
Write-Output "$verb Inbound $FilePath..."
New-NetFirewallRule -DisplayName $FileName -Direction Inbound -Program $FilePath -Action $Action | Out-Null
} elseif ($Outbound.IsPresent) {
Write-Output "$verb Outbound $FilePath..."
New-NetFirewallRule -DisplayName $FileName -Direction Outbound -Program $FilePath -Action $Action | Out-Null
}
}
function Unblock-Exe {
param(
[String]$FilePath,
[Switch]$Inbound,
[Switch]$Outbound
)
if ($Inbound.IsPresent -eq $false -and $Outbound.IsPresent -eq $false) {
Write-Output "Unblocking Inbound and Outbound $FilePath..."
$matchingRules = Get-NetFirewallApplicationFilter | ? { $_.AppPath -eq "$FilePath" } | % { Get-NetFirewallRule $_.InstanceID }
if ($matchingRules) {
$matchingRules | Remove-NetFirewallRule
} else {
Write-Warning "No matching Inbound and Outbound rules found for $FilePath"
}
} elseif ($Inbound.IsPresent) {
Write-Output "Unblocking Inbound $FilePath..."
$matchingRules = Get-NetFirewallApplicationFilter | ? { $_.AppPath -eq "$FilePath" } | % { Get-NetFirewallRule $_.InstanceID | ? { $_.Direction -eq "Inbound" } }
if ($matchingRules) {
$matchingRules | Remove-NetFirewallRule
} else {
Write-Warning "No matching Inbound rules found for $FilePath"
}
} elseif ($Outbound.IsPresent) {
Write-Output "Unblocking Outbound $FilePath..."
$matchingRules = Get-NetFirewallApplicationFilter | ? { $_.AppPath -eq "$FilePath" } | % { Get-NetFirewallRule $_.InstanceID | ? { $_.Direction -eq "Outbound" } }
if ($matchingRules) {
$matchingRules | Remove-NetFirewallRule
} else {
Write-Warning "No matching Outbound rules found for $FilePath"
}
}
}
# Update the script if -UpdateSelf is specified
if ($UpdateSelf) { UpdateSelf }
# Check for updates if -CheckForUpdate is specified
if ($CheckForUpdate) { CheckForUpdate -RepoOwner $RepoOwner -RepoName $RepoName -CurrentVersion $CurrentVersion -PowerShellGalleryName $PowerShellGalleryName }
# If Path is not set, check if -Version, -Help, or -CheckForUpdate is specified
if ("" -eq $Path) {
if ($Version.IsPresent -or $Help.IsPresent -or $CheckForUpdate.IsPresent) {
# Do nothing
} else {
Write-Error "-Path is required"
exit 1
}
}
# -Allow and -UnblockInstead are mutually exclusive
if ($Allow.IsPresent -and $UnblockInstead.IsPresent) {
Write-Error "-Allow and -UnblockInstead cannot be used together"
exit 1
}
# If any operation switch is specified, -Path is required
if ($Recurse.IsPresent -or $UnblockInstead.IsPresent -or $Allow.IsPresent -or $Outbound.IsPresent -or $Inbound.IsPresent) {
if ("" -eq $Path) {
Write-Error "-Path is required"
exit 1
}
}
# Confirm folder path exists
if (Test-Path -Path $Path -PathType Container) {
# Update note
Write-Output "`n$RepoName $CurrentVersion"
Write-Output "To check for updates, run $RepoName -CheckForUpdate`n"
# Folder path exists
Write-Output "Folder exists, continuing...`n"
# Pause for 10 seconds if the folder is C:\
If ($Path -eq "C:\") {
Write-Warning "You specified C:\ as the path, this will affect all EXEs on the C drive. Press CTRL+C to cancel, or wait 10 seconds to continue..."
Start-Sleep -Seconds 10
}
# Print operation summary line
$recursePrefix = if ($Recurse) { "Recursively " } else { "" }
if ($Allow) {
Write-Output "${recursePrefix}Allowing EXEs in $Path..."
} elseif ($UnblockInstead) {
Write-Output "${recursePrefix}Unblocking EXEs in $Path..."
} else {
Write-Output "${recursePrefix}Blocking EXEs in $Path..."
}
# Build Get-ChildItem params
$gciParams = @{ Path = $Path; Filter = '*.exe' }
if ($Recurse) { $gciParams['Recurse'] = $true }
Get-ChildItem @gciParams | ForEach-Object {
$FilePath = $_.FullName
$FileName = Split-Path $FilePath -Leaf
if ($Allow) {
Set-ExeFirewallRule -FilePath $FilePath -FileName $FileName -Action Allow -Inbound:$Inbound.IsPresent -Outbound:$Outbound.IsPresent
} elseif ($UnblockInstead) {
Unblock-Exe -FilePath $FilePath -Inbound:$Inbound.IsPresent -Outbound:$Outbound.IsPresent
} else {
Set-ExeFirewallRule -FilePath $FilePath -FileName $FileName -Action Block -Inbound:$Inbound.IsPresent -Outbound:$Outbound.IsPresent
}
}
Write-Output "Done!"
} else {
# Folder path does not exist
Write-Warning "Folder does not exist, please run the script again with a valid path"
}
Write-Output ""