PSSmb.psm1
Function Get-AvailableSmbVersion ($Session, $Version) { $sb = { Param($Version) $Version = [System.Collections.ArrayList]@($Version) $OsVersion = (Get-WmiObject Win32_OperatingSystem).Version $OsVersion -match '^\d+\.\d' | Out-Null [double]$OsVersion = $Matches[0] switch ($OsVersion) { {$_ -lt 6} { $Version.Remove(2) } {$_ -lt 6.2} { $Version.Remove(3) } } $Version } if ($Session) { Invoke-Command -ScriptBlock $sb -Session $Session -ArgumentList $Version, $null } else { & $sb $Version } } Function Get-Smb { <# .SYNOPSIS Get the status of SMB on local or remote computers .DESCRIPTION Get-Smb gets the status of SMB on local or remote computers, and returns an object reporting on both the client and the server components for each version installed on the system. Due to recent vulnerabilities, it is now recommended to disable SMB version 1, both the client and the server components, entirely. For more information, see Disable-Smb. .PARAMETER ComputerName The name of the computer to get the status of SMB from. Default is the local computer. .PARAMETER Session Specifies an array of sessions in which this command runs the command. Enter a variable that contains PSSession objects or a command that creates or gets the PSSession objects, such as a New-PSSession or Get-PSSession command. For more information, see about_PSSessions. .PARAMETER Version An array of integers corresponding to SMB versions to get the status of. Default is to retrieve all versions. .INPUTS System.String or System.Management.Automation.Runspaces.PSSession Get-Smb accepts either strings of computer names or PSSession objects. .OUTPUTS System.Management.Automation.PSCustomObject Get-Smb returns a PSCustomObject that details the client and server components for the requested SMB versions. .EXAMPLE PS C:> Get-Smb This command will get the status of the client and server components for all installed versions of SMB on the local computer. .EXAMPLE PS C:> Get-Smb -ComputerName server01 -Version 1 This command will get the status of the client and server components for SMB Version 1 on the computer named server01. .NOTES This command uses PowerShell Remoting to contact remote computers, and will not function if remote computers do not have it enabled. .LINK Invoke-Command .LINK Get-ItemProperty .LINK Add-Member #> [CmdletBinding(DefaultParameterSetName="ByName")] Param( [Parameter(ValueFromPipeline=$true,ParameterSetName="ByName")] [Alias("Cn")] [String[]]$ComputerName="$env:COMPUTERNAME", [Parameter(ValueFromPipeline=$true,ParameterSetName="BySession")] [System.Management.Automation.Runspaces.PSSession[]]$Session, [Parameter(Position=0)] [ValidateRange(1,3)] [Int[]]$Version=@(1,2,3) ) Begin { Function Get-SmbClientServerStatus ($Session, $Version) { $sb = { Param($Version) $SmbResult = New-Object PSCustomObject foreach ($num in $Version) { if ($num -eq 3) { $adjustedNum = 2 } else { $adjustedNum = $num } $ServerValue = (Get-ItemProperty -Path HKLM:\System\CurrentControlSet\services\LanmanServer\Parameters -Name "SMB$adjustedNum" -ea SilentlyContinue)."SMB$adjustedNum" $ClientValue = (Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\services\mrxsmb$($adjustedNum)0" -Name "Start" -ea SilentlyContinue).Start if ($ServerValue -eq 1 -or $ServerValue -eq $null) { $ServerEnabled = $true } else { $ServerEnabled = $false } if ($ClientValue -ne 4) { $ClientEnabled = $true } else { $ClientEnabled = $false } $SmbResult | Add-Member -MemberType NoteProperty -Name "SmbServerV$num" -Value $ServerEnabled $SmbResult | Add-Member -MemberType NoteProperty -Name "SmbClientV$num" -Value $ClientEnabled } $SmbResult } if ($Session) { Invoke-Command -ScriptBlock $sb -Session $Session -Args $Version, $null } else { & $sb $Version } } } Process { foreach ($computer in $ComputerName) { if ($PSCmdlet.ParameterSetName -eq "ByName") { if ($computer -eq $env:COMPUTERNAME -or $computer -eq "." -or $computer -eq "localhost") { $AvailableVersions = Get-AvailableSmbVersion -Version $Version Get-SmbClientServerStatus -Version $AvailableVersions } else { if (-not ($Session = New-PSSession -ComputerName $computer)) { continue } } } if ($Session) { foreach ($s in $Session) { $AvailableVersions = Get-AvailableSmbVersion -Session $s -Version $Version Get-SmbClientServerStatus -Session $s -Version $AvailableVersions if ($PSCmdlet.ParameterSetName -eq "ByName") { Remove-PSSession $s } } } } } } Function Disable-Smb { <# .SYNOPSIS Disables the client and server components of SMB. .DESCRIPTION Disable-Smb disables the SMB client and server components of the version specified in the Version parameter on local and remote computers. It is also important that the computer be rebooted for the settings made by this command to take effect which can be done immediately by using the Restart parameter. Note that versions 2 and 3 of SMB use the same stack, so disabling one of them also disables the other. Due to recent vulnerabilities like EternalBlue that was used by the WannaCry ransomware and the wiper PetyaWrap, it is now recommended to disable SMB version 1, both the client and the server components, entirely. .PARAMETER ComputerName The name of the computer to disable SMB on. Default is the local computer. .PARAMETER Session Specifies an array of sessions in which this command runs the command. Enter a variable that contains PSSession objects or a command that creates or gets the PSSession objects, such as a New-PSSession or Get-PSSession command. For more information, see about_PSSessions. .PARAMETER PassThru Returns objects representing the items that were changed. By default, this command does not generate any output. .PARAMETER Restart For the changes made by this command to take effect, the computer must be rebooted. Specifying this parameter will cause the computer to reboot immediately once the changes are made. .PARAMETER Version The version of SMB to disable. .INPUTS System.String or System.Management.Automation.Runspaces.PSSession Disable-Smb accepts either strings of computer names or PSSession objects. .OUTPUTS None or System.Management.Automation.PSCustomObject and System.ServiceProcess.ServiceController When you use the PassThru parameter, Disable-Smb returns a collection of objects representing the objects changed. Otherwise, this command does not generate any output. .EXAMPLE PS C:> Disable-Smb -Version 1 This command will disable the client and server components of SMB version 1 on the local computer. The computer will still need to be rebooted in order for the changes to take effect. .EXAMPLE PS C:> Disable-Smb -ComputerName server01 -Version 1 -Restart This command will disable the client and server components for SMB Version 1 on the computer named server01, and then immediately reboot the machine so that the settings can take effect. .NOTES This command uses PowerShell Remoting to contact remote computers, and will not function if remote computers do not have it enabled. Any computer that runs this command must be rebooted for the settings to take effect. It is recommended to use the Restart parameter to cause the machine to reboot as soon as the changes are made. .LINK Invoke-Command .LINK Set-ItemProperty .LINK Set-Service #> [CmdletBinding(DefaultParameterSetName="ByName",SupportsShouldProcess=$true)] Param( [Parameter(ValueFromPipeline=$true,ParameterSetName="ByName")] [Alias("Cn")] [String[]]$ComputerName="$env:COMPUTERNAME", [Switch]$PassThru, [Switch]$Restart, [Parameter(ValueFromPipeline=$true,ParameterSetName="BySession")] [System.Management.Automation.Runspaces.PSSession]$Session, [Parameter(Position=0,Mandatory=$true)] [ValidateRange(1,3)] [Int]$Version ) Begin { Function Set-SmbClientServerStatus ($Session, $Version, $PassThru) { $sb = { Param($Version, $PassThru) if ($Version -eq 3) { $adjustedNum = 2 } else { $adjustedNum = $Version } if ($adjustedNum -eq 1) { $dependNum = 2 } else { $dependNum = 1 } if ((Get-Service -Name "mrxsmb$($dependNum)0").StartType -ne "Disabled") { $Dependency = "Bowser","MRxSmb$($dependNum)0","NSI" } else { $Dependency = "Bowser", "NSI" } Set-ItemProperty -Path HKLM:\System\CurrentControlSet\services\LanmanServer\Parameters -Name "SMB$adjustedNum" -Type DWord -Value 0 -PassThru:$PassThru Set-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\services\LanmanWorkstation -Name DependOnService -Type MultiString -Value $Dependency -PassThru:$PassThru Set-Service -Name "mrxsmb$($adjustedNum)0" -StartupType Disabled -PassThru:$PassThru } if (!$Version) { return } if ($Session) { Invoke-Command -ScriptBlock $sb -Session $Session -Args $Version, $PassThru } else { & $sb -Version $Version -PassThru $PassThru } } } Process { foreach ($computer in $ComputerName) { if ($PSCmdlet.ParameterSetName -eq "ByName") { if ($computer -eq $env:COMPUTERNAME -or $computer -eq "." -or $computer -eq "localhost") { $AvailableVersion = Get-AvailableSmbVersion -Version $Version Set-SmbClientServerStatus -Version $AvailableVersion -PassThru $PassThru if ($Restart) { Restart-Computer -Force } } else { if (-not ($Session = New-PSSession -ComputerName $computer)) { continue } } } if ($Session) { foreach ($s in $Session) { $AvailableVersion = Get-AvailableSmbVersion -Session $s -Version $Version Set-SmbClientServerStatus -Session $s -Version $AvailableVersion -PassThru $PassThru if ($Restart) { Restart-Computer -ComputerName $s.ComputerName -Force } if ($PSCmdlet.ParameterSetName -eq "ByName") { Remove-PSSession $s -ea SilentlyContinue } } } } } } Function Enable-Smb { <# .SYNOPSIS Enables the client and server components of SMB. .DESCRIPTION Enable-Smb enables the SMB client and server components of the version specified in the Version parameter on local and remote computers. It is also important that the computer be rebooted for the settings made by this command to take effect which can be done immediately by using the Restart parameter. Note that versions 2 and 3 of SMB use the same stack, so enabling one of them also enables the other. Due to recent vulnerabilities, it is now recommended to disable SMB version 1, both the client and the server components, entirely. .PARAMETER ComputerName The name of the computer to enable SMB on. Default is the local computer. .PARAMETER Session Specifies an array of sessions in which this command runs the command. Enter a variable that contains PSSession objects or a command that creates or gets the PSSession objects, such as a New-PSSession or Get-PSSession command. For more information, see about_PSSessions. .PARAMETER PassThru Returns objects representing the items that were changed. By default, this command does not generate any output. .PARAMETER Restart For the changes made by this command to take effect, the computer must be rebooted. Specifying this parameter will cause the computer to reboot immediately once the changes are made. .PARAMETER Version The version of SMB to enable. .INPUTS System.String or System.Management.Automation.Runspaces.PSSession Enable-Smb accepts either strings of computer names or PSSession objects. .OUTPUTS None or System.Management.Automation.PSCustomObject and System.ServiceProcess.ServiceController When you use the PassThru parameter, Enable-Smb returns a collection of objects representing the objects changed. Otherwise, this command does not generate any output. .EXAMPLE PS C:> Enable-Smb -Version 1 This command will enable the client and server components of SMB version 1 on the local computer. The computer will still need to be rebooted in order for the changes to take effect. .EXAMPLE PS C:> Enable-Smb -ComputerName server01 -Version 1 -Restart This command will enable the client and server components for SMB Version 1 on the computer named server01, and then immediately reboot the machine so that the settings can take effect. .NOTES This command uses PowerShell Remoting to contact remote computers, and will not function if remote computers do not have it enabled. Any computer that runs this command must be rebooted for the settings to take effect. It is recommended to use the Restart parameter to cause the machine to reboot as soon as the changes are made. .LINK Invoke-Command .LINK Set-ItemProperty .LINK Set-Service #> [CmdletBinding(DefaultParameterSetName="ByName",SupportsShouldProcess=$true)] Param( [Parameter(ValueFromPipeline=$true,ParameterSetName="ByName")] [Alias("Cn")] [String[]]$ComputerName="$env:COMPUTERNAME", [Switch]$PassThru, [Switch]$Restart, [Parameter(ValueFromPipeline=$true,ParameterSetName="BySession")] [System.Management.Automation.Runspaces.PSSession]$Session, [Parameter(Position=0,Mandatory=$true)] [ValidateRange(1,3)] [Int]$Version ) Begin { Function Set-SmbClientServerStatus ($Session, $Version, $PassThru) { $sb = { Param($Version, $PassThru) if ($Version -eq 3) { $adjustedNum = 2 } else { $adjustedNum = $Version } if ($adjustedNum -eq 1) { $dependNum = 2 } else { $dependNum = 1 } if ((Get-Service -Name "mrxsmb$($dependNum)0").StartType -ne "Disabled") { $Dependency = "Bowser","MRxSmb$($dependNum)0","MRxSmb$($adjustedNum)0","NSI" } else { $Dependency = "Bowser","MRxSmb$($adjustedNum)0", "NSI" } Set-ItemProperty -Path HKLM:\System\CurrentControlSet\services\LanmanServer\Parameters -Name "SMB$adjustedNum" -Type DWord -Value 1 -PassThru:$PassThru Set-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\services\LanmanWorkstation -Name DependOnService -Type MultiString -Value $Dependency -PassThru:$PassThru Set-Service -Name "mrxsmb$($adjustedNum)0" -StartupType Automatic -PassThru:$PassThru } if (!$Version) { return } if ($Session) { Invoke-Command -ScriptBlock $sb -Session $Session -Args $Version, $PassThru } else { & $sb -Version $Version -PassThru $PassThru } } } Process { foreach ($computer in $ComputerName) { if ($PSCmdlet.ParameterSetName -eq "ByName") { if ($computer -eq $env:COMPUTERNAME -or $computer -eq "." -or $computer -eq "localhost") { $AvailableVersion = Get-AvailableSmbVersion -Version $Version Set-SmbClientServerStatus -Version $AvailableVersion -PassThru $PassThru if ($Restart) { Restart-Computer -Force } } else { if (-not ($Session = New-PSSession -ComputerName $computer)) { continue } } } if ($Session) { foreach ($s in $Session) { $AvailableVersion = Get-AvailableSmbVersion -Session $s -Version $Version Set-SmbClientServerStatus -Session $s -Version $AvailableVersion -PassThru $PassThru if ($Restart) { Restart-Computer -ComputerName $s.ComputerName -Force } if ($PSCmdlet.ParameterSetName -eq "ByName") { Remove-PSSession $s -ea SilentlyContinue } } } } } } Function Disable-SmbByGpo { <# .SYNOPSIS Disables SMB by setting Group Policy .DESCRIPTION Disable-SmbByGpo disables SMB version 1 specifically by setting Group Policy registry preferences. By default, it creates a GPO named "Disable SMB Version 1" in the domain of the user running the command, and links it to the domain's root which covers all of the computers in the domain. These can be changed using the Name, Domain, and Target parameters. Please, see the full help for a more detailed look at what each parameter does and requires. It is recommended to reboot all the computers this new GPO will apply to as soon as possible, since a reboot is required for the changes to take effect. Due to recent vulnerabilities, it is now recommended to disable SMB version 1, both the client and the server components, entirely. .PARAMETER Domain Specifies the domain for this cmdlet. You must specify the fully qualified domain name (FQDN) of the domain (for example: sales.contoso.com). -- The GPO to link from must exist in this domain. -- The Active Directory container to link to must exist in a domain that has a trust relationship with this domain. Note: To specify a domain to link to, use the Target parameter. If you do not specify the Domain parameter, the domain of the user that is running the current session is used. If you specify a domain that is different from the domain of the user that is running the current session, a trust must exist between that domain and the domain of the user (or the computer). You can also refer to Domain by its built-in alias, "DomainName". For more information, see about_Aliases. .PARAMETER Enforced Specifies whether the GPO link is enforced. You can specify Yes or No. By default, GPO links are not enforced. By setting the GPO link to enforced, you ensure the following: -- That the settings of the GPO cannot be blocked (by blocking inheritance) at a lower-level Active Directory container. -- That the settings of the GPO always take precedence over conflicting settings in GPOs that are linked to lower-level containers. This option should be used sparingly. Casual use of this option complicates troubleshooting. The following values are permitted for this object type: Unspecified No Yes .PARAMETER LinkEnabled Specifies whether the GPO link is enabled. You can specify Yes or No. By default, Group Policy processing is enabled for all GPO links. You can completely block the application of a GPO for a specific site, domain, or OU by disabling the GPO link for that site, domain, or OU. Disabling a GPO link does not disable the GPO itself. If the GPO is linked to other sites, domains, or OUs, Group Policy continues to process the GPO for each link that is enabled. The following values are permitted for this object type. Unspecified No Yes .PARAMETER Name Assigns a display name to the new GPO. If another GPO with the same display name exists in the domain an error occurs. You can also refer to the Name parameter by its built-in alias, "DisplayName". For more information, see about_Aliases. .PARAMETER Order Specifies the link order for the GPO link. You can specify a number that is between one and the current number of GPO links to the target site, domain, or OU, plus one. The link order specifies the order of precedence with which GPOs linked to the same Active Directory container are applied. When Group Policy is processed, GPOs with a higher link order number are processed before GPOs with a lower link order number. Therefore, when two GPOs contain conflicting settings, the settings in the GPO with the lower link order number, because it is processed last, overwrites those of the GPO with the higher link order number. A lower number indicates higher precedence. By default, the GPO link is added at the lowest precedence (with a link order equal to the number of GPO links to the container, plus one). Link order is a dynamic value because the value may change as GPO links are added and deleted from the container. You can change the link order of a GPO link with the Set-GPLink cmdlet. .PARAMETER Server Specifies the name of the domain controller that this cmdlet contacts to complete the operation. You can specify either the fully qualified domain name (FQDN) or the host name. For example: FQDN: DomainController1.sales.contoso.com Host Name: DomainController1 If you do not specify the name by using the Server parameter, the PDC emulator is contacted. You can also refer to the Server parameter by its built-in alias, "dc". For more information, see about_Aliases. .PARAMETER Target Specifies the LDAP distinguished name of the site, domain, or OU to which to link the GPO. For example, for the "MyOU" organizational unit in the contoso.com domain, the LDAP distinguished name is "ou=MyOU,dc=contoso,dc=com". By default this parameter uses the distinguished name of the FQDN passed to the Domain parameter. .INPUTS None Disable-SmbByGpo does not accept pipeline input. .OUTPUTS None Disable-SmbByGpo does not produce any output. .EXAMPLE PS C:> Disable-SmbByGpo This command will use the PDC emulator to add the GPO object named "Disable SMB Version 1" in the command user's domain, and link the GPO to the domain root. .EXAMPLE PS C:> Disable-SmbByGpo -Domain sub.example.com -Name "SMBv1 Disabled" -Target OU=Lockdown,DC=sub,DC=example,DC=com -Server dc2 This command will use the domain controller dc2 to add the GPO object named "SMBv1 Disabled" to the domain sub.example.com, and link the GPO to the Organizational Unit named "Lockdown" located in that domain. .NOTES This command requires use of the GroupPolicy module that is available on Windows Server 2008 R2 or higher domain controllers or Windows Server 2008 R2/Windows 7 or higher member computers with the Remote Server Administration Tools (RSAT) installed. If this module is not installed, the command will not work. Unlike other commands in this module, Disable-SmbByGpo targets version 1 directly due to the fact that recent tools utilizing vulnerabilities in version 1 have caused widespread damage globally, and it is now recommended to disable SMB version 1 entirely if an organization can do so. .LINK New-GPO .LINK Set-GpPrefRegistryValue .LINK New-GPLink #> [CmdletBinding(SupportsShouldProcess=$true)] Param( [Alias("DomainName")] [String]$Domain=$env:USERDNSDOMAIN, [ValidateSet("Yes","No","Unspecified")] [String]$Enforced, [ValidateSet("Yes","No","Unspecified")] [String]$LinkEnabled, [Parameter(Position=0)] [Alias("DisplayName")] [String]$Name='Disable SMB Version 1', [Int]$Order, [Alias("DC")] [String]$Server, [Parameter(Position=1)] [String]$Target ) #Function to test for module installation and successful load. Thank you to Hey, Scripting Guy! blog for this one. Function Test-Module { Param ( [Parameter(Mandatory=$true, Position=0)][String]$Name ) #Test for module imported if (!(Get-Module -Name $Name)) { #Test for module availability if (Get-Module -ListAvailable | Where-Object {$_.Name -eq $Name}) { #If not loaded but available, import module Import-Module $Name $True } #Module not installed else {$False} } #Module already imported else {$True} } #Check for Group Policy module if (-not (Test-Module -Name GroupPolicy)) { Write-Error "The Group Policy module is not installed. You need to be on a Windows Server 2008 R2 or higher domain controller, or a Windows Server 2008 R2/Windows 7 or higher member computer that has the RSAT installed." exit } #If the Target parameter is blank convert it to the Domain parameter's distinguished name if (-not $Target) { $Target = ( -join ($Domain -split '\.' | ForEach-Object { "dc=$_," })).TrimEnd([char]",") } $NewGpoParam = @{} switch ("Name","Domain","Server") { { (Get-Variable $_ -ea SilentlyContinue).Value } { $NewGpoParam.$_ = (Get-Variable $_).Value } } $Gpo = New-GPO @NewGpoParam -Comment "This GPO was added by the PowerShell module PSSmb." if (!$?) { exit } $RootKeyPath = "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services" #Server param for Get-GPPrefRegistryValue commands $ServerParam = @{} if ($Server) { $ServerParam.Server = $Server } #Turn off SMB Server version 1 registry preference $Gpo | Set-GPPrefRegistryValue -Action Create -Context Computer -Key "$RootKeyPath\LanmanServer\Parameters" -ValueName SMB1 -Type DWord -Value 0 @ServerParam | Out-Null #Remove SMB version 1 dependency registry preference $Gpo | Set-GPPrefRegistryValue -Action Replace -Context Computer -Key "$RootKeyPath\LanmanWorkstation" -ValueName DependOnService -Type MultiString -Value ("Bowser","MRxSmb20","NSI") @ServerParam | Out-Null #Turn off SMB Client version 1 registry preference $Gpo | Set-GPPrefRegistryValue -Action Update -Context Computer -Key "$RootKeyPath\mrxsmb10" -ValueName Start -Type DWord -Value 4 @ServerParam | Out-Null $NewLinkParam = @{} switch ("Server","Target","LinkEnabled","Enforced","Order") { { (Get-Variable $_ -ea SilentlyContinue).Value } { $NewLinkParam.$_ = (Get-Variable $_).Value } } #Add Link $Gpo | New-GPLink @NewLinkParam | Out-Null if (!$?) { $Gpo | Remove-GPO } } New-Alias -Name gsmb -Value Get-Smb New-Alias -Name dsmb -Value Disable-Smb New-Alias -Name esmb -Value Enable-Smb New-Alias -Name dsgp -Value Disable-SmbByGpo |