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

时间:2013-02-27 21:37:00

标签: security powershell

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

$hashtable["foo"] = "bar"        #1
$hashtable.Item("foo") = "bar"   #2
$hashtable.foo = "bar"           #3

同时,我们使用#3语法来访问Hashtable对象本身的属性,例如CountKeysValues等。如果我们添加一个项目与内部属性名称冲突的密钥,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"

输出:

---------- 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 =  ]

问题:有没有办法防止这个问题,除了在分配之前手动检查每个密钥和/或在我们需要访问某些{{1属性?

1 个答案:

答案 0 :(得分:6)

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

C:\PS> $ht = @{Count = 99}
$ht.psbase.Count
1

PowerShell中的扩展类型系统通过这些PS *属性提供对象的多个不同视图。有关详细信息,请参阅PowerShell team blog post