【问题标题】:How can I check passwords against the 'haveibeenpwned Pwned Passwords' from PowerShell?如何根据 PowerShell 中的“haveibeenpwned Pwned 密码”检查密码?
【发布时间】:2017-08-11 05:29:51
【问题描述】:

我希望能够使用Troy Hunt's have I been pwned service 提供的Pwned Passwords 列表。

他的Introducing 306 Million Freely Downloadable Pwned Passwords 博客文章中描述了该服务。该 API 使用 HTTP Not Found 404 状态代码来指示何时在列表中未找到密码,并使用 200 来指示它已在受损列表中找到。这使得通过 Invoke-WebRequest PowerShell Cmdlet 消费变得困难,这会引发 404 的 WebException。

【问题讨论】:

  • 很好的问题和答案,但为什么您不希望仅仅捕获异常?
  • 对 .NET API 的好奇心真的很重要,但在测试两种结果时,其中一种感觉不应该是“异常”@MarkWragg

标签: .net api powershell security httpwebrequest


【解决方案1】:

较新的HttpClient 允许您在较低级别发出 HTTP 请求并检查 HttpStatusCode 而无需处理 404 异常,如下所示。

function Test-CompromisedPassword {
    param([Parameter(Mandatory=$True)][string]$password)

    # Force assembly to be loaded
    Add-Type -AssemblyName 'System.Net.Http'    
    # By default PowerShell would use TLS 1.0 which is not supported by the API
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

    $baseUrl = "https://haveibeenpwned.com/api/v2/pwnedpassword/{0}?originalPasswordIsAHash={1}"
    $url = $baseUrl -f $password,'false'

    $httpClient = New-Object System.Net.Http.HttpClient
    # User-Agent header must be set to call the API
    $httpClient.DefaultRequestHeaders.Add("User-Agent", "PowerShell script $($MyInvocation.MyCommand.Name)")

    # HttpClient is only Async so use .Result to force the synchronous call
    $response = $httpClient.GetAsync($url).Result

    Write-Verbose "$password $([int]$response.StatusCode) $($response.StatusCode)"

    switch ([int]$response.StatusCode) {
        200 { $passwordFound = $true; break; }
        404 { $passwordFound = $false; break; }
        429 { throw "Rate limit exceeded" }
        default { throw "Not expected" + $response.StatusCode }
    }

    if ($response) { $response.Dispose() }
    if ($httpClient) { $httpClient.Dispose() }

    return $passwordFound
}

你可以如下测试这个函数

Test-CompromisedPassword 'password' # Returns true to indicate password found
Start-Sleep -Milliseconds 1500 # Wait for the Rate limit time to expire
Test-CompromisedPassword ([Guid]::NewGuid()) # Returns false to indicate password not found

【讨论】:

    猜你喜欢
    • 2020-12-11
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    • 2020-09-05
    • 1970-01-01
    • 2018-03-12
    • 2016-03-14
    • 2014-11-08
    相关资源
    最近更新 更多