Principais conclusões
- As políticas de senha são essenciais para fortalecer a segurança de TI nas organizações.
- O script fornecido automatiza o processo de alteração da complexidade da senha no Windows.
- O script é compatível com computadores com e sem domínio.
- A execução do script sem privilégios administrativos resultará em encerramento.
- Os métodos tradicionais para alterar as políticas de senha podem ser mais demorados do que esse script.
- Sempre teste o script em um ambiente controlado antes de implementá-lo.
- Informar os usuários sobre as alterações nas políticas de senha pode evitar confusão e possíveis bloqueios.
- Revisar e ajustar regularmente as políticas de senha é uma prática recomendada.
- O NinjaOne pode se integrar perfeitamente às ferramentas de automação para reforçar as medidas de segurança.
No atual cenário de TI, a segurança continua sendo fundamental. Com as violações de dados nas manchetes, a definição de políticas de senhas fortes se torna não apenas uma opção, mas uma necessidade. À medida que as organizações procuram fortalecer suas defesas, uma maneira eficiente de atualizar as políticas de senha do Windows surge como um tópico crucial.
Histórico
As políticas de senha, especialmente em ambientes Windows, ajudam a definir os requisitos para a criação e manutenção de senhas. Garantir que elas sejam rigorosas reduz o risco de acesso não autorizado. O script fornecido aqui foi desenvolvido para que os profissionais de TI e os provedores de serviços gerenciados (MSPs) alterem sem esforço a complexidade da senha de um computador com ou sem domínio.
Por que essa ferramenta é inestimável? Alterar manualmente as políticas de senha, especialmente em grandes organizações, pode ser complicado. Um script como esse automatiza o processo, tornando-o mais rápido e menos propenso a erros humanos.
O roteiro
#Requires -Version 5.1
<#
.SYNOPSIS
Modifies the password complexity settings for a domain or a non-domain computer.
.DESCRIPTION
This script can be used to enable or disable the password complexity requirement on a domain or a non-domain computer.
When using -Domain, this script must be run on a Domain Controller with the RSAT feature installed.
.PARAMETER ComplexityEnabled
Enables the Password Complexity requirement.
.PARAMETER Domain
Specifies the name of the domain. If specified, it will enable or disable the password complexity requirement on the Active Directory Default Domain Password Policy.
The computer this script is executed on MUST have the PowerShell RSAT features installed when using the -Domain flag.
.EXAMPLE
-ComplexityEnabled
Enables the password complexity requirement on the computer this script runs on.
.EXAMPLE
No param needed
Disables the password complexity requirement on the computer this script runs on.
.EXAMPLE
-ComplexityEnabled -Domain "test.consto.com"
Enables the password complexity requirement in Active Directory for the Default Domain Password Policy.
When using -Domain, this script must be run on a Domain Controller with the RSAT feature installed.
.EXAMPLE
-Domain "test.consto.com"
Disables the password complexity requirement in Active Directory for the Default Domain Password Policy.
When using -Domain, this script must be run on a Domain Controller with the RSAT feature installed.
.NOTES
Minimum OS Architecture Supported: Windows 10, Windows Server 2016
Release Notes: Renamed script and added Script Variable support
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
ManageUsers
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[Switch]
$ComplexityEnabled,
[Parameter(Mandatory = $false)]
[String]
$Domain
)
begin {
if ($env:activeDirectoryDomain -and $env:activeDirectoryDomain -notlike "null") {
$Domain = $env:activeDirectoryDomain
}
if ($env:complexity -and $env:complexity -notlike "null") {
switch ($env:complexity) {
"Enable" { $ComplexityEnabled = $True }
"Disable" { $ComplexityEnabled = $False }
}
}
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 Test-DomainJoined {
# Check if the computer is domain joined
if ((Get-Command -Name Get-WmiObject -ErrorAction SilentlyContinue)) {
return $(Get-WmiObject -Class Win32_ComputerSystem).PartOfDomain
}
elseif ((Get-Command -Name Get-CIMInstance -ErrorAction SilentlyContinue)) {
return $(Get-CimInstance -ClassName Win32_ComputerSystem).PartOfDomain
}
else {
Write-Host "[Error] Get-WmiObject and Get-CIMInstance are not available. This script requires at least one of these cmdlets to run."
exit 1
}
}
}
process {
if (-not (Test-IsElevated)) {
Write-Host "[Error] Access Denied. Please run with Administrator privileges."
exit 1
}
if (-not ([string]::IsNullOrWhiteSpace($Domain))) {
# Active Directory
# Check if we are running on a Domain Controller, exit if we aren't
$osInfo = Get-CimInstance -ClassName Win32_OperatingSystem
if ($osInfo.ProductType -ne 2) {
Write-Host "[Error] This needs to run on a Domain Controller."
exit 1
}
# Set ComplexityEnabled to what was passed into $ComplexityEnabled
Set-ADDefaultDomainPasswordPolicy -Identity $Domain -ComplexityEnabled $(if ($ComplexityEnabled) { $true }else { $false }) -Confirm:$false
# Sleep for a while, just in case Get-ADDefaultDomainPasswordPolicy connects to a different AD server and replication is slow
Start-Sleep -Seconds 60
# Check if the ComplexityEnabled policy was applied correctly
$Results = Get-ADDefaultDomainPasswordPolicy -Identity $Domain
# Check that the policy matches what was requested
if ($Results -and $Results.ComplexityEnabled -eq $ComplexityEnabled) {
Write-Host "[Info] Set Complexity in Default Domain Password Policy to $ComplexityEnabled"
return
}
else {
# The policy was not set for some reason
Write-Host "[Error] Failed to set Complexity in Default Domain Password Policy to $ComplexityEnabled"
exit 1
}
}
else {
# Localhost
# Check if the computer is domain joined
if ($(Test-DomainJoined)) {
Write-Host "[Error] This Computer is domain joined. Modifying the local policy is not supported for domain joined computers."
exit 1
}
# Set the path for our temp local policy config file
$Path = "$PSScriptRoot\Set-Password-Complexity-secpol.cfg"
# Get our local policy
SecEdit.exe /export /cfg $Path
if ($LASTEXITCODE -gt 0) {
Write-Host "[Error] Failed to read local machine Policy"
exit 1
}
# Next make sure that we are not changing something that does not need to be changed
# if $ComplexityEnabled is True and the temp local policy config file has PasswordComplexity set to 0, then proceed
if ($ComplexityEnabled -and $(Get-Content -Path $Path) -Match "^PasswordComplexity = 0$") {
# Change PasswordComplexity from 0 to 1
$(Get-Content -Path $Path) -Replace "PasswordComplexity = 0", "PasswordComplexity = 1" | Out-File $Path
# Update the local policy with our changes
SecEdit.exe /configure /db c:\windows\security\local.sdb /cfg $Path /areas SECURITYPOLICY
if ($LASTEXITCODE -gt 0) {
Write-Host "[Error] Failed to set Complexity in local machine Policy to $ComplexityEnabled"
exit 1
}
}# if $ComplexityEnabled is False and the temp local policy config file has PasswordComplexity set to 1, then proceed
elseif (-not $ComplexityEnabled -and $(Get-Content -Path $Path) -Match "^PasswordComplexity = 1$") {
# Change PasswordComplexity from 1 to 0
$(Get-Content -Path $Path) -Replace "PasswordComplexity = 1", "PasswordComplexity = 0" | Out-File $Path
# Update the local policy with our changes
SecEdit.exe /configure /db c:\windows\security\local.sdb /cfg $Path /areas SECURITYPOLICY
if ($LASTEXITCODE -gt 0) {
Write-Host "[Error] Failed to set Complexity in local machine Policy to $ComplexityEnabled"
exit 1
}
}
# Remove our temp local policy config file
Remove-Item $Path -Force
# Get our local policy
SecEdit.exe /export /cfg $Path
# Check if the temp local policy config file has PasswordComplexity set to match our $ComplexityEnabled
if (
($ComplexityEnabled -and $(Get-Content $Path) -Match "^PasswordComplexity = 1$") -or
(-not $ComplexityEnabled -and $(Get-Content $Path) -Match "^PasswordComplexity = 0$")
) {
# Remove our temp local policy config file again
Remove-Item $Path -Force
Write-Host "[Info] Set Complexity in local machine Policy to $ComplexityEnabled"
return
}
else {
# Remove our temp local policy config file again
Remove-Item $Path -Force
Write-Host "[Error] Failed to set Complexity in local machine Policy to $ComplexityEnabled"
exit 1
}
}
}
end {
}
Acesse mais de 300 scripts no NinjaOne Dojo
Detalhamento
- Requisitos iniciais: O script foi projetado para Windows 10 ou Windows Server 2016. Além disso, se o recurso Active Directory for usado, o RSAT para Active Directory deverá ser instalado.
- Parâmetros: O script aceita dois parâmetros opcionais:
- $ComplexityEnabled: Um switch que ativa ou desativa a complexidade da senha.
- $Domínio: Especifica o nome do domínio para o qual a política de senha será alterada.
- Verificação da elevação: Antes de qualquer ação, o script verifica se tem privilégios de administrador. Caso contrário, ele é encerrado, garantindo que as ações sejam executadas somente com as permissões corretas.
- Active Directory: Se um domínio for especificado, ele:
- Verifica se está sendo executado em um controlador de domínio.
- Valida a presença do módulo ActiveDirectory.
- Modifica a política de senha padrão do domínio com base no parâmetro $ComplexityEnabled.
- Política local: Se nenhum domínio for especificado, ele:
- Cria um arquivo temporário de configuração de política.
- Verifica a configuração atual de complexidade da senha.
- Modifica essa configuração com base no parâmetro $ComplexityEnabled.
Casos de uso em potencial
Estudo de caso: Imagine uma profissional de TI, Jane, trabalhando em uma organização que recentemente sofreu ataques de phishing. Sua equipe decide aplicar políticas de senha mais rígidas. Em vez de passar manualmente por cada sistema ou controlador de domínio, Jane usa esse script. Simplesmente executando-o com os parâmetros desejados, ela pode atualizar rapidamente as políticas de senha, melhorando assim a postura de segurança da organização.
Comparações
Tradicionalmente, a alteração das políticas de senha no Windows geralmente exigia a navegação por várias interfaces baseadas em GUI, como o Gerenciamento de Política de Grupo ou a Política de Segurança Local. Embora eficazes, esses métodos podem consumir muito tempo. Esse script do PowerShell simplifica o processo, proporcionando uma abordagem mais rápida e eficiente.
Implicações
Embora a automação das alterações na política de senhas possa agilizar os processos, é fundamental notificar os usuários sobre essas alterações. Mudanças repentinas na política de senhas podem gerar confusão e possíveis bloqueios, afetando a produtividade. Além disso, do ponto de vista da segurança de TI, a atualização regular e a aplicação de políticas de senha podem reduzir drasticamente o risco de acesso não autorizado.
Recomendações
- Sempre execute o script em um ambiente de teste antes de aplicá-lo em uma configuração ativa.
- Revise e ajuste regularmente as políticas de senha de acordo com as recomendações de segurança mais recentes.
- Eduque os usuários sobre a importância de senhas fortes e o motivo das mudanças de política.
Considerações finais
No contexto da segurança aprimorada de TI, ferramentas como o NinjaOne podem desempenhar um papel fundamental. Eles não apenas fornecem soluções de monitoramento, mas também se integram perfeitamente a scripts como o discutido. Ao usar o NinjaOne juntamente com essas ferramentas de automação, os profissionais de TI podem gerenciar e reforçar com eficiência as medidas de segurança de suas organizações.