powershell - 无法通过插值评估 Powershell 密码

标签 powershell passwords interpolation

如果用户未提供密码,我正在使用 Powershell 根据 another answer 向用户请求密码.然后我将密码(没有双关语)传递给某个程序,do-something.exe。我没有使用中间变量,而是尝试将密码转换为普通字符串“inline”:

[CmdletBinding()]
Param(
  [Parameter(Mandatory, HelpMessage="password?")] [SecureString]$password
)
do-something password=${[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))}

那是行不通的。我只能使用一个临时的中间变量让它工作:

[CmdletBinding()]
Param(
  [Parameter(Mandatory, HelpMessage="password?")] [SecureString]$password
)
$pwd=[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))
do-something.exe password=$pwd

我在调用 do-something.exe 时试图评估内联密码是否犯了错误?如何做到这一点?

最佳答案

${...} 是一个变量引用,无论 ... 是什么逐字作为变量名

  • {...} 中包含一个可变名称通常不是是必需的,但在两种情况下是必需的:(a) 如果变量名称包含特殊字符并且/或 (b) 在可扩展字符串 ("...") 的上下文中,以消除变量名称与后续字符的歧义 - 参见 this answer

为了嵌入表达式命令作为参数部分,使用 $(...)subexpression operator , 并且最好将整个参数包含在 "..." 中 - 这样,整个参数就会作为一个单个参数明确传递,而以 $(...) 子表达式开始未加引号标记将作为(至少)两个 参数(参见 this answer)。

因此:

[CmdletBinding()]
param(
  [Parameter(Mandatory, HelpMessage="password?")]
  [SecureString] $password
)

# Note the use of $(...) and the enclosure of the whole argument in "..."
do-something "password=$([Runtime.InteropServices.Marshal]::PtrToStringBSTR([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password)))"

另请注意:

  • 在 Windows 上它没有什么区别(在 Unix 上 [securestring] 实例几乎不提供任何保护,应该完全避免),但它应该是 [Runtime .InteropServices.Marshal]::PtrToStringBSTR(),而不是 [Runtime.InteropServices.Marshal]::PtrToStringAuto()

  • 作为Santiago Squarzon指出,有一种更简单的方法可以将 SecureString 实例转换为其等效的纯文本(通常应避免[1],但是,更根本的是,不鼓励在新项目中使用 [securestring][2]):

    [pscredential]::new('unused', $password).GetNetworkCredential().Password
    

[1] 存储在 .NET 字符串中的密码的纯文本表示会在内存中停留一段您无法控制的未指定时间。更具体地说,如果它是进程命令行的一部分,就像您的情况一样,可以通过这种方式发现它。当然,如果您所针对的 CLI 除了使用纯文本密码之外没有其他方式进行身份验证,您别无选择。

[2] 参见 this answer ,链接到 this .NET platform-compatibility recommendation .

关于powershell - 无法通过插值评估 Powershell 密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74201977/

相关文章:

powershell - 如何在 get-filehash 中使用 write-progress

css - 如何在 Angular 组件的样式标签中使用字符串插值?

php - 在 Laravel 4.2 中,密码哈希每次都会产生不同的结果

r - 如何提取等高线图的特定边界?

algorithm - 展开一个数组

powershell - 需要运行 PowerShell 脚本的 Azure 云服务启动任务

regex - 使用PowerShell从文本文件中提取表

powershell - 如何在 PowerShell 之上构建应用程序?

python - 计算用户密码和随 secret 码的熵

twitter - Twitter 可以查看您的密码吗?