Exploring the RunAs feature in PowerShell DSC

PowerShell DSC is a great tool to configure and manage system settings. One highly requested feature was to be able to use DSC to manage user settings as well – for example per user registry settings. Another example would be to install an MSI which only works when run as a user.

To enable such scenarios, Microsoft published augmented versions
of the WindowsProcess and Package resources on the gallery.

With the latest WMF version, you get this feature out of the
box – DSC natively supports configuring user settings!

With the new WMF, in each resource, you can specify the user
context under which you want the resource to run. You do this via the ‘PsDscRunAsCredential’ property that is part of every resource (think of it in lines of ‘DependsOn’ which also gets added to every resource).

Let us see it in action with some examples.

A simple example is changing the console color using a DSC configuration:

Configuration foo

{

    Node (“localhost”)

    {

        Registry r

        {


Key 
= “HKEY_CURRENT_USER\\Software\Microsoft\\Command
Processor”


ValueName 
= “DefaultColor”


ValueData 
= ‘1F’


ValueType 
= “DWORD”


Ensure 
= “Present”


Force 
= $true


Hex 
= $true

            PsDscRunAsCredential = (Get-Credential)

        }

    }

}

 

 

 

 

$configData = @{

    AllNodes = @(

        @{


NodeName
=“localhost”;


PSDscAllowPlainTextPassword 
= $true

           

         }

 

)}

 

foo -ConfigurationData $configData

BlueConsole

There you have it, a blue console! If you try the same configuration without specifying the ‘PsDscRunAsCredential’ property, you would not see any
change in the console color next time you fired up the cmd prompt. The reason is that by default, the DSC engine (LCM) runs under the System account.

 

Next, let us take a look at the scenario where PsDscRunAsCredential provided is that of an admin and the admin tries to access some network share (This demonstrates that we do not need to enable CredSSP and there is no double hop problem)

 

Configuration foo

{

    Node (‘localhost’)

    {

        Script s

        {


PsDscRunAsCredential 
= (Get-Credential)


GetScript 
= ‘@{}’


TestScript 
= ‘$false’


SetScript 
= {New-Item -ItemType File -Path \\scratch2\scratch\abhikcha\Demo.txt}

        }

    }

}

 

 

$configData = @{

    AllNodes = @(

        @{


NodeName
=“localhost”;


PSDscAllowPlainTextPassword 
= $true

           

         }

 

)}

 

foo -ConfigurationData $configData

Output:

 

PS C:\Windows\system32> Start-DscConfiguration -Wait
-Verbose -Path .\foo

VERBOSE: Perform operation ‘Invoke CimMethod’ with following
parameters, ”methodName’ = SendConfigurationApply,’className’ =

MSFT_DSCLocalConfigurationManager,’namespaceName’ =
root/Microsoft/Windows/DesiredStateConfiguration’.

VERBOSE: An LCM method call arrived from computer WIN-IP51C1HOSRH
with user sid S-1-5-21-2127521184-1604012920-1887927527-101

18509.

VERBOSE: [WIN-IP51C1HOSRH]: LCM:  [ Start
Set      ]

VERBOSE: [WIN-IP51C1HOSRH]: LCM:  [ Start  Resource
]  [[Script]s]

VERBOSE: [WIN-IP51C1HOSRH]: LCM:  [ Start
Test     ]  [[Script]s]

VERBOSE: [WIN-IP51C1HOSRH]: LCM:  [ End
Test     ]  [[Script]s]  in 1.0270 seconds.

VERBOSE: [WIN-IP51C1HOSRH]: LCM:  [ Start
Set      ]  [[Script]s]

VERBOSE:
[WIN-IP51C1HOSRH]:
[[Script]s] Performing the operation “Set-TargetResource” on target
“E

xecuting the SetScript with the user supplied credential”.

VERBOSE: [WIN-IP51C1HOSRH]: LCM:  [ End
Set      ]  [[Script]s]  in 1.0780 seconds.

VERBOSE: [WIN-IP51C1HOSRH]: LCM:  [ End
Resource ]  [[Script]s]

VERBOSE: [WIN-IP51C1HOSRH]: LCM:  [ End
Set      ]    in  3.1380 seconds.

VERBOSE: Operation ‘Invoke CimMethod’ complete.

VERBOSE: Time taken for configuration job to complete is 3.347
seconds

 

PS C:\Windows\system32> dir \\scratch2\scratch\abhikcha\demo.txt

 

 

    Directory: \\scratch2\scratch\abhikcha

 

 

Mode
LastWriteTime         Length
Name                                                                      

—-
————-         ——
—-                                                                      

-a—-        4/29/2015
5:07
PM
demo.txt   

A thing to note is that an admin can provide the credentials of a non admin user and DSC works in that case too. This can come in handy when you want to configure some settings based on which user is logged in (for example, the number of days a cookie remains valid for Internet Explorer).

Getting under the hood.

Now, for the really fun part, let us dig deeper and see the system environment when DSC executes a resource as a user. Take a deep breath and follow along!

