Script do PowerShell para ativar ou desativar perfis de firewall do Windows

Garantir a segurança de redes e sistemas é a base da TI. Uma das principais defesas em um ambiente Windows é o Firewall do Windows. Ao controlar o fluxo de tráfego de entrada e saída, ele atua como um gatekeeper. Este artigo se aprofunda em um script do PowerShell que fornece um método simplificado para ativar ou desativar perfis do Firewall do Windows, uma tarefa crucial para os profissionais de TI.

Histórico

O script apresentado foi projetado para ativar ou desativar todos os perfis do Firewall do Windows, ou seja, Domínio, Público e Privado. Esses perfis determinam as configurações e regras aplicadas com base no tipo de rede ao qual um computador está conectado. Para os provedores de serviços gerenciados (MSPs) e profissionais de TI, uma ferramenta que possa alternar rapidamente esses perfis é inestimável. Seja para solução de problemas, reforço de segurança ou configuração de rede, esse script oferece uma solução rápida.

O roteiro

#Requires -Version 5.1

<#
.SYNOPSIS
    Enable or disable all Windows Firewall profiles(Domain, Public, Private).
.DESCRIPTION
    Enable or disable all Windows Firewall profiles(Domain, Public, Private).
.EXAMPLE
     -Disable
    Disables all Windows Firewall profiles(Domain, Public, Private).
.EXAMPLE
     -Enable
    Enables all Windows Firewall profiles(Domain, Public, Private).
.EXAMPLE
     -Enable -BlockAllInbound
    Enables all Windows Firewall profiles(Domain, Public, Private).
    Blocks all inbound traffic on the Domain, Public, Private profiles
.OUTPUTS
    String[]
.OUTPUTS
    PSCustomObject[]
.NOTES
    Minimum OS Architecture Supported: Windows 10, Windows Server 2016
    Release Notes:
    Initial Release
By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
    Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
.COMPONENT
    ProtocolSecurity
#>

[CmdletBinding(DefaultParameterSetName = "Enable")]
param (
    [Parameter(
        Mandatory = $true,
        ParameterSetName = "Enable"
    )]
    [Switch]
    $Enable,
    [Parameter(
        Mandatory = $true,
        ParameterSetName = "Disable"
    )]
    [Switch]
    $Disable,
    [Parameter(
        ParameterSetName = "Enable"
    )]
    [Switch]
    $BlockAllInbound
)

begin {
    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
    }
}
process {
    if (-not $(Test-IsElevated)) {
        Write-Error -Message "Access Denied. Please run with Administrator privileges."
        exit 1
    }
    if ($(Get-Command "Get-NetFirewallProfile" -ErrorAction SilentlyContinue).Name -like "Get-NetFirewallProfile") {
        # Use Get-NetFirewallProfile if available
        try {
            $NetFirewallSplat = @{
                Profile     = @("Domain", "Public", "Private")
                Enabled     = $(if ($Enable) { "True" }elseif ($Disable) { "False" })
                ErrorAction = "Stop"
            }
            if ($Enable -and $BlockAllInbound) {
                $NetFirewallSplat.Add('DefaultInboundAction', 'Block')
                $NetFirewallSplat.Add('DefaultOutboundAction', 'Allow')
            }
            Set-NetFirewallProfile @NetFirewallSplat
            
        }
        catch {
            Write-Error $_
            Write-Host "Failed to turn $(if ($Enable) { "on" }elseif ($Disable) { "off" }) the firewall."
            exit 1
        }
        # Proof of work
        Get-NetFirewallProfile -ErrorAction Stop | Format-Table Name, Enabled        
    }
    else {
        # Fall back onto netsh
        netsh.exe AdvFirewall set AllProfiles state $(if ($Enable) { "on" }elseif ($Disable) { "off" })
        if ($LASTEXITCODE -gt 0) { exit $LASTEXITCODE }
        netsh.exe AdvFirewall set DomainProfile state $(if ($Enable) { "on" }elseif ($Disable) { "off" })
        if ($LASTEXITCODE -gt 0) { exit $LASTEXITCODE }
        netsh.exe AdvFirewall set PrivateProfile state $(if ($Enable) { "on" }elseif ($Disable) { "off" })
        if ($LASTEXITCODE -gt 0) { exit $LASTEXITCODE }
        netsh.exe AdvFirewall set PublicProfile state $(if ($Enable) { "on" }elseif ($Disable) { "off" })
        if ($LASTEXITCODE -gt 0) { exit $LASTEXITCODE }
        
        if ($Enable -and $BlockAllInbound) {
            try {
                netsh.exe AdvFirewall set DomainProfile FirewallPolicy "BlockInbound,AllowOutbound"
                if ($LASTEXITCODE -gt 0) { exit $LASTEXITCODE }
                netsh.exe AdvFirewall set PrivateProfile FirewallPolicy "BlockInbound,AllowOutbound"
                if ($LASTEXITCODE -gt 0) { exit $LASTEXITCODE }
                netsh.exe AdvFirewall set PublicProfile FirewallPolicy "BlockInbound,AllowOutbound"
                if ($LASTEXITCODE -gt 0) { exit $LASTEXITCODE }
            }
            catch {
                Write-Error $_
                Write-Host "Could not set Block All Inbound Traffic to 1"
            }
        }
        # Proof of work
        netsh.exe AdvFirewall show AllProfiles state
        if ($LASTEXITCODE -gt 0) { exit $LASTEXITCODE }
    }
}
end {}

 

