| 1 |
#!/usr/bin/env pwsh |
| 2 |
|
| 3 |
# 0.5.0 fixed BOM-less encoding issues with Unicode |
| 4 |
#Requires -Modules @{ ModuleName = 'OpenAuthenticode'; ModuleVersion = '0.5.0' } |
| 5 |
|
| 6 |
using namespace System.Collections.Generic |
| 7 |
using namespace System.IO |
| 8 |
using namespace System.Management.Automation |
| 9 |
using namespace System.Management.Automation.Language |
| 10 |
using namespace System.Security.Cryptography.X509Certificates |
| 11 |
|
| 12 |
[CmdletBinding()] |
| 13 |
param ( |
| 14 |
[Parameter(Mandatory)] |
| 15 |
[string] |
| 16 |
$CollectionPath, |
| 17 |
|
| 18 |
[Parameter(Mandatory)] |
| 19 |
[string] |
| 20 |
$CertPath, |
| 21 |
|
| 22 |
[Parameter(Mandatory)] |
| 23 |
[string] |
| 24 |
$UntrustedCertPath, |
| 25 |
|
| 26 |
[Parameter(Mandatory)] |
| 27 |
[string] |
| 28 |
$CertPass |
| 29 |
) |
| 30 |
|
| 31 |
$ErrorActionPreference = 'Stop' |
| 32 |
|
| 33 |
Function New-AnsiblePowerShellSignature { |
| 34 |
<# |
| 35 |
.SYNOPSIS |
| 36 |
Creates and signed Ansible content for App Control/WDAC. |
| 37 |
|
| 38 |
.DESCRIPTION |
| 39 |
This function will generate the powershell_signatures.psd1 manifest and sign |
| 40 |
it. The manifest file includes all PowerShell/C# module_utils and |
| 41 |
PowerShell modules in the collection(s) specified. It will also create the |
| 42 |
'*.authenticode' signature file for the exec_wrapper.ps1 used inside |
| 43 |
Ansible itself. |
| 44 |
|
| 45 |
.PARAMETER Certificate |
| 46 |
The certificate to use for signing the content. |
| 47 |
|
| 48 |
.PARAMETER Collection |
| 49 |
The collection(s) to sign. This is set to ansible.builtin by default but |
| 50 |
can be overridden to include other collections like ansible.windows. |
| 51 |
|
| 52 |
.PARAMETER Skip |
| 53 |
A list of plugins to skip by the fully qualified name. Plugins skipped will |
| 54 |
not be included in the signed manifest. This means that modules will be run |
| 55 |
in CLM mode and module_utils will be skipped entirely. |
| 56 |
|
| 57 |
The values in the list should be the fully qualified name of the plugin as |
| 58 |
referenced in Ansible. The value can also optionally include the extension |
| 59 |
of the file if the FQN is ambiguous, e.g. collection util that has both a |
| 60 |
PowerShell and C# util of the same name. |
| 61 |
|
| 62 |
Here are some examples for the various content types: |
| 63 |
|
| 64 |
# Ansible Builtin Modules |
| 65 |
'ansible.builtin.module_name' |
| 66 |
|
| 67 |
# Ansible Builtin ModuleUtil |
| 68 |
'Ansible.ModuleUtils.PowerShellUtil' |
| 69 |
'Ansible.CSharpUtil' |
| 70 |
|
| 71 |
# Collection Modules |
| 72 |
'namespace.name.module_name' |
| 73 |
|
| 74 |
# Collection ModuleUtils |
| 75 |
'ansible_collections.namespace.name.plugins.module_utils.PowerShellUtil' |
| 76 |
'ansible_collections.namespace.name.plugins.module_utils.PowerShellUtil.psm1' |
| 77 |
|
| 78 |
'ansible_collections.namespace.name.plugins.module_utils.CSharpUtil' |
| 79 |
'ansible_collections.namespace.name.plugins.module_utils.CSharpUtil.cs' |
| 80 |
|
| 81 |
.PARAMETER Unsupported |
| 82 |
A list of plugins to be marked as unsupported in the manifest and will |
| 83 |
error when being run. List -Skip, the values here are the fully qualified |
| 84 |
name of the plugin as referenced in Ansible. |
| 85 |
|
| 86 |
.PARAMETER TimeStampServer |
| 87 |
Optional authenticode timestamp server to use when signing the content. |
| 88 |
|
| 89 |
.EXAMPLE |
| 90 |
Signs just the content included in Ansible. |
| 91 |
|
| 92 |
$cert = [X509Certificate2]::new("wdac-cert.pfx", "password") |
| 93 |
New-AnsiblePowerShellSignature -Certificate $cert |
| 94 |
|
| 95 |
.EXAMPLE |
| 96 |
Signs just the content include in Ansible and the ansible.windows collection |
| 97 |
|
| 98 |
$cert = [X509Certificate2]::new("wdac-cert.pfx", "password") |
| 99 |
New-AnsiblePowerShellSignature -Certificate $cert -Collection ansible.builtin, ansible.windows |
| 100 |
|
| 101 |
.EXAMPLE |
| 102 |
Signs just the content in the ansible.windows collection |
| 103 |
|
| 104 |
$cert = [X509Certificate2]::new("wdac-cert.pfx", "password") |
| 105 |
New-AnsiblePowerShellSignature -Certificate $cert -Collection ansible.windows |
| 106 |
|
| 107 |
.EXAMPLE |
| 108 |
Signs content but skips the specified modules and module_utils |
| 109 |
$skip = @( |
| 110 |
# Skips the module specified |
| 111 |
'namespace.name.module' |
| 112 |
|
| 113 |
# Skips the module_utils specified |
| 114 |
'ansible_collections.namespace.name.plugins.module_utils.PowerShellUtil' |
| 115 |
'ansible_collections.namespace.name.plugins.module_utils.CSharpUtil' |
| 116 |
|
| 117 |
# Skips signing the file specified |
| 118 |
'ansible_collections.namespace.name.plugins.plugin_utils.powershell.file.ps1' |
| 119 |
) |
| 120 |
$cert = [X509Certificate2]::new("wdac-cert.pfx", "password") |
| 121 |
New-AnsiblePowerShellSignature -Certificate $cert -Collection namespace.name -Skip $skip |
| 122 |
|
| 123 |
.NOTES |
| 124 |
This function requires Ansible to be installed and available in the PATH so |
| 125 |
it can find the Ansible installation and collection paths. |
| 126 |
#> |
| 127 |
[CmdletBinding()] |
| 128 |
param ( |
| 129 |
[Parameter( |
| 130 |
Mandatory |
| 131 |
)] |
| 132 |
[X509Certificate2] |
| 133 |
$Certificate, |
| 134 |
|
| 135 |
[Parameter( |
| 136 |
ValueFromPipeline, |
| 137 |
ValueFromPipelineByPropertyName |
| 138 |
)] |
| 139 |
[string[]] |
| 140 |
$Collection = "ansible.builtin", |
| 141 |
|
| 142 |
[Parameter( |
| 143 |
ValueFromPipelineByPropertyName |
| 144 |
)] |
| 145 |
[string[]] |
| 146 |
$Skip = @(), |
| 147 |
|
| 148 |
[Parameter( |
| 149 |
ValueFromPipelineByPropertyName |
| 150 |
)] |
| 151 |
[string[]] |
| 152 |
$Unsupported = @(), |
| 153 |
|
| 154 |
[Parameter()] |
| 155 |
[string] |
| 156 |
$TimeStampServer |
| 157 |
) |
| 158 |
|
| 159 |
begin { |
| 160 |
Write-Verbose "Attempting to get ansible-config dump" |
| 161 |
$configRaw = ansible-config dump --format json --type base 2>&1 |
| 162 |
if ($LASTEXITCODE) { |
| 163 |
$err = [ErrorRecord]::new( |
| 164 |
[Exception]::new("Failed to get Ansible configuration, RC: ${LASTEXITCODE} - $configRaw"), |
| 165 |
'FailedToGetAnsibleConfiguration', |
| 166 |
[ErrorCategory]::NotSpecified, |
| 167 |
$null) |
| 168 |
$PSCmdlet.ThrowTerminatingError($err) |
| 169 |
} |
| 170 |
|
| 171 |
$config = $configRaw | ConvertFrom-Json |
| 172 |
$collectionsPaths = @($config | Where-Object name -EQ 'COLLECTIONS_PATHS' | ForEach-Object value) |
| 173 |
Write-Verbose "Collections paths to be searched: [$($collectionsPaths -join ":")]" |
| 174 |
|
| 175 |
$signParams = @{ |
| 176 |
Certificate = $Certificate |
| 177 |
HashAlgorithm = 'SHA256' |
| 178 |
} |
| 179 |
if ($TimeStampServer) { |
| 180 |
$signParams.TimeStampServer = $TimeStampServer |
| 181 |
} |
| 182 |
|
| 183 |
$checked = [HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase) |
| 184 |
|
| 185 |
Function New-HashEntry { |
| 186 |
[OutputType([PSObject])] |
| 187 |
[CmdletBinding()] |
| 188 |
param ( |
| 189 |
[Parameter(Mandatory, ValueFromPipeline)] |
| 190 |
[FileInfo] |
| 191 |
$File, |
| 192 |
|
| 193 |
[Parameter(Mandatory)] |
| 194 |
[AllowEmptyString()] |
| 195 |
[string] |
| 196 |
$PluginBase, |
| 197 |
|
| 198 |
[Parameter()] |
| 199 |
[AllowEmptyCollection()] |
| 200 |
[string[]] |
| 201 |
$Unsupported = @(), |
| 202 |
|
| 203 |
[Parameter()] |
| 204 |
[AllowEmptyCollection()] |
| 205 |
[string[]] |
| 206 |
$Skip = @() |
| 207 |
) |
| 208 |
|
| 209 |
process { |
| 210 |
$nameWithoutExt = [string]::IsNullOrEmpty($PluginBase) ? $File.BaseName : "$PluginBase.$($File.BaseName)" |
| 211 |
$nameWithExt = "$nameWithoutExt$($File.Extension)" |
| 212 |
|
| 213 |
$mode = 'Trusted' |
| 214 |
if ($nameWithoutExt -in $Skip -or $nameWithExt -in $Skip) { |
| 215 |
Write-Verbose "Skipping plugin '$nameWithExt' as it is in the supplied skip list" |
| 216 |
return |
| 217 |
} |
| 218 |
elseif ($nameWithoutExt -in $Unsupported -or $nameWithExt -in $Unsupported) { |
| 219 |
Write-Verbose "Marking plugin '$nameWithExt' as unsupported as it is in the unsupported list" |
| 220 |
$mode = 'Unsupported' |
| 221 |
} |
| 222 |
|
| 223 |
Write-Verbose "Hashing plugin '$nameWithExt'" |
| 224 |
$hash = Get-FileHash -LiteralPath $File.FullName -Algorithm SHA256 |
| 225 |
[PSCustomObject]@{ |
| 226 |
Name = $nameWithExt |
| 227 |
Hash = $hash.Hash |
| 228 |
Mode = $mode |
| 229 |
} |
| 230 |
} |
| 231 |
} |
| 232 |
} |
| 233 |
|
| 234 |
process { |
| 235 |
$newHashParams = @{ |
| 236 |
Skip = $Skip |
| 237 |
Unsupported = $Unsupported |
| 238 |
} |
| 239 |
|
| 240 |
foreach ($c in $Collection) { |
| 241 |
try { |
| 242 |
if (-not $checked.Add($c)) { |
| 243 |
Write-Verbose "Skipping already processed collection $c" |
| 244 |
continue |
| 245 |
} |
| 246 |
|
| 247 |
$metaPath = $null |
| 248 |
$pathsToSign = [List[FileInfo]]::new() |
| 249 |
$hashedPaths = [List[PSObject]]::new() |
| 250 |
|
| 251 |
if ($c -eq 'ansible.builtin') { |
| 252 |
Write-Verbose "Attempting to get Ansible installation path" |
| 253 |
$ansiblePath = python -c "import ansible; print(ansible.__file__)" 2>&1 |
| 254 |
if ($LASTEXITCODE) { |
| 255 |
throw "Failed to find Ansible installation path, RC: ${LASTEXITCODE} - $ansiblePath" |
| 256 |
} |
| 257 |
|
| 258 |
$ansibleBase = Split-Path -Path $ansiblePath -Parent |
| 259 |
$metaPath = [Path]::Combine($ansibleBase, 'config') |
| 260 |
|
| 261 |
$execWrapper = Get-Item -LiteralPath ([Path]::Combine($ansibleBase, 'executor', 'powershell', 'exec_wrapper.ps1')) |
| 262 |
$pathsToSign.Add($execWrapper) |
| 263 |
|
| 264 |
$ansiblePwshContent = [PSObject[]]@( |
| 265 |
# These are needed for Ansible and cannot be skipped |
| 266 |
Get-ChildItem -Path ([Path]::Combine($ansibleBase, 'executor', 'powershell', '*.ps1')) -Exclude "bootstrap_wrapper.ps1" | |
| 267 |
New-HashEntry -PluginBase "ansible.executor.powershell" |
| 268 |
|
| 269 |
# Builtin utils are special where the filename is their FQN |
| 270 |
Get-ChildItem -Path ([Path]::Combine($ansibleBase, 'module_utils', 'csharp', '*.cs')) | |
| 271 |
New-HashEntry -PluginBase "" @newHashParams |
| 272 |
Get-ChildItem -Path ([Path]::Combine($ansibleBase, 'module_utils', 'powershell', '*.psm1')) | |
| 273 |
New-HashEntry -PluginBase "" @newHashParams |
| 274 |
|
| 275 |
Get-ChildItem -Path ([Path]::Combine($ansibleBase, 'modules', '*.ps1')) | |
| 276 |
New-HashEntry -PluginBase $c @newHashParams |
| 277 |
) |
| 278 |
$hashedPaths.AddRange($ansiblePwshContent) |
| 279 |
} |
| 280 |
else { |
| 281 |
Write-Verbose "Attempting to get collection path for $c" |
| 282 |
$namespace, $name, $remaining = $c.ToLowerInvariant() -split '\.' |
| 283 |
if (-not $name -or $remaining) { |
| 284 |
throw "Invalid collection name '$c', must be in the format 'namespace.name'" |
| 285 |
} |
| 286 |
|
| 287 |
$foundPath = $null |
| 288 |
foreach ($path in $collectionsPaths) { |
| 289 |
$collectionPath = [Path]::Combine($path, 'ansible_collections', $namespace, $name) |
| 290 |
|
| 291 |
Write-Verbose "Checking if collection $c exists in '$collectionPath'" |
| 292 |
if (Test-Path -LiteralPath $collectionPath) { |
| 293 |
$foundPath = $collectionPath |
| 294 |
break |
| 295 |
} |
| 296 |
} |
| 297 |
|
| 298 |
if (-not $foundPath) { |
| 299 |
throw "Failed to find collection path for $c" |
| 300 |
} |
| 301 |
|
| 302 |
Write-Verbose "Using collection path '$foundPath' for $c" |
| 303 |
|
| 304 |
$metaPath = [Path]::Combine($foundPath, 'meta') |
| 305 |
|
| 306 |
$collectionPwshContent = [PSObject[]]@( |
| 307 |
$utilPath = [Path]::Combine($foundPath, 'plugins', 'module_utils') |
| 308 |
if (Test-Path -LiteralPath $utilPath) { |
| 309 |
Get-ChildItem -LiteralPath $utilPath | Where-Object Extension -In '.cs', '.psm1' | |
| 310 |
New-HashEntry -PluginBase "ansible_collections.$c.plugins.module_utils" @newHashParams |
| 311 |
} |
| 312 |
|
| 313 |
$modulePath = [Path]::Combine($foundPath, 'plugins', 'modules') |
| 314 |
if (Test-Path -LiteralPath $modulePath) { |
| 315 |
Get-ChildItem -LiteralPath $modulePath | Where-Object Extension -EQ '.ps1' | |
| 316 |
New-HashEntry -PluginBase $c @newHashParams |
| 317 |
} |
| 318 |
) |
| 319 |
$hashedPaths.AddRange($collectionPwshContent) |
| 320 |
} |
| 321 |
|
| 322 |
if (-not (Test-Path -LiteralPath $metaPath)) { |
| 323 |
Write-Verbose "Creating meta path '$metaPath'" |
| 324 |
New-Item -Path $metaPath -ItemType Directory -Force | Out-Null |
| 325 |
} |
| 326 |
|
| 327 |
$manifest = @( |
| 328 |
'@{' |
| 329 |
' Version = 1' |
| 330 |
' HashList = @(' |
| 331 |
foreach ($content in $hashedPaths) { |
| 332 |
# To avoid encoding problems with Authenticode and non-ASCII |
| 333 |
# characters, we escape them as Unicode code points. We also |
| 334 |
# escape some ASCII control characters that can cause escaping |
| 335 |
# problems like newlines. |
| 336 |
$escapedName = [Regex]::Replace( |
| 337 |
$content.Name, |
| 338 |
'([^\u0020-\u007F])', |
| 339 |
{ '\u{0:x4}' -f ([uint16][char]$args[0].Value) }) |
| 340 |
|
| 341 |
$escapedHash = [CodeGeneration]::EscapeSingleQuotedStringContent($content.Hash) |
| 342 |
$escapedMode = [CodeGeneration]::EscapeSingleQuotedStringContent($content.Mode) |
| 343 |
" # $escapedName" |
| 344 |
" @{" |
| 345 |
" Hash = '$escapedHash'" |
| 346 |
" Mode = '$escapedMode'" |
| 347 |
" }" |
| 348 |
} |
| 349 |
' )' |
| 350 |
'}' |
| 351 |
) -join "`n" |
| 352 |
$manifestPath = [Path]::Combine($metaPath, 'powershell_signatures.psd1') |
| 353 |
Write-Verbose "Creating and signing manifest for $c at '$manifestPath'" |
| 354 |
Set-Content -LiteralPath $manifestPath -Value $manifest -NoNewline |
| 355 |
|
| 356 |
Set-OpenAuthenticodeSignature -LiteralPath $manifestPath @signParams |
| 357 |
|
| 358 |
$pathsToSign | ForEach-Object -Process { |
| 359 |
$tempPath = Join-Path $_.DirectoryName "$($_.BaseName)_tmp.ps1" |
| 360 |
$_ | Copy-Item -Destination $tempPath -Force |
| 361 |
|
| 362 |
try { |
| 363 |
Write-Verbose "Signing script '$($_.FullName)'" |
| 364 |
Set-OpenAuthenticodeSignature -LiteralPath $tempPath @signParams |
| 365 |
|
| 366 |
$signedContent = Get-Content -LiteralPath $tempPath -Raw |
| 367 |
$sigIndex = $signedContent.LastIndexOf("`r`n# SIG # Begin signature block`r`n") |
| 368 |
if ($sigIndex -eq -1) { |
| 369 |
throw "Failed to find signature block in $($_.FullName)" |
| 370 |
} |
| 371 |
|
| 372 |
# Ignore the first and last \r\n when extracting the signature |
| 373 |
$sigIndex += 2 |
| 374 |
$signature = $signedContent.Substring($sigIndex, $signedContent.Length - $sigIndex - 2) |
| 375 |
$sigPath = Join-Path $_.DirectoryName "$($_.Name).authenticode" |
| 376 |
|
| 377 |
Write-Verbose "Creating signature file at '$sigPath'" |
| 378 |
Set-Content -LiteralPath $sigPath -Value $signature -NoNewline |
| 379 |
} |
| 380 |
finally { |
| 381 |
$tempPath | Remove-Item -Force |
| 382 |
} |
| 383 |
} |
| 384 |
} |
| 385 |
catch { |
| 386 |
$_.ErrorDetails = "Failed to process collection ${c}: $_" |
| 387 |
$PSCmdlet.WriteError($_) |
| 388 |
continue |
| 389 |
} |
| 390 |
} |
| 391 |
} |
| 392 |
} |
| 393 |
|
| 394 |
$cert = [X509Certificate2]::new($CertPath, $CertPass) |
| 395 |
$untrustedCert = [X509Certificate2]::new($UntrustedCertPath, $CertPass) |
| 396 |
|
| 397 |
$sigParams = @{ |
| 398 |
Certificate = $cert |
| 399 |
Collection = 'ansible.builtin', 'ansible.windows', 'ns.col', 'ns.module_util_ref' |
| 400 |
Skip = @( |
| 401 |
'ns.col.skipped' |
| 402 |
'ns.col.inline_signed' |
| 403 |
'ns.col.inline_signed_not_trusted' |
| 404 |
'ns.col.unsigned_module_with_util' |
| 405 |
'ansible_collections.ns.col.plugins.module_utils.CSharpUnsigned' |
| 406 |
'ansible_collections.ns.col.plugins.module_utils.PwshUnsigned' |
| 407 |
) |
| 408 |
Unsupported = 'ns.col.unsupported' |
| 409 |
} |
| 410 |
New-AnsiblePowerShellSignature @sigParams |
| 411 |
|
| 412 |
@( |
| 413 |
"$CollectionPath/plugins/modules/inline_signed.ps1" |
| 414 |
"$CollectionPath/roles/app_control_script/files/signed.ps1" |
| 415 |
) | Set-OpenAuthenticodeSignature -Certificate $cert -HashAlgorithm SHA256 |
| 416 |
|
| 417 |
@( |
| 418 |
"$CollectionPath/plugins/modules/inline_signed_not_trusted.ps1" |
| 419 |
) | Set-OpenAuthenticodeSignature -Certificate $untrustedCert -HashAlgorithm SHA256 |