We are going to use the new DSC resource debugging features and see them in conjunction with the ‘RunAs’ feature to peek at the internals of the runspace, user environment, etc. First, let us see how to run LCM so that it breaks into the debugger whenever we apply a configuration. The ‘DebugMode’ is enhanced with a ‘ResourceScriptBreakAll’ mode to enable this:

LocalConfigurationManager

{

DebugMode =
“ResourceScriptBreakAll”

}

PS C:\Windows\system32>
Set-DscLocalConfigurationManager -Verbose -Path .\foo

VERBOSE: Performing the operation
“Start-DscConfiguration: SendMetaConfigurationApply” on target
“MSFT_DSCLocalConfigurationM

anager”.

VERBOSE: Perform operation ‘Invoke CimMethod’
with following parameters, ”methodName’ = SendMetaConfigurationApply,’classNam

e’ =
MSFT_DSCLocalConfigurationManager,’namespaceName’ =
root/Microsoft/Windows/DesiredStateConfiguration’.

VERBOSE: An LCM method call arrived
from computer APRILWMF with user sid
S-1-5-21-2127521184-1604012920-1887927527-10118509.

VERBOSE: [APRILWMF]: LCM: [ Start
Set ]

VERBOSE: [APRILWMF]: LCM: [ Start
Resource ] [MSFT_DSCMetaConfiguration]

VERBOSE: [APRILWMF]: LCM: [ Start
Set ] [MSFT_DSCMetaConfiguration]

VERBOSE: [APRILWMF]: LCM: [ End
Set ] [MSFT_DSCMetaConfiguration] in 0.1100 seconds.

VERBOSE: [APRILWMF]: LCM: [ End
Resource ] [MSFT_DSCMetaConfiguration]

VERBOSE: [APRILWMF]: LCM: [ End
Set ]

VERBOSE: [APRILWMF]: LCM: [ End
Set ] in 0.1570 seconds.

VERBOSE: Operation ‘Invoke CimMethod’
complete.

VERBOSE:
Set-DscLocalConfigurationManager finished in 1.156 seconds.

Let us now apply the configuration:

PS C:\Windows\system32>
Start-DscConfiguration -Wait -Verbose -Path .\foo

VERBOSE: Perform operation ‘Invoke
CimMethod’ with following parameters, ”methodName’ =
SendConfigurationApply,’className’ =

MSFT_DSCLocalConfigurationManager,’namespaceName’
= root/Microsoft/Windows/DesiredStateConfiguration’.

VERBOSE: An LCM method call arrived
from computer APRILWMF with user sid
S-1-5-21-2127521184-1604012920-1887927527-10118509.

VERBOSE: [APRILWMF]: LCM: [ Start
Set ]

WARNING:
[APRILWMF]: [DSCEngine] Warning LCM is in Debug
‘ResourceScriptBreakAll’ mode. Resource

script processing will be
stopped to wait for PowerShell script debugger to attach.

VERBOSE: [APRILWMF]: LCM: [ Start
Resource ] [[Registry]r]

VERBOSE: [APRILWMF]: LCM: [ Start
Test ] [[Registry]r]

WARNING:
[APRILWMF]: [[Registry]r] Resource is waiting for
PowerShell script debugger to attach.

Use the following commands to
begin debugging this resource script:

Enter-PSSession -ComputerName
APRILWMF -Credential <credentials>

Enter-PSHostProcess -Id 3628
-AppDomainName DscPsPluginWkr_AppDomain

Debug-Runspace -Id 4

As you can see, the engine stops and gives you the instructions on how to debug. Once you see these instructions, open up another instance of ISE and enter the last three commands:

p

You are in the debugger and have all the power at your fingertips! At this point, you can see the environment by printing out the value of $env:temp for example and see that it points to the ‘PsDscRunAsCredential’ user’s temp folder path. You can step in / step out / set breakpoints – do all the normal debugging tasks that you are familiar with. This is an incredibly powerful way to root cause complex issues during resource development and authoring.

As you may have noticed, the debugger starts with the Test-TargetResource function of the resource. This is because LCM first calls the Test-TargetResource when you apply a configuration. Once you are done debugging, press F5. After that, hit CTRL+C and type ‘exit’. This causes the debugger to come out of the runspace where Test-TargetResource was executing. LCM then continues applying the configuration:

VERBOSE: [APRILWMF]: LCM: [ End
Test ] [[Registry]r] in 101.3310 seconds.

VERBOSE: [APRILWMF]: LCM: [ Start
Set ] [[Registry]r]

WARNING:
[APRILWMF]: [[Registry]r] Resource is waiting for
PowerShell script debugger to attach.

Use the following commands to
begin debugging this resource script:

Enter-PSSession -ComputerName
APRILWMF -Credential <credentials>

Enter-PSHostProcess -Id 3628
-AppDomainName DscPsPluginWkr_AppDomain

Debug-Runspace -Id 3

Executing the instructions from the second ISE window will
cause the debugger to hit the beginning of the Set-TargetResource function and you can continue with your debugging.

The ‘RunAs’ is a really cool feature in the latest version of WMF. I can imagine it lighting up various new scenarios that were simply notpossible before.

Give it a try and share your experiences!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s