# -*- coding: utf-8 -*-
from setuphelpers import *
def install():
waptpython_paths = [
makepath(WAPT.wapt_base_dir, "wapt-get.exe"),
makepath(WAPT.wapt_base_dir, "waptpython.exe"),
makepath(WAPT.wapt_base_dir, "Scripts", "python.exe"),
]
# Removing rules to prevent duplication
remove_netfirewallrule("WAPT Python")
remove_netfirewallrule("WAPT Python Scripts")
if force:
remove_netfirewallrule("Wapt line command tool")
# Adding Firewall Rules
for waptpython_path in waptpython_paths:
add_netfirewallrule("WAPT Python", waptpython_path, group="WAPT", direction="Inbound", profile="Any", remote_addresses="127.0.0.1")
add_netfirewallrule("WAPT Python", waptpython_path, group="WAPT", direction="Outbound", profile="Domain,Private")
def uninstall():
# Removing Firewall Rules
remove_netfirewallrule("WAPT Python")
def add_netfirewallrule(
rule_name,
app_path,
group=None,
direction="Inbound",
profile=None,
enabled=True,
action="Allow",
protocol=None,
remote_addresses=None,
):
"""
Add a Windows Firewall rule using New-NetFirewallRule cmdlet in PowerShell for Windows 10 and newer,
or netsh advfirewall for older Windows versions.
https://learn.microsoft.com/troubleshoot/windows-server/networking/netsh-advfirewall-firewall-control-firewall-behavior
https://learn.microsoft.com/powershell/module/netsecurity/new-netfirewallrule
Args:
rule_name (str): Display name for the firewall rule.
app_path (str): Path to the program for which the rule is being created.
group (str, optional): Group name for the firewall rule (only works with PowerShell).
direction (str): Direction of the rule (Inbound or Outbound). Default: Inbound.
profile (str or list, optional): Profile(s) to which the rule should apply (e.g., "Domain,Private"). Default: Any.
enabled (bool): Specify if the created rule's state is Enabled (True) or not (False). Default: True.
action (str): Action for the rule (Allow or Block). Default: Allow.
protocol (str, optional): Protocol by name or number (e.g., "TCP", "UDP", "ICMPv4", or "ICMPv6"). Default: Any.
remote_addresses (str or list, optional): Specifies that network packets with matching IP addresses match this rule. Default: None.
Returns:
waptutils.RunOutput: The result of the command execution.
.. versionadded:: 2.5
"""
if not isinstance(profile, list):
profile = ensure_list(profile)
profile = ",".join(profile)
if not isinstance(remote_addresses, list):
remote_addresses = ensure_list(remote_addresses)
remote_addresses_str = ",".join(remote_addresses) if remote_addresses else None
message = f'Adding {"Blocked" if action == "Block" else "Allowed"} and {"Enabled" if enabled else "Disabled"} Firewall Rule: {rule_name}'
if group:
message += f" (Group: {group})"
if direction:
message += f" (Direction: {direction})"
if profile:
message += f" (Profile(s): {profile})"
if protocol:
message += f" (Protocol: {protocol})"
if remote_addresses_str:
message += f" (Distant IPs: {remote_addresses_str})"
message += f" for: {app_path}"
print(message)
if windows_version() < WindowsVersions.Windows10:
direction = "out" if direction.lower() == "Outbound".lower() else "in"
enabled = "no" if not enabled else "yes"
cmd_command = f'netsh advfirewall firewall add rule name="{rule_name}" dir={direction} action={action} program="{app_path}" enable={enabled}'
if profile: # any and all are working
cmd_command += f' profile="{profile}"'
if protocol:
cmd_command += f' protocol="{protocol}"'
if remote_addresses_str:
cmd_command += f' remoteip="{remote_addresses_str}"'
result = run_notfatal(cmd_command)
else:
pwsh_command = (
f'New-NetFirewallRule -DisplayName "{rule_name}" -Direction {direction} -Action {action} -Program "{app_path}" -Enabled {str(enabled)}'
)
if group:
pwsh_command += f' -Group "{group}"'
if profile:
pwsh_command += f' -Profile "{profile}"'
if protocol:
pwsh_command += f' -Protocol "{protocol}"'
if remote_addresses_str:
pwsh_command += f' -RemoteAddress "{remote_addresses_str}"'
result = run_powershell(pwsh_command, output_format="text")
return result
def remove_netfirewallrule(rule_name):
"""
Remove Windows Firewall rules using New-NetFirewallRule cmdlet in PowerShell for Windows 10 and newer,
or netsh advfirewall for older Windows versions.
Args:
rule_name (str): Display name of the firewall rules to remove.
Returns:
waptutils.RunOutput: The result of the command execution.
.. versionadded:: 2.5
"""
print(f"Removing Firewall Rules: {rule_name}")
if windows_version() < WindowsVersions.Windows10:
result = run_notfatal(f'netsh advfirewall firewall delete rule name="{rule_name}"')
else:
result = run_powershell(
f'Remove-NetFirewallRule -DisplayName "{rule_name}" -ErrorAction SilentlyContinue', output_format="text", accept_returncodes=[0, 1, 3010]
)
return result