Nesta postagem, forneceremos um script do PowerShell que os administradores de TI podem usar para montar e desmontar arquivos ISO dinamicamente.
Histórico
Os arquivos ISO, essencialmente uma cópia completa de um disco em formato digital, são amplamente usados para distribuir software(incluindo malware, infelizmente). Os profissionais de TI e os provedores de serviços gerenciados (MSPs) podem preferir bloquear a montagem de arquivos ISO em geral, ou podem se deparar com a necessidade de ativar ou desativar a montagem dessas imagens ISO dinamicamente, especialmente em sistemas corporativos. Esse script do PowerShell ajuda a controlar esse recurso com precisão, garantindo que a segurança e a adesão à política sejam cumpridas com elegância.
O roteiro
#Requires -Version 5.1
<#
.SYNOPSIS
Enables or disables the mounting of ISO images.
.DESCRIPTION
Enables or disables the mounting of ISO images.
.EXAMPLE
-Enable
Enables mounting of ISO images.
.EXAMPLE
-Disable
Disables mounting of ISO images.
.OUTPUTS
None
.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).
#>
[CmdletBinding()]
param (
[Parameter()]
[switch]
$Enable,
[Parameter()]
[switch]
$Disable
)
begin {
function Set-ItemProp {
param (
$Path,
$Name,
$Value,
[ValidateSet("DWord", "QWord", "String", "ExpandedString", "Binary", "MultiString", "Unknown")]
$PropertyType = "DWord"
)
# Do not output errors and continue
$ErrorActionPreference = [System.Management.Automation.ActionPreference]::SilentlyContinue
if (-not $(Test-Path -Path $Path)) {
# Check if path does not exist and create the path
New-Item -Path $Path -Force | Out-Null
}
if ((Get-ItemProperty -Path $Path -Name $Name)) {
# Update property and print out what it was changed from and changed to
$CurrentValue = Get-ItemProperty -Path $Path -Name $Name
try {
Set-ItemProperty -Path $Path -Name $Name -Value $Value -Force -Confirm:$false -ErrorAction Stop | Out-Null
}
catch {
Write-Error $_
}
Write-Host "$Path$Name changed from $CurrentValue to $(Get-ItemProperty -Path $Path -Name $Name)"
}
else {
# Create property with value
try {
New-ItemProperty -Path $Path -Name $Name -Value $Value -PropertyType $PropertyType -Force -Confirm:$false -ErrorAction Stop | Out-Null
}
catch {
Write-Error $_
}
Write-Host "Set $Path$Name to $(Get-ItemProperty -Path $Path -Name $Name)"
}
$ErrorActionPreference = [System.Management.Automation.ActionPreference]::Continue
}
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 ($env:Action -like "Enable") {
$Enable = $true
}
elseif ($env:Action -like "Disable") {
$Disable = $true
}
# Use a unique number that isn't likely to be used
# "ninja" to something close to a number plus 1 at the end: "41470" + "1"
$GroupName = "414701"
# Mount HKEY_CLASSES_ROOT as HKCR: for the current session
New-PSDrive -PSProvider registry -Root HKEY_CLASSES_ROOT -Name HKCR
if ($Enable -and $Disable) {
Write-Error "Both Enable and Disable can not be used at the same time."
exit 1
}
elseif ($Enable) {
# Enables the use of ISO mounting by removing registry settings
# ErrorAction set to SilentlyContinue for when the registry settings don't exist
Remove-ItemProperty -Path "HKLM:SOFTWAREPoliciesMicrosoftWindowsDeviceInstallRestrictionsDenyDeviceIDs" -Name "$GroupName" -ErrorAction SilentlyContinue
Write-Host "Removed $GroupName from HKLM:SOFTWAREPoliciesMicrosoftWindowsDeviceInstallRestrictionsDenyDeviceIDs"
Remove-ItemProperty -Path "HKLM:SOFTWAREPoliciesMicrosoftWindowsDeviceInstallRestrictions" -Name "DenyDeviceIDsRetroactive" -ErrorAction SilentlyContinue
Write-Host "Removed DenyDeviceIDsRetroactive from HKLM:SOFTWAREPoliciesMicrosoftWindowsDeviceInstallRestrictionsDenyDeviceIDs"
Remove-ItemProperty -Path "HKCR:Windows.IsoFileshellmount" -Name "ProgrammaticAccessOnly" -ErrorAction SilentlyContinue
Write-Host "Removed ProgrammaticAccessOnly from HKCR:Windows.IsoFileshellmount"
}
elseif ($Disable) {
# Disables the use of ISO mounting by creating registry settings
Set-ItemProp -Path "HKLM:SOFTWAREPoliciesMicrosoftWindowsDeviceInstallRestrictionsDenyDeviceIDs" -Name "$GroupName" -Value "SCSICdRomMsft____Virtual_DVD-ROM_" -PropertyType String
Set-ItemProp -Path "HKLM:SOFTWAREPoliciesMicrosoftWindowsDeviceInstallRestrictions" -Name "DenyDeviceIDsRetroactive" -Value "1" -PropertyType DWord
Set-ItemProp -Path "HKCR:Windows.IsoFileshellmount" -Name "ProgrammaticAccessOnly" -Value "" -PropertyType String
}
else {
Write-Error "Enable or Disable is required."
exit 1
}
Write-Host "Any logged in users will need to log out and back in for changes to take effect."
}
end {
$ScriptVariables = @(
[PSCustomObject]@{
name = "Action"
calculatedName = "action"
required = $true
defaultValue = [PSCustomObject]@{
type = "TEXT"
value = "Disable"
}
valueType = "DROPDOWN"
valueList = @(
[PSCustomObject]@{
type = "UNDEFINED"
value = "Disable"
},
[PSCustomObject]@{
type = "UNDEFINED"
value = "Enable"
}
)
description = "Used to enable or disable the mounting of ISO images."
}
)
}
Acesse mais de 300 scripts no NinjaOne Dojo
Detalhamento
O script fornecido foi projetado para alternar o recurso de montagem de imagens ISO. Vamos dissecar seus componentes:
- Parâmetros: O script aceita duas opções: $Enable e $Disable. Eles determinam o comportamento do script, ativando ou desativando a montagem do ISO.
- Função Set-ItemProp: Essa função interna lida com a criação ou modificação de uma propriedade de registro. Ele atende a diferentes tipos de propriedades, garantindo flexibilidade no gerenciamento das chaves do Registro do Windows.
- Função Test-IsElevated: Verifica se o script é executado com privilégios administrativos. Isso garante que as alterações sejam aplicadas em todo o sistema e não se limitem à sessão do usuário.
- Bloco de processo: O coração do roteiro. Aqui reside a lógica:
- Verifica os direitos administrativos.
- Determina a ação com base nos parâmetros ou variáveis de ambiente fornecidos.
- Remove (ativação) ou define (desativação) chaves de registro específicas para controlar o recurso de montagem de ISO.
Casos de uso em potencial
Considere um estudo de caso: O departamento de TI da Acme Corp envia uma atualização de software por meio de arquivos ISO para todos os sistemas dos funcionários. Após a conclusão da atualização, eles pretendem desativar temporariamente o recurso de montagem de ISO. Ao implementar esse script em toda a empresa, eles podem controlar essa funcionalidade, garantindo que ISOs não oficiais ou não sancionadas não sejam montadas por usuários curiosos.
Comparações
Embora a intervenção manual ou as ferramentas baseadas em GUI possam gerenciar as permissões de montagem ISO, elas são ineficientes para operações em grande escala. Nosso script oferece um método automatizado, sem complicações e robusto quando comparado a processos manuais demorados.
Implicações
O gerenciamento da capacidade de montar arquivos ISO pode ter profundas implicações de segurança. ISOs não autorizadas podem introduzir malware ou software indesejado. Com o controle desse recurso, os departamentos de TI podem garantir que somente ISOs sancionadas sejam montadas, reduzindo as possíveis ameaças.
Recomendações
- Sempre faça backup das configurações do registro antes de fazer alterações.
- Teste o script em um ambiente controlado antes da implementação em toda a empresa.
- Monitore os comportamentos do sistema após a implantação para identificar quaisquer resultados inesperados.
Considerações finais
Para plataformas como a NinjaOne, que atende a operações e gerenciamento de TI, scripts como esses são inestimáveis. Eles demonstram a versatilidade e o alinhamento da plataforma com as necessidades contemporâneas de TI. Ao utilizar essas ferramentas, os profissionais de TI podem aproveitar todo o potencial do PowerShell, tornando o gerenciamento do sistema eficiente e seguro.