哈希表漏洞(属性覆盖)?

Yur*_*uts 8 security powershell

我在PowerShell中使用哈希表,我注意到一些与访问项目有关的奇怪行为.我们知道,PowerShell至少允许三种不同的方式为散列表条目赋值:

$hashtable["foo"] = "bar"        #1
$hashtable.Item("foo") = "bar"   #2
$hashtable.foo = "bar"           #3
Run Code Online (Sandbox Code Playgroud)

同时,我们使用#3语法访问Hashtable对象本身,如性能Count,Keys,Values等如果我们有与内部属性的名称冲突的关键添加项目,PowerShell的让我们这样做,我们实际上不再能够读取属性的值(除了使用Reflection).

我想在密钥来自不可信赖的来源(例如来自外部文件或网络)的情况下,这可能会对流量控制产生不良影响,并且可能被恶意用户利用.

此代码段演示了此问题:

function Get-HashtableProperties($hashTable, $header)
{
    "{0} {1} {0}" -f ("-" * 10), $header

    "Count                      : {0}" -f $hashtable.Count
    "Keys.Count                 : {0}" -f $hashtable.Keys.Count
    "Values.Count               : {0}" -f $hashtable.Values.Count
    "Actual Count (Reflection)  : {0}" -f $hashtable.GetType().GetProperty("Count").GetValue($hashtable)

    "`nItems (Keys iteration):"
    $hashtable.Keys | ForEach-Object { "  [ {0} = {1} ]" -f $_, $hashtable.Item($_) }

    "`nItems (Enumerator iteration):"
    $enumerator = $hashTable.GetEnumerator()
    while ($enumerator.MoveNext())
    {
        "  [ {0} = {1} ]" -f $enumerator.Current.Key, $enumerator.Current.Value
    }
}

$fileContent = @"
    Foo = a
    Bar = b
"@

$maliciousFileContent = @"
    Foo = a
    Bar = b
    Count = 0
    Keys =
    Values =
"@

$hashtable = ConvertFrom-StringData $fileContent
$damagedHashtable = ConvertFrom-StringData $maliciousFileContent

Get-HashtableProperties $hashtable "Normal Hash Table"
Get-HashtableProperties $damagedHashtable "Damaged Hash Table"
Run Code Online (Sandbox Code Playgroud)

输出:

---------- Normal Hash Table ----------
Count                      : 2
Keys.Count                 : 2
Values.Count               : 2
Actual Count (Reflection)  : 2

Items (Keys iteration):
  [ Bar = b ]
  [ Foo = a ]

Items (Enumerator iteration):
  [ Bar = b ]
  [ Foo = a ]
---------- Damaged Hash Table ----------
Count                      : 0
Keys.Count                 : 1
Values.Count               : 1
Actual Count (Reflection)  : 5

Items (Keys iteration):
  [  =  ]

Items (Enumerator iteration):
  [ Count = 0 ]
  [ Bar = b ]
  [ Foo = a ]
  [ Values =  ]
  [ Keys =  ]
Run Code Online (Sandbox Code Playgroud)

问题:有没有办法防止这个问题,除了在分配之前手动检查每个密钥和/或在我们需要访问某些Hashtable属性的值时在代码中的任何地方使用Reflection ?

Kei*_*ill 6

在这种情况下,您可以像这样访问Hashtable的count属性:

C:\PS> $ht = @{Count = 99}
$ht.psbase.Count
1
Run Code Online (Sandbox Code Playgroud)

PowerShell中的扩展类型系统通过这些PS*属性提供对象的多个不同视图.有关详细信息,请参阅PowerShell团队博客文章.