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

标签 security powershell

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

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

同时,我们使用#3语法来访问Hashtable对象本身的属性,例如Count , Keys , Values等。如果我们添加一个键与内部属性名称冲突的项目,PowerShell 允许我们这样做,并且我们实际上不再能够读取该属性的值(使用反射除外)。

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

此代码段演示了该问题:
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 =  ]

问题 : 有没有办法防止这个问题,除了在赋值之前手动检查每个键和/或当我们需要访问一些 Hashtable 的值时在代码中的任何地方使用反射属性(property)?

最佳答案

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

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

PowerShell 中的扩展类型系统通过这些 PS* 属性提供对象的几种不同 View 。见 PowerShell team blog post详情。

关于security - 哈希表漏洞(属性覆盖)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15122913/

相关文章:

java - 签名的小程序无法加载

c - 如何在终端中接受密码而不显示密码

使用 key 和 iv 的 Java AES block 解密

c# - 存储 Windows 密码

windows - Powershell脚本无法读取AD电话号码

powershell - 复制项目并排除文件夹

powershell - 设置环境变量 - SETX

amazon-web-services - 使用 Lambda 集成保护 AWS API 网关

linux - 自定义提示在 Ubuntu 上的 PowerShell Core 6.0 中打印两次

exception - Powershell:捕获无法启动服务时引发的异常