#Requires -Version 5.1 <# .SYNOPSIS Measures one existing IIT configuration download from this Windows PC. .DESCRIPTION Use the Singapore PC and its usual office connection. Supply a private, authorized Netscape cookie jar from an existing IIT session. Paste the exact IIT object URL when prompted. The test makes one HTTPS GET without following redirects. For GcsDirect, request a fresh signed link on the test page and paste it at the hidden prompt. Supply the page's run ID to correlate the resulting report. .EXAMPLE .\measure-iit-baseline.ps1 -CookieJar 'C:\Private\iit-session.cookies' .EXAMPLE .\measure-iit-baseline.ps1 -Mode GcsDirect -RunId '0123456789abcdef0123456789abcdef' #> [CmdletBinding(DefaultParameterSetName = 'Iotc')] param( [Parameter(Mandatory, ParameterSetName = 'Iotc')] [string] $CookieJar, [Parameter(Mandatory, ParameterSetName = 'GcsDirect')] [ValidateSet('GcsDirect')] [string] $Mode, [Parameter(ParameterSetName = 'GcsDirect')] [ValidatePattern('\A[0-9a-fA-F]{32}\z')] [string] $RunId, [ValidateRange(1, 67108864)] [long] $ExpectedBytes = 9930488, [ValidatePattern('\A[0-9a-fA-F]{64}\z')] [string] $ExpectedSha256, [string] $OutputPath ) $ErrorActionPreference = 'Stop' $culture = [Globalization.CultureInfo]::InvariantCulture $utf8 = [Text.UTF8Encoding]::new($false) $isGcsDirect = $Mode -eq 'GcsDirect' function ConvertTo-CurlOptionValue([string] $Value) { if ($Value -match '[\x00-\x1F\x7F]') { throw 'A local path or option contains an unsupported control character.' } return '"' + $Value.Replace('\', '\\').Replace('"', '\"') + '"' } function ConvertTo-Milliseconds([string] $Value) { if ($Value -notmatch '\A[0-9]+(?:\.[0-9]+)?\z') { return $null } $seconds = [double]::Parse($Value, $culture) return [Math]::Round($seconds * 1000, 3) } function Test-GcsDownloadUrl([string] $Value) { $route = 'https://storage.googleapis.com/' if (!$Value.StartsWith($route, [StringComparison]::Ordinal) -or $Value.Length -gt 8192) { return $false } $parts = $Value.Substring($route.Length) -split '\?', 2 $pathPattern = '\A[a-z0-9][a-z0-9._-]{1,220}[a-z0-9]/(?(?:[A-Za-z0-9._~/-]|%[0-9A-F]{2})+)\z' $pathMatch = [regex]::Match($parts[0], $pathPattern) if ($parts.Length -ne 2 -or !$pathMatch.Success) { return $false } foreach ($segment in ($pathMatch.Groups['object'].Value -split '/')) { $decoded = [Uri]::UnescapeDataString($segment) if ($decoded -in '.', '..' -or $decoded -match '[/\\\x00-\x1F\x7F]') { return $false } } $queryNames = @('X-Goog-Algorithm', 'X-Goog-Credential', 'X-Goog-Date', 'X-Goog-Expires', 'X-Goog-SignedHeaders', 'X-Goog-Signature', 'generation') $query = @{} foreach ($pair in ($parts[1] -split '&')) { $parameter = $pair -split '=', 2 if ($parameter.Length -ne 2 -or $parameter[0] -cnotin $queryNames -or $query.ContainsKey($parameter[0]) -or $parameter[1] -cnotmatch '\A(?:[A-Za-z0-9._~-]|%[0-9A-F]{2})+\z') { return $false } $query[$parameter[0]] = [Uri]::UnescapeDataString($parameter[1]) } $timestamp = $query['X-Goog-Date'] $expiry = $query['X-Goog-Expires'] if ($query.Count -ne $queryNames.Length -or $timestamp -cnotmatch '\A[0-9]{8}T[0-9]{6}Z\z' -or $expiry -notmatch '\A[1-9][0-9]{0,3}\z' -or [int] $expiry -gt 3600) { return $false } $credentialPattern = '\A[A-Za-z0-9._-]+@[A-Za-z0-9.-]+\.gserviceaccount\.com/' + $timestamp.Substring(0, 8) + '/auto/storage/goog4_request\z' return ($query['X-Goog-Algorithm'] -ceq 'GOOG4-RSA-SHA256' -and $query['X-Goog-SignedHeaders'] -ceq 'host' -and $query['X-Goog-Credential'] -cmatch $credentialPattern -and $query['X-Goog-Signature'] -cmatch '\A(?:[0-9a-f]{2}){256,512}\z' -and $query['generation'] -match '\A[1-9][0-9]{0,19}\z') } if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) { throw 'Run this baseline helper from PowerShell on the Windows IIT PC.' } $curl = Get-Command curl.exe -CommandType Application -ErrorAction SilentlyContinue if (!$curl) { throw 'This helper requires the Windows curl.exe application.' } if (!$isGcsDirect) { try { $cookieItem = Get-Item -LiteralPath $CookieJar if ($cookieItem -isnot [IO.FileInfo] -or $cookieItem.FullName.Contains('=')) { throw 'Unsupported cookie jar path.' } $header = Get-Content -LiteralPath $cookieItem.FullName -TotalCount 1 if ($header -notmatch '\A# (?:Netscape )?HTTP Cookie File\s*\z') { throw 'Unsupported cookie jar format.' } } catch { throw 'Provide a readable Netscape cookie file from the existing authorized IIT session.' } } $localRunId = [Guid]::NewGuid().ToString('N') if ($RunId) { $runId = $RunId.ToLowerInvariant() } else { $runId = $localRunId } $userAgentTag = 'IITBaseline/' + $runId if (!$OutputPath) { $OutputPath = 'iit-baseline-' + $runId + '.json' } $reportPath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($OutputPath) if ([IO.Path]::GetExtension($reportPath) -ine '.json' -or ![IO.Directory]::Exists([IO.Path]::GetDirectoryName($reportPath)) -or [IO.File]::Exists($reportPath)) { throw 'Choose an unused .json filename in an existing folder for the baseline report.' } $prompt = if ($isGcsDirect) { 'GCS signed download URL (hidden)' } else { 'IIT object URL (hidden)' } $secretUrl = Read-Host $prompt -AsSecureString $urlPointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secretUrl) try { $url = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($urlPointer) } finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($urlPointer) $secretUrl.Dispose() } if ($isGcsDirect) { if (!(Test-GcsDownloadUrl $url)) { $url = $null throw 'Use a fresh signed GCS download URL from the test page.' } } else { $route = 'https://www.cloud.urmet.com/tool/multiapi/private/userdata/' $objectPattern = '\A[A-Za-z0-9._~!$&''()*+,;=:@%\-]+\z' if (!$url.StartsWith($route, [StringComparison]::Ordinal) -or $url.Length -gt 4096 -or $url.Substring($route.Length) -notmatch $objectPattern -or $url -match '%(?![0-9a-fA-F]{2})') { throw 'Use the exact IIT userdata HTTPS URL for one object on www.cloud.urmet.com.' } $objectSegment = [Uri]::UnescapeDataString($url.Substring($route.Length)) if ($objectSegment -in '.', '..' -or $objectSegment -match '[/\\\x00-\x1F\x7F]') { throw 'Use a single IIT object identifier.' } $objectSegment = $null } $profileDirectory = [Environment]::GetFolderPath([Environment+SpecialFolder]::LocalApplicationData) if (!$profileDirectory) { throw 'The private Windows user profile directory is unavailable.' } $workDirectory = Join-Path $profileDirectory ('IitBaseline-' + $localRunId) $bodyPath = Join-Path $workDirectory 'response.bin' $process = $null $processStarted = $false $directoryCreated = $false $result = [ordered]@{ schema = 'iit-baseline-v1' source = if ($isGcsDirect) { 'singapore-gcs-client' } else { 'singapore-iit-client' } runId = $runId userAgentTag = $userAgentTag startedAtUtc = $null status = 0 curlExit = $null ttfbMs = $null totalMs = $null wireBytes = $null expectedBytes = $ExpectedBytes fileBytes = $null sha256 = $null contentTypeCheck = 'not-checked' digestCheck = 'not-checked' outcome = 'transport-error' remoteIp = $null httpVersion = $null } try { [void] [IO.Directory]::CreateDirectory($workDirectory) $directoryCreated = $true $owner = [Security.Principal.WindowsIdentity]::GetCurrent().User $acl = [Security.AccessControl.DirectorySecurity]::new() $acl.SetAccessRuleProtection($true, $false) $inheritance = [Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [Security.AccessControl.InheritanceFlags]::ObjectInherit $access = [Security.AccessControl.FileSystemAccessRule]::new( $owner, [Security.AccessControl.FileSystemRights]::FullControl, $inheritance, [Security.AccessControl.PropagationFlags]::None, [Security.AccessControl.AccessControlType]::Allow) $acl.AddAccessRule($access) Set-Acl -LiteralPath $workDirectory -AclObject $acl $timing = '%{http_code}\t%{size_download}\t%{time_starttransfer}\t%{time_total}\t%{remote_ip}\t%{http_version}\t%{content_type}' $transferOption = if ($isGcsDirect) { 'path-as-is' } else { 'cookie = ' + (ConvertTo-CurlOptionValue $cookieItem.FullName) } $config = @( ('url = ' + (ConvertTo-CurlOptionValue $url)) $transferOption ('output = ' + (ConvertTo-CurlOptionValue $bodyPath)) ('user-agent = ' + (ConvertTo-CurlOptionValue $userAgentTag)) ('write-out = ' + (ConvertTo-CurlOptionValue $timing)) 'request = "GET"' 'header = "Accept-Encoding: identity"' 'proto = "=https"' 'noproxy = "*"' 'globoff' 'silent' 'max-redirs = "0"' 'max-filesize = "67108864"' 'connect-timeout = "20"' 'max-time = "600"' ) -join "`n" $url = $null $startInfo = [Diagnostics.ProcessStartInfo]::new() $startInfo.FileName = $curl.Source $startInfo.Arguments = '-q --config -' $startInfo.UseShellExecute = $false $startInfo.CreateNoWindow = $true $startInfo.RedirectStandardInput = $true $startInfo.RedirectStandardOutput = $true $startInfo.RedirectStandardError = $true $process = [Diagnostics.Process]::new() $process.StartInfo = $startInfo $result.startedAtUtc = [DateTime]::UtcNow.ToString('o', $culture) $processStarted = $process.Start() if (!$processStarted) { throw 'Could not start Windows curl.' } $statsTask = $process.StandardOutput.ReadToEndAsync() $errorsTask = $process.StandardError.BaseStream.CopyToAsync([IO.Stream]::Null) $configBytes = $utf8.GetBytes($config + "`n") $config = $null try { $process.StandardInput.BaseStream.Write($configBytes, 0, $configBytes.Length) $process.StandardInput.BaseStream.Flush() } finally { [Array]::Clear($configBytes, 0, $configBytes.Length) $process.StandardInput.BaseStream.Close() } if (!$process.WaitForExit(610000)) { throw 'Windows curl did not finish after its transfer deadline.' } $result.curlExit = $process.ExitCode $stats = $statsTask.GetAwaiter().GetResult() $errorsTask.GetAwaiter().GetResult() $fields = $stats -split "`t", 7 if ($fields.Length -eq 7 -and $fields[0] -match '\A[0-9]{3}\z') { $result.status = [int] $fields[0] if ($fields[1] -match '\A[0-9]{1,15}\z') { $result.wireBytes = [long] $fields[1] } if ($result.status -gt 0) { $result.ttfbMs = ConvertTo-Milliseconds $fields[2] } $result.totalMs = ConvertTo-Milliseconds $fields[3] $address = $null if ([Net.IPAddress]::TryParse($fields[4], [ref] $address)) { $result.remoteIp = $address.ToString() } if ($fields[5] -match '\A[1-3](?:\.[0-9])?\z') { $result.httpVersion = $fields[5] } if ($result.status -eq 200) { $mime = ($fields[6] -split ';', 2)[0].Trim() $result.contentTypeCheck = if ($mime -ieq 'application/octet-stream') { 'match' } else { 'mismatch' } } } if ([IO.File]::Exists($bodyPath)) { $result.fileBytes = (Get-Item -LiteralPath $bodyPath).Length } if ($result.status -ge 300 -and $result.status -lt 400) { $result.outcome = 'redirect' } elseif ($result.curlExit -ne 0 -or !$result.status -or $null -eq $result.totalMs -or $null -eq $result.ttfbMs) { $result.outcome = 'transport-error' } elseif ($result.status -ne 200) { $result.outcome = 'http-error' } elseif ($result.contentTypeCheck -ne 'match') { $result.outcome = 'content-type-mismatch' } elseif ($result.fileBytes -ne $ExpectedBytes -or $result.wireBytes -ne $ExpectedBytes) { $result.outcome = 'size-mismatch' } else { $digest = (Get-FileHash -LiteralPath $bodyPath -Algorithm SHA256).Hash.ToLowerInvariant() if (!$ExpectedSha256) { $result.sha256 = $digest $result.digestCheck = 'not-provided' $result.outcome = 'size-match' } elseif ($digest -ieq $ExpectedSha256) { $result.sha256 = $digest $result.digestCheck = 'match' $result.outcome = 'verified' } else { $result.digestCheck = 'mismatch' $result.outcome = 'digest-mismatch' } } } catch { throw 'The local baseline probe could not finish. Check curl and private profile folder access before trying again.' } finally { $url = $null $config = $null try { if ($process) { if ($processStarted -and !$process.HasExited) { $process.Kill() [void] $process.WaitForExit(5000) } $process.Dispose() } } finally { if ($directoryCreated) { Remove-Item -LiteralPath $workDirectory -Recurse -Force } } } $json = $result | ConvertTo-Json try { $report = [IO.File]::Open($reportPath, [IO.FileMode]::CreateNew) try { $jsonBytes = $utf8.GetBytes($json + "`n") $report.Write($jsonBytes, 0, $jsonBytes.Length) } finally { $report.Dispose() } } catch { throw 'The sanitized baseline JSON could not be saved to the selected filename.' } Write-Output $reportPath