Skip to content

Instantly share code, notes, and snippets.

@kflu
Created November 28, 2016 04:16
Show Gist options
  • Save kflu/cef6884628693df9601650d802883941 to your computer and use it in GitHub Desktop.
Save kflu/cef6884628693df9601650d802883941 to your computer and use it in GitHub Desktop.
Unsign an assembly by tweaking the IL code before assembling it again.
[cmdletbinding()]
param($assembly, [switch]$DisplaySigningOnly)
$fullpath = [System.IO.Path]::GetFullPath($assembly)
$dir = [System.IO.Path]::GetDirectoryName($fullpath)
$ext = [System.IO.Path]::GetExtension($fullpath)
$filename = [System.IO.Path]::GetFileNameWithoutExtension($fullpath)
$assemblyBackupPath = [System.IO.Path]::Combine($dir, $filename + ".signed" + $ext)
$assemblyBackupDir = [System.IO.Path]::Combine($dir, "original")
$dasmFile = "$($env:TEMP)/$assembly.dasm.il"
$unsignedFile = "$($env:TEMP)/$assembly.unsigned.il"
function getSigningInfo
{
param($fn)
$out = sn /vf $fn
if ($out -match 'does not represent a strongly named assembly') { return "unsigned" }
if ($out -match 'delay-signed or test-signed assembly') { return "delaysigned" }
if ($out -match 'is valid') { return "signed" }
}
try
{
$signinfo = getSigningInfo $assembly
Write-Host "Processing $assembly : $signinfo" -ForegroundColor Green
if ($DisplaySigningOnly)
{
exit
}
if (($signinfo -eq "signed") -or ($signinfo -eq "unsigned"))
{
Write-Host "Skip."
exit
}
$Error.Clear()
Write-Host "Disassemble $assembly" -ForegroundColor Green
ildasm $assembly /out:$dasmFile
$il = [System.IO.File]::ReadAllText($dasmFile)
Write-Host "Removing signing..." -ForegroundColor Green
$unsigned = [regex]::Replace(
$il,
"(^ \.publickey =.+$\n.+\n.+\n.+\n.+\n.+\n.+\n.+\n.+\n.+\n)",
"",
[System.Text.RegularExpressions.RegexOptions]::Multiline)
Write-Host "Writing to $unsignedFile" -ForegroundColor Green
$unsigned | Out-File -Encoding utf8 $unsignedFile
Write-Host "Backing up $assembly to $assemblyBackupDir" -ForegroundColor Green
mkdir -Force $assemblyBackupDir -ErrorAction Stop > $null
if ($Error.Count -ge 1)
{
Write-Host "Something went wrong" -ForegroundColor Red
exit
}
move $assembly $assemblyBackupPath -Force -ErrorAction Stop
Write-Host "Updating $assembly" -ForegroundColor Green
if ($ext -ieq ".dll")
{
ilasm.exe $unsignedFile /dll /output=$assembly > $null
}
else
{
ilasm.exe $unsignedFile /output=$assembly > $null
}
}
finally
{
del $dasmFile -ErrorAction SilentlyContinue
del $unsignedFile -ErrorAction SilentlyContinue
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment