Sunday, November 08, 2015

Powershell: Importing hashtable from file or a psd1 file

Have you ever wanted to import a hashtable from a file? A module manifest that is saved in a *.psd1 file is a hashtable. If you ever wanted to read the meta data in it, this trick may help.

You import the contents into a script block, validate the script block, execute it and capture the resulting hashtable into a variable. Here is the sample code below:


$content = Get-Content -Path $Path -Raw -ErrorAction Stop
$scriptBlock = [scriptblock]::Create($content)
$scriptBlock.CheckRestrictedLanguage([string[]]@(), [string[]]@(), $false)
Write-Output (& $scriptBlock)



If you target a module manifest, you can access all the attributes in it. 

Name                           Value
----                           -----
Copyright                      (c) 2015 Kevin.Marquette. All rights reserved.
CompanyName                    Self
GUID                           6ab379f9-41ed-4c1e-beda-7855d1c1e3c8
Author                         Kevin.Marquette
FunctionsToExport              *
VariablesToExport              *
RootModule                     .\my_module.psm1
AliasesToExport                *
CmdletsToExport                *
ModuleVersion                  1.0.1 

The CheckRestrictedLanguage will throw an error if it finds any powershell commands in the hashtable. Because you are executing code from a un-trusted source in the middle of your script, you should validate it.

There is a second quick and dirty way to do the same thing without the validation. I almost don't want to mention it because it is so dangerous. So if you see this in the wild, know that there is a better way.

$HashTable = Invoke-Expression (Get-Content $Path -raw)

This blindly executes a file as if it was a script. This is just asking to be exploited. Think CSS cross site or SQL injection type of vulnerability. 

No comments: