Remove Azure Hybrid Connection objects


There is currently no cmdlet to easily remove an Azure Hybrid Connection object (from an App Service Plan).
So in a case you need to remove several connection objects, doing it from the protal is tedious.

This is why I created the following script:

# Login to Azure
Login-AzureRmAccount
# Select a specific subscription for the context
Get-AzureRmSubscription | Out-GridView -PassThru -Title 'Select Subscription' | Select-AzureRmSubscription
# Get all the Hybrid Connections from all namespaces in all resource groups
$hybridConnections = Get-AzureRmResource -ResourceType Microsoft.Relay/namespaces | ForEach-Object {
$resourceGroupName = $_.ResourceGroupName
Get-AzureRmRelayHybridConnection -ResourceGroupName $resourceGroupName -Namespace $namespace.Name | ForEach-Object {
$resourceName = '{0}/{1}' -f ($_.Id -split '/')[-3,-1]
Get-AzureRmResource -ResourceGroupName $resourceGroupName -ResourceType Microsoft.Relay/Namespaces/HybridConnections `
-ApiVersion 2016-07-01 -ResourceName $resourceName | Select-Object @{N='ResourceGroupName';E={$resourceGroupName}},
@{N='ResourceName';E={$resourceName}},
@{N='CreatedAt';E={$_.Properties.createdAt}},
@{N='UpdatedAt';E={$_.Properties.updatedAt}},
@{N='ListenerCount';E={$_.Properties.listenerCount}},
@{N='UserMetadata';E={$_.Properties.userMetadata}}
}
}
# Ask which connection to delete
$hybridConnections | Out-GridView -PassThru -Title 'Select the Hybrid Connections you want to delete' | ForEach-Object {
Remove-AzureRmResource -ResourceGroupName $resourceGroupName -ResourceType Microsoft.Relay/Namespaces/HybridConnections `
-ApiVersion 2016-07-01 -ResourceName $_.ResourceName -Force
}

HTH,
Martin.

Set the minimum TLS version to 1.2 on your AzureRM AppServices


There is currently no cmdlet to easily set the minimum TLS version on an Azure App Service. But it can be accomplished by calling the Set-AzureRMResource cmdlet with the relevant parameters

# Login to Azure
Add-AzureRmAccount
# Iterate all sites and set the Minimum TLS version to 1.2 (SSL Settings)
Get-AzureRmResource -ResourceType Microsoft.Web/sites | ForEach-Object {
$params = @{
ApiVersion = '2018-02-01'
ResourceName = '{0}/web' -f $_.Name
ResourceGroupName = $_.ResourceGroupName
PropertyObject = @{ minTlsVersion = 1.2 }
ResourceType = 'Microsoft.Web/sites/config'
}
Set-AzureRmResource @params -Force
}

HTH,
Martin.

Disabling the Scripting.FileSystemObject ComObject (When you get the 0x8002801c error)


While working with a customer to automate the hardening process (STIG: Security Technical Implementation Guide) for IIS servers, we ran into a problem (error 0x8002801c) when we tried to run the following command in order to disable (unregister) the Scripting.FileSystemObject ComObject

C:\Windows\System32\regsvr32.exe /u scrrun.dll

The 0x8002801c error translates to TYPE_E_REGISTRYACCESS. Using Sysinternal’s Process Monitor (aka procmon), we found that it was failing because of missing permissions to the following registry keys:

HKEY_CLASSES_ROOT\TypeLib\{420B2830-E718-11CF-893D-00A0C9054228}\1.0\0\win32
HKEY_CLASSES_ROOT\Scripting.FileSystemObject\CLSID

Note that adding permissions to the first key only (as suggested in Finding V-13700 @ stigviewer.com) is not enough. The command would run without errors, the validation would pass (thinking that FSO is disabled) but you could still create and use FSO objects.

So for automating the whole process, we needed to take ownership on the registry keys, add permissions to the keys, and then run the command to unregister the DLL.

This results in the following code:

#region Helper functions
function Set-Ownership {
[CmdletBinding(SupportsShouldProcess = $false)]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$Path,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()] [ValidatePattern('(\w+)\\(\w+)')]
[string]$Identity,
[Parameter(Mandatory = $false)]
[switch]$AddFullControl,
[Parameter(Mandatory = $false)]
[switch]$Recurse
)
begin {
$tokenManipulate = @'
using System;
using System.Runtime.InteropServices;
public class TokenManipulate {
[DllImport("kernel32.dll", ExactSpelling = true)]
internal static extern IntPtr GetCurrentProcess();
[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall, ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);
[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);
[DllImport("advapi32.dll", SetLastError = true)]
internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct TokPriv1Luid {
public int Count;
public long Luid;
public int Attr;
}
internal const int SE_PRIVILEGE_DISABLED = 0x00000000;
internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
internal const int TOKEN_QUERY = 0x00000008;
internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
public static bool AddPrivilege(string privilege) {
bool retVal;
TokPriv1Luid tp;
IntPtr hproc = GetCurrentProcess();
IntPtr htok = IntPtr.Zero;
retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
tp.Count = 1;
tp.Luid = 0;
tp.Attr = SE_PRIVILEGE_ENABLED;
retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);
retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
return retVal;
}
public static bool RemovePrivilege(string privilege) {
bool retVal;
TokPriv1Luid tp;
IntPtr hproc = GetCurrentProcess();
IntPtr htok = IntPtr.Zero;
retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
tp.Count = 1;
tp.Luid = 0;
tp.Attr = SE_PRIVILEGE_DISABLED;
retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);
retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
return retVal;
}
}
'@
}
Process {
Add-Type -TypeDefinition $TokenManipulate
[void][TokenManipulate]::AddPrivilege('SeTakeOwnershipPrivilege')
[void][TokenManipulate]::AddPrivilege('SeRestorePrivilege')
$item = Get-Item -Path $Path -ErrorAction SilentlyContinue
if(-not $item) {
Write-Warning ("'{0}' not found" -f $Path)
return
}
$owner = New-Object System.Security.Principal.NTAccount -ArgumentList ($Identity -split '\\')
if ($item.PSIsContainer) {
switch ($item.PSProvider.Name) {
'FileSystem' {
$acl = New-Object -TypeName System.Security.AccessControl.DirectorySecurity
}
'Registry' {
$acl = New-Object -TypeName System.Security.AccessControl.RegistrySecurity
switch (($item.Name -split '\\')[0]) {
'HKEY_CLASSES_ROOT' { $rootKey = [Microsoft.Win32.Registry]::ClassesRoot; break }
'HKEY_LOCAL_MACHINE' { $rootKey = [Microsoft.Win32.Registry]::LocalMachine; break }
'HKEY_CURRENT_USER' { $rootKey = [Microsoft.Win32.Registry]::CurrentUser; break }
'HKEY_USERS' { $rootKey = [Microsoft.Win32.Registry]::Users; break }
'HKEY_CURRENT_CONFIG' { $rootKey = [Microsoft.Win32.Registry]::CurrentConfig; break }
}
$key = $item.Name -replace "$rootKey\\"
$item = $rootKey.OpenSubKey($Key, [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree,
[System.Security.AccessControl.RegistryRights]::TakeOwnership)
}
}
Write-Verbose "Setting ownership for $($owner.Value) on $Path"
$acl.SetOwner($owner)
$item.SetAccessControl($acl)
if($AddFullControl) {
$ace = New-Object -TypeName System.Security.AccessControl.RegistryAccessRule -ArgumentList @(
$owner, [System.Security.AccessControl.RegistryRights]::FullControl,
[System.Security.AccessControl.InheritanceFlags]::None,
[System.Security.AccessControl.PropagationFlags]::None,
[System.Security.AccessControl.AccessControlType]::Allow
)
Write-Verbose "Setting FullControl permissions for $($owner.Value) on $Path"
$acl.AddAccessRule($ace)
$item.SetAccessControl($acl)
}
if ($item.PSProvider.Name -eq 'Registry') { $item.Close() }
if ($Recurse.IsPresent) {
if ($item.PSProvider.Name -eq 'Registry') {
$items = @(Get-ChildItem -Path $Path -Recurse -Force | Where-Object { $_.PSIsContainer })
}
else {
$items = @(Get-ChildItem -Path $Path -Recurse -Force)
}
for ($i = 0; $i -lt $items.Count; $i++) {
switch ($item.PSProvider.Name) {
'FileSystem' {
$item = Get-Item $items[$i].FullName
if ($item.PSIsContainer) { $acl = New-Object -TypeName System.Security.AccessControl.DirectorySecurity }
else { $acl = New-Object -TypeName System.Security.AccessControl.FileSecurity }
}
'Registry' {
$item = Get-Item $items[$i].PSPath
$acl = New-Object -TypeName System.Security.AccessControl.RegistrySecurity
switch ($item.Name.Split('\')[0]) {
'HKEY_CLASSES_ROOT' { $rootKey = [Microsoft.Win32.Registry]::ClassesRoot; break }
'HKEY_LOCAL_MACHINE' { $rootKey = [Microsoft.Win32.Registry]::LocalMachine; break }
'HKEY_CURRENT_USER' { $rootKey = [Microsoft.Win32.Registry]::CurrentUser; break }
'HKEY_USERS' { $rootKey = [Microsoft.Win32.Registry]::Users; break }
'HKEY_CURRENT_CONFIG' { $rootKey = [Microsoft.Win32.Registry]::CurrentConfig; break }
}
$Key = $item.Name.Replace(($item.Name.Split('\')[0] + '\'), '')
$item = $rootKey.OpenSubKey($Key, [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree,
[System.Security.AccessControl.RegistryRights]::TakeOwnership)
}
}
$acl.SetOwner($owner)
Write-Verbose "Setting ownership for $($owner.Value) on $($item.Name)"
$item.SetAccessControl($acl)
if ($item.PSProvider.Name -eq 'Registry') { $item.Close() }
}
}
}
else {
if ($Recurse.IsPresent) { Write-Warning 'Object specified is neither a folder nor a registry key. Recursion is not possible.' }
switch ($item.PSProvider.Name) {
'FileSystem' { $acl = New-Object -TypeName System.Security.AccessControl.FileSecurity }
'Registry' { Write-Error 'You cannot set ownership on a registry value' }
default { Write-Error "Unknown provider: $($item.PSProvider.Name)" }
}
$acl.SetOwner($owner)
Write-Verbose "Setting ownership for $($owner.Value) on $Path"
$item.SetAccessControl($acl)
}
}
}
#endregion
#region Test FileSystemObject ComObject (Should work)
(New-Object -ComObject Scripting.FileSystemObject).Drives
#endregion
#region Set ownership and add permissions to the relevant registry keys
$regPaths = @(
'Registry::HKEY_CLASSES_ROOT\TypeLib\{420B2830-E718-11CF-893D-00A0C9054228}\1.0\0\win32'
'Registry::HKEY_CLASSES_ROOT\TypeLib\{420B2830-E718-11CF-893D-00A0C9054228}\1.0\0\win64'
'Registry::HKEY_CLASSES_ROOT\TypeLib\{420B2830-E718-11CF-893D-00A0C9054228}\1.0\0'
'Registry::HKEY_CLASSES_ROOT\TypeLib\{420B2830-E718-11CF-893D-00A0C9054228}\1.0\FLAGS'
'Registry::HKEY_CLASSES_ROOT\TypeLib\{420B2830-E718-11CF-893D-00A0C9054228}\1.0\HELPDIR'
'Registry::HKEY_CLASSES_ROOT\TypeLib\{420B2830-E718-11CF-893D-00A0C9054228}\1.0'
'Registry::HKEY_CLASSES_ROOT\TypeLib\{420B2830-E718-11CF-893D-00A0C9054228}'
)
foreach($regPath in $regPaths) {
Set-Ownership -Path $regPath -Identity 'BUILTIN\Administrators' -AddFullControl -Recurse -Verbose
}
#endregion
#region unregister the FileSystemObject scrrun dll
C:\Windows\System32\regsvr32.exe scrrun.dll /u /s
#endregion
#region Test FileSystemObject ComObject (Should fail)
(New-Object -ComObject Scripting.FileSystemObject).Drives
#endregion

HTH,
Martin.

Add permissions to a Session Configuration


Though the recommended approach would be to upgrade to PowerShell 5.1 and implement JEA (preferable with DSC and the JEA DSC module), there sometimes might be a need to programmatically add permissions to a PowerShell session configuration.

Continuing the mentioned above, and a question asked on the reddit forum, below is an example on how to add a specific permission (ACE) to the configuration session permissions (ACL):

# The identity to add permissions for
$Identity = "myDomain\nonAdmins"
# The configuration name to change permissions to (default is 'microsoft.powershell')
$sessionConfigurationName = 'microsoft.powershell'
# Get the current permissions on the default endpoint
$sddl = (Get-PSSessionConfiguration -Name $sessionConfigurationName).SecurityDescriptorSddl
# Build the new Access Control Entry object
$rights = -1610612736 # AccessAllowed
$IdentitySID = ((New-Object -TypeName System.Security.Principal.NTAccount -ArgumentList $Identity).Translate(
[System.Security.Principal.SecurityIdentifier])).Value
$newAce = New-Object System.Security.AccessControl.CommonAce(
[System.Security.AccessControl.AceFlags]::None,
[System.Security.AccessControl.AceQualifier]::AccessAllowed,
$rights, $IdentitySID, $false, $null
)
# Prepare the RawSecurityDescriptor
$rawSD = New-Object -TypeName System.Security.AccessControl.RawSecurityDescriptor -ArgumentList $sddl
if ($rawSD.DiscretionaryAcl.GetEnumerator() -notcontains $newAce) {
$rawSD.DiscretionaryAcl.InsertAce($rawSD.DiscretionaryAcl.Count, $newAce)
}
$newSDDL = $rawSD.GetSddlForm([System.Security.AccessControl.AccessControlSections]::All)
# Set the PSSessionConfiguration permissions
Set-PSSessionConfiguration -Name $sessionConfigurationName -SecurityDescriptorSddl $newSDDL
# Verify permissions were added
(Get-PSSessionConfiguration -Name $sessionConfigurationName).Permission -split ', '

HTH,
Martin.

Remove Profiles from a local or remote computer


A common need for a Remote Desktop Services (RDS) and/or Citrix farm admin, is to remove local profiles from a server.
Another example for this, is the question posted a few days ago in the PowerShell.org forum here.

Funny thing, about 6 years ago, I wrote a vbscript that does that. It just doesn’t filter by last used date.

Anyway, I decided to write the Remove-Profile PowerShell function:

#requires -version 3
function Remove-Profile {
param(
[string[]]$ComputerName = $env:ComputerName,
[pscredential]$Credential = $null,
[string[]]$Name,
[ValidateRange(0,365)][int]$DaysOld = 0,
[string[]]$Exclude,
[switch]$IgnoreLastUseTime,
[switch]$Remove
)
$ComputerName | ForEach-Object {
if(Test-Connection -ComputerName $_ -BufferSize 16 -Count 2 -Quiet) {
$params = @{
ComputerName = $_
Namespace = 'root\cimv2'
Class = 'Win32_UserProfile'
}
if($Credential -and (@($env:ComputerName,'localhost','127.0.0.1','::1','.') -notcontains $_)) {
$params.Add('Credential', $Credential)
}
if($null -ne $Name) {
if($Name.Count -gt 1) {
$params.Add('Filter', ($Name | % { "LocalPath = '{0}'" -f $_ }) -join ' OR ')
} else {
$params.Add('Filter', "LocalPath LIKE '%{0}'" -f ($Name -replace '\*', '%'))
}
}
Get-WmiObject @params | ForEach-Object {
$WouldBeRemoved = $false
if(($_.SID -notin @('S-1-5-18', 'S-1-5-19', 'S-1-5-20')) -and
((Split-Path -Path $_.LocalPath -Leaf) -notin $Exclude) -and (-not $_.Loaded) -and ($IgnoreLastUseTime -or (
($_.LastUseTime) -and (([WMI]'').ConvertToDateTime($_.LastUseTime)) -lt (Get-Date).AddDays(-1*$DaysOld)))) {
$WouldBeRemoved = $true
}
$prf = [pscustomobject]@{
PSComputerName = $_.PSComputerName
Account = (New-Object System.Security.Principal.SecurityIdentifier($_.Sid)).Translate([System.Security.Principal.NTAccount]).Value
LocalPath = $_.LocalPath
LastUseTime = if($_.LastUseTime) { ([WMI]'').ConvertToDateTime($_.LastUseTime) } else { $null }
Loaded = $_.Loaded
}
if(-not $Remove) {
$prf | Select-Object -Property *, @{N='WouldBeRemoved'; E={$WouldBeRemoved}}
}
if($Remove -and $WouldBeRemoved) {
try {
$_.Delete()
$Removed = $true
} catch {
$Removed = $false
Write-Error -Exception $_
}
finally {
$prf | Select-Object -Property *, @{N='Removed'; E={$Removed}}
}
}
}
} else {
Write-Warning -Message "Computer $_ is unavailable"
}
}
}

You can use it to report all the profiles in the local computer:

Remove-Profile

To report all the profiles, except a specific profile:

Remove-Profile -Exclude Administrator

To report profiles last used in the past 90 days that would be deleted:

Remove-Profile -DaysOld 90 | Where-Object { $_.WouldBeRemoved }

To report against a remote computer:

Remove-Profile -ComputerName myRemoteServer

To report against a collection of remote computers, authenticating different credentials:

Remove-Profile -ComputerName $Computers -Credential $cred -DaysOld 90

To ignore the LastUseTime value in case the account never logged-on locally (e.g. an IIS ApplicationPool), use the IgnoreLastUseTime switch:

Remove-Profile -ComputerName WebServer01 -DaysOld 30 -IgnoreLastUseTime 

To really remove the profiles, use the -Remove switch:

Remove-Profile -DaysOld 90 -Remove

HTH,
Martin.