Principais conclusões
- O script define as configurações do Windows Defender SmartScreen por meio do GPO local.
- Projetado para uso em sistemas Windows a partir do Windows 8.1 e Windows Server 2012.
- Oferece opções para ativar ou desativar o SmartScreen e definir seu nível como “Avisar” ou “Bloquear”
- A automação do PowerShell simplifica e padroniza as configurações do SmartScreen em vários sistemas.
- A execução adequada requer privilégios administrativos; caso contrário, ele retorna um erro.
- Antes de implementar, sempre faça backup dos estados do registro e teste o script em configurações controladas.
- O uso do NinjaOne pode simplificar e aprimorar ainda mais essas tarefas de configuração em ambientes corporativos.
No âmbito da segurança de TI corporativa, a definição das configurações e preferências das ferramentas é fundamental para garantir uma segurança hermética. Uma dessas ferramentas que geralmente exige configurações meticulosas é o Windows Defender SmartScreen. Nesta postagem, vamos nos aprofundar em um script do PowerShell desenvolvido para configurar facilmente o Windows Defender SmartScreen por meio de um GPO local.
Histórico
O Windows Defender SmartScreen é um elemento essencial no ecossistema do Windows, fornecendo avisos aos usuários sobre sites, arquivos, aplicativos potencialmente prejudiciais e muito mais. A necessidade de um script do PowerShell para ajustar as configurações de todos os usuários de uma organização surge à medida que os profissionais de TI e os provedores de serviços gerenciados (MSPs) buscam padronizar as configurações e evitar possíveis brechas na segurança.
O roteiro
#Requires -Version 2.0
<#
.SYNOPSIS
Changes the SmartScreen state for all users via local GPO.
.DESCRIPTION
Changes the SmartScreen state for all users via local GPO.
Effected registry entries that are set:
HKLM:SoftwarePoliciesMicrosoftEdgeSmartScreenEnabled = 1
HKLM:SoftwarePoliciesMicrosoftWindowsSystemEnableSmartScreen = 1
HKLM:SoftwarePoliciesMicrosoftWindowsSystemShellSmartScreenLevel = Warn
HKLM:SoftwarePoliciesMicrosoftMicrosoftEdgePhishingFilterEnabledV9 = 1
HKLM:SoftwarePoliciesMicrosoftMicrosoftEdgePhishingFilterPreventOverride = 1
HKLM:SoftwarePoliciesMicrosoftMicrosoftEdgePhishingFilterPreventOverrideAppRepUnknown = 1
.EXAMPLE
-Off
Turn off SmartScreen
.EXAMPLE
-On
Turn on SmartScreen and Warn.
.EXAMPLE
-On -Level Block
Turn on SmartScreen and Block when it normally warns.
.EXAMPLE
PS C:> Set-SmartScreen.ps1 -Off
Turn off SmartScreen
.OUTPUTS
None
.NOTES
Minimum OS Architecture Supported: Windows 8.1, Windows Server 2012
Release Notes:
Fixes bug where registry wasn't being set correctly.
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
OSSecurity
#>
[CmdletBinding(DefaultParameterSetName = "On")]
param (
[Parameter(Mandatory = $true, ParameterSetName = "On")]
[Switch]
$On,
[Parameter(Mandatory = $true, ParameterSetName = "Off")]
[Switch]
$Off,
[Parameter(Mandatory = $false, ParameterSetName = "On")]
[ValidateSet("Block", "Warn")]
[String]
$Level = "Warn"
)
begin {
function Test-IsElevated {
$id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$p = New-Object System.Security.Principal.WindowsPrincipal($id)
if ($p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator))
{ Write-Output $true }
else
{ Write-Output $false }
}
function Set-ItemProp {
param (
$Path,
$Name,
$Value,
[ValidateSet("DWord", "QWord", "String", "ExpandedString", "Binary", "MultiString", "Unknown")]
$PropertyType = "DWord"
)
New-Item -Path $Path -Force | Out-Null
if ((Get-ItemProperty -Path $Path -Name $Name -ErrorAction SilentlyContinue)) {
Set-ItemProperty -Path $Path -Name $Name -Value $Value -Force -Confirm:$false | Out-Null
}
else {
New-ItemProperty -Path $Path -Name $Name -Value $Value -PropertyType $PropertyType -Force -Confirm:$false | Out-Null
}
}
}
process {
if (-not (Test-IsElevated)) {
Write-Error -Message "Access Denied. Please run with Administrator privileges."
exit 1
}
# Set $State to 1 if -On was used or to 0 if -Off was used
$State = if ($On) { 1 }
elseif ($Off) { 0 }
else {
Write-Error ""
}
try {
Set-ItemProp -Path "HKLM:SoftwarePoliciesMicrosoftWindowsSystem" -Name "EnableSmartScreen" -Value $State
Set-ItemProp -Path "HKLM:SoftwarePoliciesMicrosoftWindowsSystem" -Name "ShellSmartScreenLevel" -Value $Level -PropertyType String
Set-ItemProp -Path "HKLM:SoftwarePoliciesMicrosoftMicrosoftEdgePhishingFilter" -Name "EnabledV9" -Value $State
Set-ItemProp -Path "HKLM:SoftwarePoliciesMicrosoftMicrosoftEdgePhishingFilter" -Name "PreventOverride" -Value $State
Set-ItemProp -Path "HKLM:SoftwarePoliciesMicrosoftMicrosoftEdgePhishingFilter" -Name "PreventOverrideAppRepUnknown" -Value $State
# Uses: https://admx.help/?Category=EdgeChromium&Policy=Microsoft.Policies.Edge::SmartScreenEnabled
Set-ItemProp -Path "HKLM:SoftwarePoliciesMicrosoftEdge" -Name "SmartScreenEnabled" -Value $State
}
catch {
Write-Error $_
exit 1
}
Write-Host "Values change in Registry:"
# Output Proof of Work
@(
[PSCustomObject]@{
"Registry Entry" = "HKLM:SoftwarePoliciesMicrosoftEdgeSmartScreenEnabled"
Value = "$(Get-ItemPropertyValue -Path "HKLM:SoftwarePoliciesMicrosoftEdge" -Name "SmartScreenEnabled" -ErrorAction SilentlyContinue)"
}
[PSCustomObject]@{
"Registry Entry" = "HKLM:SoftwarePoliciesMicrosoftWindowsSystemEnableSmartScreen"
Value = "$(Get-ItemPropertyValue -Path "HKLM:SoftwarePoliciesMicrosoftWindowsSystem" -Name "EnableSmartScreen" -ErrorAction SilentlyContinue)"
}
[PSCustomObject]@{
"Registry Entry" = "HKLM:SoftwarePoliciesMicrosoftWindowsSystemShellSmartScreenLevel"
Value = "$(Get-ItemPropertyValue -Path "HKLM:SoftwarePoliciesMicrosoftWindowsSystem" -Name "ShellSmartScreenLevel" -ErrorAction SilentlyContinue)"
}
[PSCustomObject]@{
"Registry Entry" = "HKLM:SoftwarePoliciesMicrosoftMicrosoftEdgePhishingFilterEnabledV9"
Value = "$(Get-ItemPropertyValue -Path "HKLM:SoftwarePoliciesMicrosoftMicrosoftEdgePhishingFilter" -Name "EnabledV9" -ErrorAction SilentlyContinue)"
}
[PSCustomObject]@{
"Registry Entry" = "HKLM:SoftwarePoliciesMicrosoftMicrosoftEdgePhishingFilterPreventOverride"
Value = "$(Get-ItemPropertyValue -Path "HKLM:SoftwarePoliciesMicrosoftMicrosoftEdgePhishingFilter" -Name "PreventOverride" -ErrorAction SilentlyContinue)"
}
[PSCustomObject]@{
"Registry Entry" = "HKLM:SoftwarePoliciesMicrosoftMicrosoftEdgePhishingFilterPreventOverrideAppRepUnknown"
Value = "$(Get-ItemPropertyValue -Path "HKLM:SoftwarePoliciesMicrosoftMicrosoftEdgePhishingFilter" -Name "PreventOverrideAppRepUnknown" -ErrorAction SilentlyContinue)"
}
)
gpupdate.exe /force
Write-Host "A reboot, or three, will be needed for this policy to take affect."
}
end {}
Acesse mais de 300 scripts no NinjaOne Dojo
Detalhamento
O script fornecido visa alterar o estado do SmartScreen para todos os usuários. Ele funciona ajustando entradas de registro específicas. Veja a seguir um detalhamento passo a passo da mecânica do script:
- Configuração inicial: O script começa especificando a versão necessária e fornece uma breve sinopse de sua operação.
- Vinculação e parâmetros de cmdlet: O usuário pode executar o script com os parâmetros -On ou -Off. Além disso, um parâmetro -Level permite que os usuários decidam entre um estado de “Warn” ou “Block” para o SmartScreen.
- Funções de suporte:
- O Test-IsElevated verifica se o script é executado com privilégios administrativos.
- O Set-ItemProp cria ou modifica entradas de registro.
- Processo principal:
- O script primeiro verifica se foi executado com as permissões necessárias.
- Dependendo da entrada do usuário, o script define o estado do SmartScreen e modifica as entradas de registro relevantes.
- Uma saída que exibe os valores de registro alterados é mostrada ao usuário.
- Por fim, o script invoca o gpupdate.exe para forçar uma atualização da Política de Grupo, lembrando aos usuários que talvez seja necessário reiniciar o sistema.
Casos de uso em potencial
Imagine uma empresa em que uma nova política de segurança determina que todos os computadores devem ter o Windows Defender SmartScreen ativado e definido como “Bloquear” Em vez de configurar manualmente cada máquina, um profissional de TI pode implementar esse script para ajustar as configurações em massa, garantindo uniformidade e conformidade em todos os dispositivos.
Comparações
Embora os objetos de política de grupo (GPO) do console de gerenciamento de política de grupo (GPMC ) também possam definir as configurações do SmartScreen, esse script do PowerShell simplifica o processo. Em vez de navegar por várias janelas e configurações no GPMC, os profissionais de TI podem executar um único script, economizando tempo e reduzindo possíveis erros.
Implicações
A configuração bem-sucedida do estado do SmartScreen em toda a organização reforça a segurança de TI, reduzindo os riscos associados a downloads ou sites prejudiciais. No entanto, a configuração incorreta pode expor os sistemas a ameaças ou levar a muitos avisos falsos, dificultando o trabalho.
Recomendações
- Sempre faça backup do estado atual do registro antes de fazer alterações.
- Teste exaustivamente o script em um ambiente controlado antes de implementá-lo em toda a organização.
- Monitore e ajuste continuamente as configurações com base nas necessidades organizacionais.
Considerações finais
Para os profissionais de TI que buscam uma solução perfeita para essas configurações, ferramentas como o NinjaOne podem oferecer recursos aprimorados. Ao integrar scripts como o discutido, o NinjaOne pode ajudar a automatizar, gerenciar e monitorar as tarefas de TI em uma empresa, garantindo operações otimizadas e seguras.