param( [Parameter(Mandatory = $true)] [string] $PackageDirectory, [Parameter(Mandatory = $true)] [string] $TrustedPublicKey ) $ErrorActionPreference = 'Stop' $packageRoot = [IO.Path]::GetFullPath($PackageDirectory) $publicKeyPath = [IO.Path]::GetFullPath($TrustedPublicKey) $manifestPath = Join-Path $packageRoot 'SHA256SUMS' $signaturePath = Join-Path $packageRoot 'SHA256SUMS.sig' foreach ($path in @($packageRoot, $publicKeyPath, $manifestPath, $signaturePath)) { if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { if ($path -eq $packageRoot -and (Test-Path -LiteralPath $path -PathType Container)) { continue } throw "Required verification file does not exist: $path" } } $rsa = [Security.Cryptography.RSA]::Create() try { $rsa.ImportFromPem([IO.File]::ReadAllText($publicKeyPath)) $manifest = [IO.File]::ReadAllBytes($manifestPath) $signature = [IO.File]::ReadAllBytes($signaturePath) if (-not $rsa.VerifyData( $manifest, $signature, [Security.Cryptography.HashAlgorithmName]::SHA256, [Security.Cryptography.RSASignaturePadding]::Pkcs1 )) { throw 'Release signature is invalid. Do not install these packages.' } } finally { $rsa.Dispose() } $entries = [IO.File]::ReadAllLines($manifestPath) if ($entries.Count -eq 0) { throw 'SHA256SUMS is empty.' } foreach ($entry in $entries) { if ($entry -notmatch '^([A-Fa-f0-9]{64}) [ *](.+)$') { throw "Invalid SHA256SUMS entry: $entry" } $expectedHash = $Matches[1].ToLowerInvariant() $relativePath = $Matches[2].Replace('\', '/') if ($relativePath.StartsWith('/') -or $relativePath -match '(^|/)\.\.(/|$)') { throw "Unsafe package path in SHA256SUMS: $relativePath" } $filePath = [IO.Path]::GetFullPath((Join-Path $packageRoot $relativePath)) if (-not $filePath.StartsWith($packageRoot.TrimEnd([IO.Path]::DirectorySeparatorChar) + [IO.Path]::DirectorySeparatorChar, [StringComparison]::OrdinalIgnoreCase) -or -not (Test-Path -LiteralPath $filePath -PathType Leaf)) { throw "Package file is missing or outside the download directory: $relativePath" } $actualHash = (Get-FileHash -LiteralPath $filePath -Algorithm SHA256).Hash.ToLowerInvariant() if ($actualHash -ne $expectedHash) { throw "SHA-256 mismatch for $relativePath. Do not install these packages." } Write-Output "Verified $relativePath" } Write-Output 'Release signature and all package hashes are valid.'