Creating symbolic links with PowerShell DSC


Background

In an Azure Windows VM you automatically get a temporary disk drive mapped to D: (on Linux it’s mapped to /dev/sdb1). It is temporary because the storage is assigned from the local storage on the physical host. So if your VM is re-deployed (due to host updates, host failures, resizing, etc.), the VM is recreated on a new host and the VM will be assigned a new temporary drive on the new host. The data on the temporary drive is not migrated, but the OS disk is obviously preserved from the vhd in your storage account or managed-disk.

The problem

In this specific scenario, the customer had a 3rd party legacy application that reads and writes from two directories in the D:\ drive. The directories paths were hard-coded in the application and were a couple of gigabytes in size, so copying them to the temporary drive each time the VMs were deployed would be time and resource consuming.

Choosing a solution

After thorough testing of course, we decided to create two symbolic links from the D:\ drive to the real directories in the OS disk (where the directories were already present as part of the image). The symbolic-links creation would be accomplished with either the mklink command, or with the New-Item cmdlet in PowerShell 5.x.

Of course there are other methods overcoming this challenge, such as switching the drive letters with a data-disk and moving the PageFile to the other drive letter. But we decided that the symbolic-links approach would be faster and wouldn’t require an additional data-disk, and with it, additional costs.

The implementation

Since the creation of the symbolic-links would need to happen every time the VM is created (and redeployed), we ended up adding a PowerShell DSC extension to the VM in the ARM template and since there were no built-in DSC Resources in the OS, nor in the DSC Resource Kit in the PowerShell gallery that configures symbolic-links, we wrote a (quick-and-dirty) PowerShell module and the resource to create them.

Creating the module structure and the psm1 and schema.mof files is pretty easy when you’re using the cmdlets from the xDSCResourceDesigner module:

Install-Module -Name xDSCResourceDesigner

$ModuleName = 'myModule'
$ResourceName = 'SymbolicLink'
$ModuleFolder = "C:\Program Files\WindowsPowerShell\Modules\$ModuleName"

New-xDscResource -Name $ResourceName -Property @(
    New-xDscResourceProperty -Name Path -Type String -Attribute Key
    New-xDscResourceProperty -Name TargetPath -Type String -Attribute Write
) -Path $ModuleFolder

cd $ModuleFolder
New-ModuleManifest -Path ".\$ModuleName.psd1"

The contents of the .psm1 resource file C:\Program Files\WindowsPowerShell\Modules\myModule\DSCResources\SymbolicLink\SymbolicLink.psm1 should contain the three *-TargetResource functions (Get, Set and Test):

function Get-TargetResource {
    [CmdletBinding()]
    [OutputType([System.Collections.Hashtable])]
    param (
        [parameter(Mandatory = $true)]
        [System.String]
        $Path
    )

    Write-Verbose "Getting SymbolicLink for $Path"

    $Root = Split-Path -Path $Path -Parent
    $LinkName = Split-Path -Path $Path -Leaf
    $TargetPath = $null

    $link = Get-Item -Path (Join-Path -Path $Root -ChildPath $LinkName) -ErrorAction SilentlyContinue
    if($link -and  $link.LinkType -eq 'SymbolicLink') { $TargetPath = $link.Target[0] }
    
    @{Path = $Path; TargetPath = $TargetPath}
}


function Set-TargetResource {
    [CmdletBinding()]
    param
    (
        [parameter(Mandatory = $true)]
        [System.String]
        $Path,

        [System.String]
        $TargetPath
    )

    Write-Verbose "Creating a SymbolicLink from $Path to $TargetPath"

    $Root = Split-Path -Path $Path -Parent
    $LinkName = Split-Path -Path $Path -Leaf
    Set-Location -Path $Root
    New-Item -ItemType SymbolicLink -Name $LinkName -Target $TargetPath | Out-Null
}


function Test-TargetResource {
    [CmdletBinding()]
    [OutputType([System.Boolean])]
    param (
        [parameter(Mandatory = $true)]
        [System.String]
        $Path,

        [System.String]
        $TargetPath
    )

    Write-Verbose "Testing SymbolicLink for $Path"

    $current = Get-TargetResource -Path $Path
    return (($current.Path -eq $Path) -and ($current.TargetPath -eq $TargetPath))
}

Export-ModuleMember -Function *-TargetResource

And in the configuration document, remember to import the DSC resources from the module:

configuration Main {

    Import-DscResource -ModuleName PSDesiredStateConfiguration
    Import-DscResource -ModuleName myModule

    node localhost {

        SymbolicLink 'INPUT_DIR' {
            Path       = 'D:\INPUT_DIR'
            TargetPath = 'C:\PathTo\myLegacyApp\INPUT_DIR'
        }
        
        SymbolicLink 'OUTPUT_DIR' {
            Path       = 'D:\OUTPUT_DIR'
            TargetPath = 'C:\PathTo\myLegacyApp\OUTPUT_DIR'
        }
    }
}

Now, to create the zip file containing the configuration document and all required modules:

# Create the zip package
Publish-AzureRmVMDscConfiguration .\myDSC.ps1 -OutputArchivePath .\myDSC.zip

And upload it to the blob container (used in the ARM template):

# Variables
$storageAccountName = 'statweb'
$resourceGroupName = 'rg-statweb'

# Login to Azure
Login-AzureRmAccount

# Get the Storage Account authentication key
$keys = Get-AzureRmStorageAccountKey -ResourceGroupName $resourceGroupName -Name $storageAccountName

# Create a Storage Authentication Context
$context = New-AzureStorageContext -StorageAccountName $storageAccountName -StorageAccountKey $keys.Item(0).value

# Upload the file to the blob container
Set-AzureStorageBlobContent -Context $context -Container dsc -File .\myDSC.zip -Blob myDSC.zip

Conclusion

There are usually several methods to accomplish a single task, and you should take under consideration all aspects and constrains, because one can be more effective than another.

HTH,
Martin.

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.