Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent variable injection in PowerShell?

I was triggered again on a comment on a recent PowerShell question from @Ansgar Wiechers: DO NOT use Invoke-Expression with regards to a security question I have for a long time somewhere in the back of my mind and need to ask.

The strong statement (with a reference to the Invoke-Expression considered harmful article) suggests that an invocation of a script that can overwrite variables is considered harmful.

Also the PSScriptAnalyzer advises against using Invoke-Expression, see the AvoidUsingInvokeExpression rule.

But I once used a technic myself to update a common variable in a recursive script which can actually overwrite a value in any of its parents scopes which is as simple as:

([Ref]$ParentVariable).Value = $NewValue

As far as I can determine a potential malicious script could use this technic too to inject variables in any case no matter how it is invoked...

Consider the following "malicious" Inject.ps1 script:

([Ref]$MyValue).Value = 456
([Ref]$MyString).Value = 'Injected string'
([Ref]$MyObject).Value = [PSCustomObject]@{Name = 'Injected'; Value = 'Object'}

My Test.ps1 script:

$MyValue = 123
$MyString = "MyString"
$MyObject = [PSCustomObject]@{Name = 'My'; Value = 'Object'}
.\Inject.ps1
Write-Host $MyValue
Write-Host $MyString
Write-Host $MyObject

Result:

456
Injected string
@{Name=Injected; Value=Object}

As you see all three variables in the Test.ps1 scope are overwritten by the Inject.ps1 script. This can also be done using the Invoke-Command cmdlet and it doesn't even matter whether I set the scope of a variable to Private either:

New-Variable -Name MyValue -Value 123 -Scope Private
$MyString = "MyString"
$MyObject = [PSCustomObject]@{Name = 'My'; Value = 'Object'}
Invoke-Command {
    ([Ref]$MyValue).Value = 456
    ([Ref]$MyString).Value = 'Injected string'
    ([Ref]$MyObject).Value = [PSCustomObject]@{Name = 'Injected'; Value = 'Object'}
}
Write-Host $MyValue
Write-Host $MyString
Write-Host $MyObject

Is there a way to completely isolate an invoked script/command from overwriting variables in the current scope?
If not, can this be considered as a security risk for invoking scripts in any way?

like image 232
iRon Avatar asked Sep 06 '25 16:09

iRon


1 Answers

The advice against use of Invoke-Expression use is primarily about preventing unintended execution of code (code injection).

If you invoke a piece of PowerShell code - whether directly or via Invoke-Expression - it can indeed (possibly maliciously) manipulate parent scopes, including the global scope.
Note that this potential manipulation isn't limited to variables: for instance, functions and aliases can be modified as well.

Caveat: Running unknown code is problematic in two respects:

  • Primarily for the potential to perform unwanted / destructive actions directly.[1]
  • Secondarily, for the potential to maliciously modify the caller's state (variables, ...), which is the only aspect the solutions below guard against.

To provide the desired isolation, you have two basic choices:

  • Run the code in a child process:

    • By starting another PowerShell instance; e.g. (use powershell instead of pwsh in Windows PowerShell):

      • pwsh -c { ./someUntrustedScript.ps1 }
    • By starting a background job; e.g.:

      • Start-Job { ./someUntrustedScript.ps1 } | Receive-Job -Wait -AutoRemove
  • Run the code in a separate thread in the same process:

    • As a thread job, via the Start-ThreadJob cmdlet (ships with PowerShell [Core] 6+; in Windows PowerShell, it can be installed from the PowerShell Gallery with something like
      Install-Module -Scope CurrentUser ThreadJob); e.g.:

      • Start-ThreadJob { ./someUntrustedScript.ps1 } | Receive-Job -Wait -AutoRemove
    • By creating a new runspace via the PowerShell SDK; e.g.:

      • [powershell]::Create().AddScript('./someUntrustedScript.ps1').Invoke()
      • Note that you'll have to do extra work to get the output streams other than the success one, notably the error stream's output; also, .Dispose() should be called on the PowerShell instance on completion of the command.

A child process-based solution will be slow and limited in terms of data types you can return (due to serialization / deserialization being involved), but it provides isolation against the invoked code crashing the process.

A thread-based job is much faster, can return any data type, but can crash the entire process.

In all cases you will have to pass any values from the caller that the invoked code needs access to as arguments or, with background jobs and thread jobs, alternatively via the $using: scope specifier.


js2010 mentions other, less desirable alternatives:

  • Start-Process (child process-based, with text-only arguments and output)

  • PowerShell Workflows, which are obsolescent (they weren't ported to PowerShell Core and won't be).

  • Using Invoke-Command with "loopback remoting" (-ComputerName localhost) is hypothetically also an option, but then you incur the double overhead of a child process and HTTP-based communication; also, your computer must be set up for remoting, and you must run with elevation (as administrator).


[1] A way to mitigate the problem is to limit which commands, statements, types, ... are permitted to be called when the string is evaluated, which can be achieved via the PowerShell SDK in combination with language modesand/or by explicitly constructing an initial session state. See this answer for an example of SDK use with language modes.

like image 97
mklement0 Avatar answered Sep 10 '25 00:09

mklement0