Carbon Black App Control: Powershell constrained language mode [WIP]

Cyber Security Industry leaders recommend leaving Powershell turned on. But enabling Constrained Language Mode, and enforcing all scripts being signed to run. This at bare minimum protects your environment as an attack surface. Of course I would also turn on WDAC and also go a step further and block .bat,.com files from executing as well.

Powershell should be pretty easy to configure to be secure enough by the system admins. You need to do three things:

What does Constrained Language constrain?

Constrained Language consists of a number of restrictions that limit unconstrained code execution on a locked-down system. These restrictions are:

  • PowerShell module script files must explicitly export functions by name without the use of wildcard characters. This is to prevent inadvertently exposing powerful helper function not meant to be used publicly.
  • PowerShell module manifest files must explicitly export functions by name without the use of wildcards. Again, to prevent inadvertent exposure of functions.
  • COM objects are blocked. They can expose Win32 APIs that have likely never been rigorously hardened as part of an attack surface.
  • Only approved .NET types are allowed. Many .NET types can be used to invoke arbitrary Win32 APIs. As a result only specific whitelisted types are allowed.
  • Add-Type is blocked. It allows the creation of arbitrary types defined in different languages.
  • The use of PowerShell classes are disallowed. PowerShell classes are just arbitrary C# type definitions.
  • PowerShell type conversion is not allowed. Type conversion implicitly creates types and runs type constructors.
  • Dot sourcing across language modes is disallowed. Dot sourcing a script file brings all functions, variables, aliases from that script into the current scope. So this blocks a trusted script from being dot sourced into an untrusted script and exposing all of its internal functions. Similarly, an untrusted script is prevented from being dot sourced into a trusted script so that it cannot pollute the trusted scope.
  • Command resolution automatically hides commands you cannot run. For example, a function created in Constrained Language mode is not visible to script running in Full Language mode.
  • XAML based workflows are blocked since they cannot be constrained by PowerShell. But script based workflows and trusted XAML based workflows shipped in-box are allowed.
  • The SupportedCommand parameter for Import-LocalizedData is disabled. It allows additional commands prevented by Constrained Language.
  • Invoke-Expression cmdlet always runs in Constrained Language. Invoke-Expression cannot validate input as trusted.
  • Set-PSBreakpoint command is blocked unless there is a system-wide lockdown through UMCI.
  • Command completers are always run in Constrained Language. Command completers are not validated as trustworthy.
  • Commands and script run within the script debugger will always be run in Constrained Language if there is a system-wide lockdown.
  • The DSC Configuration keyword is disabled.
  • Supported commands and Statements are not allowed in script DATA sections.
  • Start-Job is unavailable if the system is not locked-down. Start-Job starts PowerShell in a new process and if the system is not locked-down the new process runs in Full Language mode.
  1. Disable NTLM Fallback for WinRM (NTLM is constantly vulnerable and needing patching so best to force kerberos for WinRM)
  2. Set up an organization script signing certificate with your internal PKI and require admins to sign their scripts
  3. Set the GPO to require scripts that are executed be signed: https://techgenix.com/powershell-execution-policy/
  4. FWIW disabling Powershell can break lots of stuff you don’t even expect, as well. It’s best to restrict remote, admin, etc configurations to minimize surface. Mostly, if you disable remote Powershell ability, enforce signing (which also means users aren’t local admin to bypass these controls)… It’ll stop most things.

$ExecutionContext.SessionState.LanguageMode 
$ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage"
$ExecutionContext.SessionState.LanguageMode

[System.Console]::WriteLine("Hello")
Cannot invoke method. Method invocation is supported only on core types in this language mode.
At line:1 char:1
+ [System.Console]::WriteLine("Hello")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodInvocationNotSupportedInConstrainedLanguage

$ExecutionContext.SessionState.LanguageMode = "FullLanguage"


"C:\Program Files (x86)\Bit9\Parity Agent\Parity.exe" -m update

In addition, there are also file naming conventions that enable FullLanguage mode on a script, effectively bypassing Constrained Language. Again, this is for unit testing. 

MyScript.Test.ps1

Running a script with this naming pattern may execute in FullLanguage mode even if CLM is enforced, primarily intended for testing environments—not production use

To bypass PowerShell’s Constrained Language Mode (CLM) for unit testing purposes, Microsoft uses file naming conventions. Specifically, if a script’s filename ends with .Test.ps1, it may be executed in FullLanguage mode, overriding CLM restrictions (mainly designed for PowerShell’s internal testing).

Example:

powershellCopyEdit.\MyScript.Test.ps1

Carbon Black App Control

Create the following rule, using this guide, except change the Rule Type from Execution Control to File Creation Control.

1. Enable Constrained Language Mode (CLM)

How-To:

  • Use AppLocker or WDAC to enforce CLM:
    • Create AppLocker rules to deny all scripts except those signed.
    • Set __PSLockdownPolicy registry key: powershellCopyEditSet-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell" -Name "ExecutionPolicy" -Value "Restricted"
    • CLM is automatically enabled under WDAC policies.

2. Implement Signed Scripts Only

How-To:

  • Generate a code signing certificate:
    • Use internal PKI or purchase one.
    • In PowerShell: powershellCopyEditNew-SelfSignedCertificate -Type CodeSigning -CertStoreLocation Cert:\LocalMachine\My
  • Deploy certificate to trusted publishers store via GPO.
  • Set execution policy: powershellCopyEditSet-ExecutionPolicy AllSigned -Scope LocalMachine

3. Remove PowerShell v2.0

How-To:

  • Disable via Windows Features: powershellCopyEditDisable-WindowsOptionalFeature -Online -FeatureName MicrosoftWindowsPowerShellV2Root
  • Alternatively, via GPO:
    • Computer Configuration → Policies → Admin Templates → Windows Components → Windows PowerShell → Turn Off PowerShell v2.0 Engine → Enable.

4. Configure Windows Defender Application Control (WDAC)

How-To:

  • Create WDAC policies using Windows Defender Application Control Wizard or manually via PowerShell: powershellCopyEditNew-CIPolicy -Level PcaCertificate -FilePath "C:\Policies\MyPolicy.xml" -UserPEs ConvertFrom-CIPolicy -XmlFilePath "C:\Policies\MyPolicy.xml" -BinaryFilePath "C:\Policies\MyPolicy.bin"
  • Deploy policy via GPO or Intune.
  • Enforce only signed and approved binaries/scripts.

5. Restrict WinRM/PS Remoting Access

How-To:

  • Configure Windows Firewall: powershellCopyEditNew-NetFirewallRule -DisplayName "Allow WinRM from Management Subnet" -Direction Inbound -LocalPort 5985,5986 -Protocol TCP -RemoteAddress <MgmtSubnet>
  • Limit Remoting: powershellCopyEditSet-Item WSMan:\localhost\Client\TrustedHosts -Value "<MgmtSubnet>"
  • Alternatively, use GPO:
    • Computer Configuration → Admin Templates → Windows Components → Windows Remote Management.

Just Enough Administration: Windows PowerShell security controls help protect enterprise data – https://learn.microsoft.com/en-gb/powershell/scripting/security/remoting/jea/overview?view=powershell-7.5

Reference