Acesse mais de 300 scripts no NinjaOne Dojo

Obter acesso

Detalhamento

Em sua essência, o script verifica se há privilégios de administrador, o que é essencial, pois a alteração das configurações do firewall exige direitos elevados. Em seguida, ele verifica a presença do cmdlet Get-NetFirewallProfile, um comando moderno do PowerShell para gerenciar perfis de firewall.

Se esse cmdlet estiver disponível, o script o utilizará para ativar ou desativar os perfis especificados. Uma opção para bloquear todo o tráfego de entrada, embora permita o tráfego de saída, acrescenta uma camada extra de segurança.

Na ausência do cmdlet Get-NetFirewallProfile, o script reverte para a ferramenta de linha de comando netsh.exe mais antiga.

Casos de uso em potencial

Considere uma profissional de TI, Jane, em uma grande corporação. Eles estão introduzindo um novo aplicativo, mas, durante os testes, descobrem que o aplicativo não consegue se comunicar com o servidor. Suspeitando de um problema de firewall, Jane usa esse script para desativar temporariamente os perfis de firewall, testar o aplicativo e, em seguida, reativá-los imediatamente. Essa ação rápida ajuda a diagnosticar o problema sem navegação manual.

Comparações

O script fornece uma abordagem programática para gerenciar perfis de firewall. As alternativas incluem o ajuste manual por meio da GUI do Firewall do Windows ou o uso de GPOs (Group Policy Objects, Objetos de Política de Grupo) para máquinas unidas por domínio. No entanto, ambos não têm o imediatismo desse roteiro.

Implicações de segurança

A capacidade de alternar rapidamente os perfis de firewall é uma faca de dois gumes. Desativá-los, mesmo que momentaneamente, pode expor os sistemas a ameaças. É fundamental compreender as implicações de segurança e garantir que os sistemas permaneçam protegidos.

Recomendações

  • Teste o script em um ambiente controlado primeiro.
  • Se você estiver desativando o firewall para diagnóstico, reative-o imediatamente depois.
  • Revisar regularmente as regras de firewall para garantir o alinhamento com as políticas de segurança.

Considerações finais

O gerenciamento dos perfis do Firewall do Windows é essencial para a segurança da rede e do sistema. Embora ferramentas como o NinjaOne ofereçam soluções abrangentes de gerenciamento de TI, scripts como o discutido são inestimáveis para tarefas específicas. Como sempre, entender seu funcionamento e suas implicações garante seu uso eficaz e seguro.

FAQs

Ele foi projetado para Windows 10 e Windows Server 2016 e superior.

Sim, são necessários privilégios de administrador.

Próximas etapas

Montar uma equipe de TI eficaz requer uma solução centralizada que seja a principal ferramenta de entrega de serviços. Com NinjaOne, a TI monitora, gerencia, protege e oferece suporte a todos os dispositivos, onde quer que estejam, dispensando infraestrutura complexa no local.

Saiba mais sobre a solução NinjaOne Remote Script Deployment, agende uma demonstração, ou inicie sua avaliação gratuita da plataforma NinjaOne.

Categories:

You might also like