Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

Sign Windows releases with the Certum code signing certificate

KnifeLemon9e886dd2fd03
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index fe2a145b..4ad9db94 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -3,6 +3,9 @@
#
# Output (build/build-installer.ps1): Filee-<version>-win-Setup.exe (Filee's own installer, src/Filee.Setup),
# Filee-<version>-win-Portable.zip and Filee-<version>-SHA256SUMS.txt.
+# The release is a draft with the Linux and macOS packages: the Windows files are signed on a PC signed in to Certum's
+# SimplySign cloud (its key needs a phone token), so this run keeps the tested, unsigned build as the artifact
+# windows-unsigned, and build/sign-release.ps1 signs it, packs Setup again, uploads the Windows files and publishes.
# Release notes: the version's section of CHANGELOG.md (what changed, for people using Filee), then the list GitHub
# generates from the pull requests merged since the previous release, grouped by label (.github/release.yml), with
# their authors and new contributors.
@@ -87,6 +90,22 @@ jobs:
shell: pwsh
run: ./build/build-installer.ps1 -Version ${{ steps.version.outputs.value }} -Portable
+ # The publish folder and the Setup program as tested, for build/sign-release.ps1 (artifacts leave out hidden
+ # folders such as build/.cache, so both are moved into one folder first).
+ - name: Keep the unsigned Windows build
+ shell: pwsh
+ run: |
+ New-Item -ItemType Directory -Force -Path unsigned | Out-Null
+ Move-Item publish/win-x64 unsigned/app
+ Copy-Item build/.cache/setup/Filee.Setup.exe unsigned/
+
+ - uses: actions/upload-artifact@v7
+ with:
+ name: windows-unsigned
+ path: unsigned/
+ if-no-files-found: error
+ retention-days: 30
+
- name: Download Linux and macOS packages
uses: actions/download-artifact@v8
with:
@@ -94,13 +113,15 @@ jobs:
merge-multiple: true
path: Releases
- - name: Publish the GitHub release
+ - name: Draft the GitHub release
shell: pwsh
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
$version = '${{ steps.version.outputs.value }}'
- $files = Get-ChildItem Releases -File -Filter "Filee-$version-*" | ForEach-Object FullName
+ # Linux and macOS only: build/sign-release.ps1 adds the signed Windows files.
+ $windows = "Filee-$version-win-Setup.exe", "Filee-$version-win-Portable.zip", "Filee-$version-SHA256SUMS.txt"
+ $files = Get-ChildItem Releases -File -Filter "Filee-$version-*" | Where-Object Name -notin $windows | ForEach-Object FullName
# "## 1.4.0" up to the next "## " heading of CHANGELOG.md, without the heading itself.
$changes = ''
$changelog = Get-Content CHANGELOG.md -Raw -Encoding utf8
@@ -126,4 +147,4 @@ jobs:
if ($tail) { $parts += $tail }
$notesFile = Join-Path $env:RUNNER_TEMP 'notes.md'
Set-Content $notesFile ($parts -join "`n`n") -Encoding utf8
- gh release create '${{ github.ref_name }}' --title "Filee $version" --notes-file $notesFile --verify-tag @files
+ gh release create '${{ github.ref_name }}' --draft --title "Filee $version" --notes-file $notesFile --verify-tag @files
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 0d21ccca..6ae31e67 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -110,8 +110,20 @@ Read [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) first. In short:
Bump `<Version>` in `Directory.Build.props`, merge, then push a tag `vX.Y.Z`. `.github/workflows/release.yml` runs the
tests and `build/build-installer.ps1 -Portable`: it publishes the app (`-p:FileeRelease=true`, which lets it register
Explorer and startup entries), adds the Explorer menu extension and the bundled rhwp and 7-Zip, compiles
-`src/Filee.Setup` (Filee's own installer) and appends the app to it, and uploads `Filee-X.Y.Z-win-Setup.exe`, the portable zip and
-their SHA-256 sums with release notes generated from the merged pull requests.
+`src/Filee.Setup` (Filee's own installer) and appends the app to it. It drafts the release with the Linux and macOS
+packages and release notes generated from the merged pull requests, and keeps the tested Windows build unsigned (the
+artifact `windows-unsigned`).
+
+Then, on a PC signed in to SimplySign Desktop (Certum's cloud certificate; its key needs the phone app's token), sign
+the Windows files and add them to the draft:
+
+```
+pwsh build/sign-release.ps1 -Version X.Y.Z -CertificateThumbprint <sha1>
+```
+
+It signs every unsigned program in the build and the Setup program, packs and signs `Filee-X.Y.Z-win-Setup.exe`, zips
+the portable copy, checks the signed Setup in a sandbox install and uploads the files with their SHA-256 sums. Look
+over the draft and publish it (or pass `-Publish`). `build/sign-windows.ps1` signs any folder or file on its own.
### "What's new" slides for a release
diff --git a/Directory.Build.props b/Directory.Build.props
index 11ed7f24..7162db41 100644
--- a/Directory.Build.props
+++ b/Directory.Build.props
@@ -23,4 +23,16 @@
<FileeRepositoryUrl>https://github.com/KnifeLemon/Filee</FileeRepositoryUrl>
<RepositoryUrl>$(FileeRepositoryUrl)</RepositoryUrl>
</PropertyGroup>
+
+ <!-- Libraries their makers sign: ReadyToRun recompiles an assembly and drops its Authenticode signature, so these
+ stay as shipped and keep it (Windows Smart App Control trusts signed code). build/sign-windows.ps1 signs the
+ rest. Run it on a publish folder to see which files are still unsigned when a package is added. -->
+ <ItemGroup>
+ <PublishReadyToRunExclude Include="CommunityToolkit.Mvvm.dll;HarfBuzzSharp.dll;SkiaSharp.dll" />
+ <PublishReadyToRunExclude Include="Magick.NET-Q8-AnyCPU.dll;Magick.NET.Core.dll;PDFtoImage.dll" />
+ <PublishReadyToRunExclude Include="Microsoft.Extensions.DependencyInjection.Abstractions.dll;Microsoft.Extensions.DependencyInjection.dll" />
+ <PublishReadyToRunExclude Include="Microsoft.Extensions.Logging.Abstractions.dll;Microsoft.Extensions.Logging.dll" />
+ <PublishReadyToRunExclude Include="Microsoft.Extensions.Options.dll;Microsoft.Extensions.Primitives.dll" />
+ <PublishReadyToRunExclude Include="Microsoft.IO.RecyclableMemoryStream.dll;Microsoft.Maui.Graphics.dll;System.Security.Cryptography.Pkcs.dll" />
+ </ItemGroup>
</Project>
diff --git a/README.ar.md b/README.ar.md
index c9437487..de71cfab 100644
--- a/README.ar.md
+++ b/README.ar.md
@@ -161,8 +161,8 @@ dotnet test
## سياسة توقيع الشيفرة
يطوّر Filee وينشره **Myeonggu Kim** ([KnifeLemon](https://github.com/KnifeLemon)).
-ستُوقَّع إصدارات Windows بشهادة توقيع شيفرة للمشاريع مفتوحة المصدر من [Certum](https://www.certum.eu/) صادرة باسم
-Myeonggu Kim، والشهادة قيد الإصدار.
+تُوقَّع إصدارات Windows بشهادة توقيع شيفرة للمشاريع مفتوحة المصدر من [Certum](https://www.certum.eu/) صادرة باسم
+Myeonggu Kim. الإصدارات حتى 2.0.0 غير موقَّعة.
السياسة الكاملة وسياسة الخصوصية في [README الإنجليزي](README.md#code-signing-policy).
لا يرفع Filee ملفاتك ولا يرسل أي بيانات استخدام.
diff --git a/README.es.md b/README.es.md
index 71137783..f46048d5 100644
--- a/README.es.md
+++ b/README.es.md
@@ -151,8 +151,8 @@ Las pull requests son bienvenidas. Si Filee te ahorra unos cuantos clics, una
## Política de firma de código
Filee lo desarrolla y publica **Myeonggu Kim** ([KnifeLemon](https://github.com/KnifeLemon)).
-Las versiones para Windows se firmarán con un certificado de firma de código para código abierto de [Certum](https://www.certum.eu/)
-emitido a nombre de Myeonggu Kim. El certificado está en trámite.
+Las versiones para Windows se firman con un certificado de firma de código para código abierto de [Certum](https://www.certum.eu/)
+emitido a nombre de Myeonggu Kim. Las versiones hasta la 2.0.0 no están firmadas.
La política completa y la política de privacidad están en el [README en inglés](README.md#code-signing-policy).
Filee no sube tus archivos ni envía datos de uso.
diff --git a/README.fr.md b/README.fr.md
index 36744543..ec6bf367 100644
--- a/README.fr.md
+++ b/README.fr.md
@@ -152,12 +152,13 @@ Les pull requests sont les bienvenues. Si Filee vous épargne quelques clics, un
Filee est développé et publié par **Myeonggu Kim** ([KnifeLemon](https://github.com/KnifeLemon)).
-Les versions Windows seront signées avec un certificat de signature de code open source [Certum](https://www.certum.eu/) délivré
-à Myeonggu Kim. Le certificat est en cours de délivrance ; d'ici là, les versions ne sont pas signées et Windows SmartScreen
-peut afficher un avertissement au lancement du programme d'installation (« Informations complémentaires » → « Exécuter quand même »). Les paquets macOS sont signés ad hoc et ne sont pas notarisés.
+Les versions Windows sont signées avec un certificat de signature de code open source [Certum](https://www.certum.eu/) délivré
+à Myeonggu Kim. Les versions jusqu'à la 2.0.0 ne sont pas signées. Windows SmartScreen peut encore afficher un
+avertissement pour une nouvelle version tant qu'elle n'a pas été assez téléchargée (« Informations complémentaires » → « Exécuter quand même »). Les paquets macOS sont signés ad hoc et ne sont pas notarisés.
-Seuls le programme d'installation et les fichiers produits par le workflow de publication GitHub Actions de ce dépôt sont signés, et chaque version
-est approuvée manuellement. Les programmes tiers inclus (rhwp, 7-Zip) conservent les fichiers de leurs propres éditeurs.
+Seuls les fichiers produits par le workflow de publication GitHub Actions de ce dépôt sont signés, et chaque version
+est signée et approuvée manuellement. Les bibliothèques et programmes déjà signés par leurs éditeurs gardent leur
+signature ; ceux qui arrivent sans signature (rhwp, 7-Zip et la plupart des bibliothèques) sont signés avec le certificat de Filee.
### Politique de confidentialité
diff --git a/README.hi.md b/README.hi.md
index d6098a7d..e07777f7 100644
--- a/README.hi.md
+++ b/README.hi.md
@@ -151,8 +151,8 @@ dotnet test
## कोड साइनिंग नीति
Filee को **Myeonggu Kim** ([KnifeLemon](https://github.com/KnifeLemon)) विकसित और प्रकाशित करते हैं।
-Windows रिलीज़ को Myeonggu Kim के नाम जारी [Certum](https://www.certum.eu/) ओपन-सोर्स कोड साइनिंग सर्टिफ़िकेट से साइन किया जाएगा।
-सर्टिफ़िकेट अभी जारी होने की प्रक्रिया में है।
+Windows रिलीज़ Myeonggu Kim के नाम जारी [Certum](https://www.certum.eu/) ओपन-सोर्स कोड साइनिंग सर्टिफ़िकेट से साइन की जाती हैं।
+2.0.0 तक की रिलीज़ साइन नहीं हैं।
पूरी नीति और गोपनीयता नीति [अंग्रेज़ी README](README.md#code-signing-policy) में है।
Filee आपकी फ़ाइलें अपलोड नहीं करता और इस्तेमाल का कोई डेटा नहीं भेजता।
diff --git a/README.ja.md b/README.ja.md
index 8b17efae..0335379d 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -151,8 +151,8 @@ dotnet test
## コード署名ポリシー
Fileeは**Myeonggu Kim**([KnifeLemon](https://github.com/KnifeLemon))が開発・公開しています。
-Windows版のリリースには、Myeonggu Kim名義で発行される[Certum](https://www.certum.eu/)のオープンソース向けコード署名証明書で署名する予定です。
-証明書は現在、発行手続き中です。
+Windows版のリリースには、Myeonggu Kim名義で発行された[Certum](https://www.certum.eu/)のオープンソース向けコード署名証明書で署名しています。
+2.0.0までのリリースは署名されていません。
ポリシーの詳細とプライバシーポリシーは[英語版README](README.md#code-signing-policy)をご覧ください。
Fileeはファイルをアップロードせず、利用データも送信しません。
diff --git a/README.ko.md b/README.ko.md
index 445343d9..1ba39596 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -150,8 +150,8 @@ PR 환영해요. Filee가 쓸만하다면 ⭐ 하나가 다른 사람들이 File
## 코드 서명 정책
Filee는 **Myeonggu Kim**([KnifeLemon](https://github.com/KnifeLemon))이 개발하고 배포해요.
-Windows 릴리스는 Myeonggu Kim 명의의 [Certum](https://www.certum.eu/) 오픈소스 코드 서명 인증서로 서명할 예정이고,
-지금은 발급 절차가 진행 중이에요.
+Windows 릴리스는 Myeonggu Kim 명의의 [Certum](https://www.certum.eu/) 오픈소스 코드 서명 인증서로 서명해요.
+2.0.0까지의 릴리스는 서명되지 않았어요.
자세한 정책과 개인정보 처리 방침은 [영문 README](README.md#code-signing-policy)에 있어요.
Filee는 파일을 업로드하지 않고, 사용 기록도 보내지 않아요.
diff --git a/README.md b/README.md
index c3ec701c..0e9c9a67 100644
--- a/README.md
+++ b/README.md
@@ -152,12 +152,15 @@ Pull requests are welcome. If Filee saves you some clicks, a ⭐ helps other peo
Filee is developed and published by **Myeonggu Kim** ([KnifeLemon](https://github.com/KnifeLemon)).
-Windows releases will be signed with a [Certum](https://www.certum.eu/) open source code signing certificate issued
-to Myeonggu Kim. The certificate is being issued; until then, releases are not code-signed and Windows SmartScreen
-may warn when you run the installer ("More info" → "Run anyway"). macOS packages are ad-hoc signed and not notarized.
-
-Only the installer and files built by this repository's GitHub Actions release workflow are signed, and every release
-is approved by hand. Bundled third-party programs (rhwp, 7-Zip) keep their own publishers' files.
+Windows releases are signed with a [Certum](https://www.certum.eu/) open source code signing certificate issued to
+Myeonggu Kim ("Open Source Developer MYEONGGU KIM"). Releases before it, up to 2.0.0, are not signed. SmartScreen can
+still warn about a new release until it has been downloaded enough ("More info" → "Run anyway"). macOS packages are
+ad-hoc signed and not notarized.
+
+Only files built by this repository's GitHub Actions release workflow are signed, and every release is signed and
+approved by hand. Libraries and programs their makers signed (.NET, SkiaSharp, ImageMagick, the Microsoft C++
+runtime …) keep their own signatures; bundled ones that come unsigned (rhwp, 7-Zip and most libraries) are signed with
+Filee's certificate, as part of Filee.
### Privacy policy
diff --git a/README.pl.md b/README.pl.md
index c057b7ed..ea22965f 100644
--- a/README.pl.md
+++ b/README.pl.md
@@ -151,8 +151,8 @@ Pull requesty są mile widziane. Jeśli Filee oszczędza Ci kilka kliknięć,
## Zasady podpisywania kodu
Filee tworzy i publikuje **Myeonggu Kim** ([KnifeLemon](https://github.com/KnifeLemon)).
-Wydania dla Windows będą podpisywane certyfikatem [Certum](https://www.certum.eu/) do podpisywania kodu open source,
-wystawionym na Myeonggu Kim. Certyfikat jest w trakcie wydawania.
+Wydania dla Windows są podpisywane certyfikatem [Certum](https://www.certum.eu/) do podpisywania kodu open source,
+wystawionym na Myeonggu Kim. Wydania do 2.0.0 włącznie nie są podpisane.
Pełne zasady i politykę prywatności znajdziesz w [angielskim README](README.md#code-signing-policy).
Filee nie wysyła Twoich plików ani danych o użytkowaniu.
diff --git a/README.pt-BR.md b/README.pt-BR.md
index 32206c3f..daa4e012 100644
--- a/README.pt-BR.md
+++ b/README.pt-BR.md
@@ -152,12 +152,13 @@ Pull requests são bem-vindos. Se o Filee poupar alguns cliques, uma ⭐ ajuda o
O Filee é desenvolvido e publicado por **Myeonggu Kim** ([KnifeLemon](https://github.com/KnifeLemon)).
-As versões para Windows serão assinadas com um certificado de assinatura de código de código aberto da [Certum](https://www.certum.eu/), emitido
-para Myeonggu Kim. O certificado está sendo emitido; até lá, as versões não são assinadas e o SmartScreen do Windows
-pode avisar ao executar o instalador (“Mais informações” → “Executar mesmo assim”). Os pacotes de macOS são assinados ad hoc e não são notarizados.
+As versões para Windows são assinadas com um certificado de assinatura de código de código aberto da [Certum](https://www.certum.eu/), emitido
+para Myeonggu Kim. As versões até a 2.0.0 não são assinadas. O SmartScreen do Windows ainda pode avisar sobre uma versão
+nova até ela ser baixada o bastante (“Mais informações” → “Executar mesmo assim”). Os pacotes de macOS são assinados ad hoc e não são notarizados.
-Só o instalador e os arquivos gerados pelo fluxo de release das GitHub Actions deste repositório são assinados, e cada release
-é aprovada manualmente. Programas de terceiros incluídos (rhwp, 7-Zip) mantêm os arquivos dos próprios editores.
+Só os arquivos gerados pelo fluxo de release das GitHub Actions deste repositório são assinados, e cada release
+é assinada e aprovada manualmente. Bibliotecas e programas já assinados pelos próprios editores mantêm a assinatura;
+os que vêm sem assinatura (rhwp, 7-Zip e a maioria das bibliotecas) são assinados com o certificado do Filee.
### Política de privacidade
diff --git a/README.ru.md b/README.ru.md
index f73fa002..9a4af954 100644
--- a/README.ru.md
+++ b/README.ru.md
@@ -151,8 +151,8 @@ dotnet test
## Подпись кода
Filee разрабатывает и публикует **Myeonggu Kim** ([KnifeLemon](https://github.com/KnifeLemon)).
-Выпуски для Windows будут подписаны сертификатом [Certum](https://www.certum.eu/) для подписи кода open source,
-выданным на имя Myeonggu Kim. Сертификат сейчас оформляется.
+Выпуски для Windows подписываются сертификатом [Certum](https://www.certum.eu/) для подписи кода open source,
+выданным на имя Myeonggu Kim. Выпуски до 2.0.0 включительно не подписаны.
Полные правила и политику конфиденциальности смотрите в [английском README](README.md#code-signing-policy).
Filee не отправляет ни ваши файлы, ни данные об использовании.
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 7467d936..e534ab6f 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -147,7 +147,7 @@ dotnet test
## 代码签名政策
Filee 由 **Myeonggu Kim**([KnifeLemon](https://github.com/KnifeLemon))开发和发布。
-Windows 版本将使用颁发给 Myeonggu Kim 的 [Certum](https://www.certum.eu/) 开源代码签名证书签名,证书正在办理中。
+Windows 版本使用颁发给 Myeonggu Kim 的 [Certum](https://www.certum.eu/) 开源代码签名证书签名。2.0.0 及更早的版本没有签名。
详细政策和隐私政策见[英文 README](README.md#code-signing-policy)。
Filee 不会上传文件,也不会发送任何使用数据。
diff --git a/README.zh-TW.md b/README.zh-TW.md
index a66ef1bd..84715f5f 100644
--- a/README.zh-TW.md
+++ b/README.zh-TW.md
@@ -147,7 +147,7 @@ dotnet test
## 程式碼簽章政策
Filee 由 **Myeonggu Kim**([KnifeLemon](https://github.com/KnifeLemon))開發和發布。
-Windows 版本將使用頒發給 Myeonggu Kim 的 [Certum](https://www.certum.eu/) 開放原始碼程式碼簽章憑證簽署,憑證正在辦理中。
+Windows 版本使用頒發給 Myeonggu Kim 的 [Certum](https://www.certum.eu/) 開放原始碼程式碼簽章憑證簽署。2.0.0 及更早的版本沒有簽署。
詳細政策和隱私權政策見[英文 README](README.md#code-signing-policy)。
Filee 不會上傳檔案,也不會傳送任何使用資料。
diff --git a/build/build-installer.ps1 b/build/build-installer.ps1
index f4e396f7..d33e61cf 100644
--- a/build/build-installer.ps1
+++ b/build/build-installer.ps1
@@ -14,6 +14,11 @@
engines Setup offers from EngineDownloads. The portable zip is the publish folder as it is: without Setup's
uninstall.exe next to Filee.exe, Filee knows it is a portable copy.
+.PARAMETER CertificateThumbprint
+ Signs the release (build/sign-windows.ps1): the programs in the publish folder that come unsigned, the Setup
+ program (it becomes uninstall.exe) and, after the payload is appended, Setup.exe. The release workflow builds
+ without it; build/sign-release.ps1 signs its output on a PC signed in to SimplySign.
+
.PARAMETER CheckOnly
Builds Setup around a stub app (fast compression) and runs it in a sandbox: install, update and uninstall into a
scratch folder with its own registry file, nothing on the PC is touched (CI).
@@ -21,6 +26,7 @@
.EXAMPLE
pwsh build/build-installer.ps1
pwsh build/build-installer.ps1 -Version 2.0.0 -Portable
+ pwsh build/build-installer.ps1 -Version 2.0.0 -Portable -PublishDir app -SetupProgram Filee.Setup.exe -CertificateThumbprint <sha1>
pwsh build/build-installer.ps1 -CheckOnly
#>
[CmdletBinding()]
@@ -29,8 +35,11 @@ param(
[string]$Version,
# A finished publish folder (Filee.exe, FileeExplorerMenu.dll/.msix, engines\); skips publishing.
[string]$PublishDir,
+ # A finished Setup program (Filee.Setup.exe from an earlier run); skips publishing src/Filee.Setup.
+ [string]$SetupProgram,
[string]$OutputDir = (Join-Path $PSScriptRoot '..\Releases'),
[switch]$Portable,
+ [string]$CertificateThumbprint,
[switch]$CheckOnly
)
@@ -100,11 +109,22 @@ if (-not $CheckOnly) {
}
# Setup: one self-contained, trimmed program (src/Filee.Setup).
-$setupProgram = Join-Path $cache 'setup'
-Remove-Item $setupProgram -Recurse -Force -ErrorAction SilentlyContinue
-Invoke-Checked 'dotnet publish (setup)' {
- dotnet publish (Join-Path $root 'src\Filee.Setup\Filee.Setup.csproj') -c Release -r win-x64 -p:FileeSetupPublish=true `
- "-p:Version=$Version" -o $setupProgram
+if (-not $SetupProgram) {
+ $setupFolder = Join-Path $cache 'setup'
+ Remove-Item $setupFolder -Recurse -Force -ErrorAction SilentlyContinue
+ Invoke-Checked 'dotnet publish (setup)' {
+ dotnet publish (Join-Path $root 'src\Filee.Setup\Filee.Setup.csproj') -c Release -r win-x64 -p:FileeSetupPublish=true `
+ "-p:Version=$Version" -o $setupFolder
+ }
+ $SetupProgram = Join-Path $setupFolder 'Filee.Setup.exe'
+}
+$SetupProgram = (Resolve-Path $SetupProgram).Path
+
+# Signed before packing: the app's files are signed inside the payload, and the Setup program's signature carries
+# over to the uninstaller (SetupPayload). Setup.exe itself is signed after the payload is appended.
+$sign = if ($CertificateThumbprint -and -not $CheckOnly) { Join-Path $PSScriptRoot 'sign-windows.ps1' }
+if ($sign) {
+ & $sign -Path $PublishDir, $SetupProgram -CertificateThumbprint $CertificateThumbprint
}
$setupExe = Join-Path $OutputDir "Filee-$Version-win-Setup.exe"
@@ -112,13 +132,15 @@ Write-Host "pack installer $Version"
$fast = @(if ($CheckOnly) { '--fast' })
Push-Location $root
try {
- $program = Join-Path $setupProgram 'Filee.Setup.exe'
- Invoke-Checked 'make-setup' { dotnet run --no-cache build/tools/make-setup.cs -- $program $PublishDir $Version $setupExe @fast }
+ Invoke-Checked 'make-setup' { dotnet run --no-cache build/tools/make-setup.cs -- $SetupProgram $PublishDir $Version $setupExe @fast }
}
finally {
Pop-Location
}
if (-not (Test-Path $setupExe)) { throw "make-setup did not write $setupExe" }
+if ($sign) {
+ & $sign -Path $setupExe -CertificateThumbprint $CertificateThumbprint
+}
if ($CheckOnly) {
# Install, update and uninstall in a sandbox: a registry file and folders of its own, no administrator rights.
diff --git a/build/sign-release.ps1 b/build/sign-release.ps1
new file mode 100644
index 00000000..c7d32476
--- /dev/null
+++ b/build/sign-release.ps1
@@ -0,0 +1,102 @@
+<#
+.SYNOPSIS
+ Signs a release's Windows files and adds them to its draft on GitHub: run on a PC signed in to SimplySign Desktop
+ once the release workflow of the tag has finished.
+
+.DESCRIPTION
+ The release workflow tests and builds the tag, keeps the unsigned Windows build (artifact windows-unsigned: the
+ publish folder and the Setup program) and drafts the release with the Linux and macOS packages. This script:
+
+ 1. downloads that build, exactly as it was tested;
+ 2. checks out the tag in a worktree and runs its build-installer.ps1 with -CertificateThumbprint, which signs the
+ unsigned programs and the Setup program, packs Setup.exe, signs it, zips the portable copy and writes the
+ SHA-256 sums;
+ 3. installs the signed Setup into a sandbox (nothing on the PC is touched) and checks that Filee.exe and
+ uninstall.exe come out signed, then uninstalls it;
+ 4. uploads Filee-<version>-win-Setup.exe, the portable zip and Filee-<version>-SHA256SUMS.txt to the draft, and
+ with -Publish publishes the release.
+
+ Needs gh (signed in), git and the .NET SDK. Output: build/.cache/release-<version>/out.
+
+.EXAMPLE
+ pwsh build/sign-release.ps1 -Version 2.1.0 -CertificateThumbprint <sha1>
+ pwsh build/sign-release.ps1 -Version 2.1.0 -Publish
+#>
+[CmdletBinding()]
+param(
+ [Parameter(Mandatory)]
+ [string]$Version,
+ # Defaults to $env:FILEE_SIGNING_CERT (see sign-windows.ps1).
+ [string]$CertificateThumbprint = $env:FILEE_SIGNING_CERT,
+ [switch]$Publish
+)
+
+$ErrorActionPreference = 'Stop'
+if (-not $IsWindows) { throw 'Windows releases are signed on Windows.' }
+if (-not $CertificateThumbprint) { throw 'Pass -CertificateThumbprint or set FILEE_SIGNING_CERT.' }
+$root = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
+$Version = $Version.TrimStart('v')
+$tag = "v$Version"
+
+function Invoke-Checked([string]$what, [scriptblock]$command) {
+ & $command
+ if ($LASTEXITCODE -ne 0) { throw "$what failed with exit code $LASTEXITCODE" }
+}
+
+# The draft and the run that made it.
+$release = gh release view $tag --json isDraft | ConvertFrom-Json
+if (-not $release.isDraft) { throw "$tag is already published." }
+$run = gh run list --workflow release.yml --branch $tag --limit 1 --json databaseId,status,conclusion | ConvertFrom-Json | Select-Object -First 1
+if (-not $run) { throw "No release workflow run for $tag." }
+if ($run.status -ne 'completed' -or $run.conclusion -ne 'success') { throw "The release run $($run.databaseId) is $($run.status) ($($run.conclusion))." }
+
+$work = Join-Path $PSScriptRoot ".cache\release-$Version"
+$source = Join-Path $work 'source'
+if (Test-Path $source) { Invoke-Checked 'git worktree remove' { git -C $root worktree remove --force $source } }
+Remove-Item $work -Recurse -Force -ErrorAction SilentlyContinue
+New-Item -ItemType Directory -Force -Path $work | Out-Null
+
+Write-Host "download the unsigned build of run $($run.databaseId)"
+Invoke-Checked 'gh run download' { gh run download $run.databaseId --name windows-unsigned --dir (Join-Path $work 'unsigned') }
+
+Invoke-Checked 'git fetch' { git -C $root fetch --quiet origin "refs/tags/${tag}:refs/tags/$tag" }
+Invoke-Checked 'git worktree add' { git -C $root worktree add --detach $source $tag }
+try {
+ $out = Join-Path $work 'out'
+ & (Join-Path $source 'build\build-installer.ps1') -Version $Version -Portable -OutputDir $out `
+ -PublishDir (Join-Path $work 'unsigned\app') -SetupProgram (Join-Path $work 'unsigned\Filee.Setup.exe') `
+ -CertificateThumbprint $CertificateThumbprint
+}
+finally {
+ git -C $root worktree remove --force $source
+}
+
+$setup = Join-Path $out "Filee-$Version-win-Setup.exe"
+$files = @($setup, (Join-Path $out "Filee-$Version-win-Portable.zip"), (Join-Path $out "Filee-$Version-SHA256SUMS.txt"))
+foreach ($file in $files) { if (-not (Test-Path $file)) { throw "$file was not written." } }
+
+# The signed Setup still finds its payload, and what it installs is signed, the uninstaller too.
+$sandbox = Join-Path $work 'sandbox'
+function Invoke-Setup([string]$exe) {
+ $process = Start-Process -FilePath $exe -ArgumentList @('/VERYSILENT', '/SUPPRESSMSGBOXES', "/SANDBOX=`"$sandbox`"") -Wait -PassThru
+ if ($process.ExitCode -ne 0) { throw "$(Split-Path $exe -Leaf) failed in the sandbox with exit code $($process.ExitCode) (logs: $sandbox\Temp)" }
+}
+Write-Host 'install the signed Setup into a sandbox'
+Invoke-Setup $setup
+$installed = Join-Path $sandbox 'Program Files\Filee'
+foreach ($file in 'Filee.exe', 'filee-cli.exe', 'uninstall.exe', 'engines\rhwp\rhwp.exe') {
+ $signature = Get-AuthenticodeSignature (Join-Path $installed $file)
+ if ($signature.Status -ne 'Valid') { throw "$file is not signed after installing ($($signature.Status))." }
+}
+Invoke-Setup (Join-Path $installed 'uninstall.exe')
+Remove-Item $sandbox -Recurse -Force -ErrorAction SilentlyContinue
+
+Write-Host "upload to the draft of $tag"
+Invoke-Checked 'gh release upload' { gh release upload $tag @files --clobber }
+if ($Publish) {
+ Invoke-Checked 'gh release edit' { gh release edit $tag --draft=false --latest }
+ Write-Host "published $tag"
+}
+else {
+ Write-Host "$tag is still a draft: check it on GitHub, then publish it there or run again with -Publish."
+}
diff --git a/build/sign-windows.ps1 b/build/sign-windows.ps1
new file mode 100644
index 00000000..ee269cdc
--- /dev/null
+++ b/build/sign-windows.ps1
@@ -0,0 +1,98 @@
+<#
+.SYNOPSIS
+ Signs Windows programs with Filee's code signing certificate: Authenticode, SHA-256, with a timestamp from Certum.
+
+.DESCRIPTION
+ Signs every .exe and .dll under -Path (files or folders) that has no valid signature yet: Filee's own programs, and
+ the bundled ones that come unsigned (rhwp, 7-Zip, most NuGet libraries). Files their makers signed (.NET, Microsoft,
+ ImageMagick …) keep their signature. Afterwards every program under -Path must have a valid signature.
+
+ The certificate's key is in Certum's SimplySign cloud: sign in to SimplySign Desktop (with the token from the
+ SimplySign phone app) before running this. signtool comes from the Microsoft.Windows.SDK.BuildTools NuGet package,
+ downloaded once into build/.cache.
+
+.PARAMETER CertificateThumbprint
+ SHA-1 thumbprint of the certificate ("Cert Hash(sha1)" in certutil -user -store My). Defaults to
+ $env:FILEE_SIGNING_CERT.
+
+.EXAMPLE
+ pwsh build/sign-windows.ps1 -Path publish\win-x64 -CertificateThumbprint <sha1>
+#>
+[CmdletBinding()]
+param(
+ [Parameter(Mandatory)]
+ [string[]]$Path,
+ [string]$CertificateThumbprint = $env:FILEE_SIGNING_CERT
+)
+
+$ErrorActionPreference = 'Stop'
+if (-not $IsWindows) { throw 'Authenticode signing needs Windows.' }
+if (-not $CertificateThumbprint) { throw 'Pass -CertificateThumbprint or set FILEE_SIGNING_CERT.' }
+$CertificateThumbprint = $CertificateThumbprint -replace '\s', ''
+
+$certificate = Get-Item "Cert:\CurrentUser\My\$CertificateThumbprint" -ErrorAction SilentlyContinue
+if (-not $certificate) {
+ throw "Certificate $CertificateThumbprint is not in the current user's store. Sign in to SimplySign Desktop first."
+}
+if ($certificate.NotAfter -lt (Get-Date)) { throw "Certificate $CertificateThumbprint expired on $($certificate.NotAfter)." }
+
+# signtool from the Windows SDK build tools, pinned by version and SHA-256 like the engines (fetch-engines.ps1).
+$sdkVersion = '10.0.28000.2526'
+$sdkSha256 = 'a09a4c9d68160ced4765137a9a7444ea560ea86c45d6a77093dea58c2f7563a0'
+$toolFolder = Join-Path $PSScriptRoot ".cache\signtool-$sdkVersion"
+$signtool = Join-Path $toolFolder 'signtool.exe'
+if (-not (Test-Path $signtool)) {
+ $package = Join-Path $PSScriptRoot ".cache\microsoft.windows.sdk.buildtools.$sdkVersion.nupkg"
+ New-Item -ItemType Directory -Force -Path (Split-Path $package) | Out-Null
+ Write-Host "get Microsoft.Windows.SDK.BuildTools $sdkVersion (signtool)"
+ Invoke-WebRequest "https://api.nuget.org/v3-flatcontainer/microsoft.windows.sdk.buildtools/$sdkVersion/microsoft.windows.sdk.buildtools.$sdkVersion.nupkg" -OutFile $package
+ $actual = (Get-FileHash $package -Algorithm SHA256).Hash.ToLowerInvariant()
+ if ($actual -ne $sdkSha256) {
+ Remove-Item $package
+ throw "Microsoft.Windows.SDK.BuildTools $sdkVersion has SHA-256 $actual, expected $sdkSha256."
+ }
+ Add-Type -AssemblyName System.IO.Compression.FileSystem
+ $zip = [System.IO.Compression.ZipFile]::OpenRead($package)
+ try {
+ New-Item -ItemType Directory -Force -Path $toolFolder | Out-Null
+ foreach ($entry in $zip.Entries | Where-Object { $_.FullName -match '^bin/[^/]+/x64/[^/]+$' }) {
+ [System.IO.Compression.ZipFileExtensions]::ExtractToFile($entry, (Join-Path $toolFolder $entry.Name), $true)
+ }
+ }
+ finally {
+ $zip.Dispose()
+ }
+ if (-not (Test-Path $signtool)) { throw "signtool.exe is not in Microsoft.Windows.SDK.BuildTools $sdkVersion." }
+}
+
+$programs = @(foreach ($item in $Path) {
+ $resolved = (Resolve-Path $item).Path
+ if (Test-Path $resolved -PathType Container) {
+ Get-ChildItem $resolved -Recurse -File -Include *.exe, *.dll | ForEach-Object FullName
+ }
+ else {
+ $resolved
+ }
+ })
+$unsigned = @($programs | Where-Object { (Get-AuthenticodeSignature $_).Status -ne 'Valid' })
+Write-Host "sign $($unsigned.Count) of $($programs.Count) programs (the others are signed by their makers)"
+
+# Several files per signtool run: each one is still signed in the cloud, but the session is opened once.
+$batch = 40
+$options = @('sign', '/sha1', $CertificateThumbprint, '/fd', 'sha256', '/tr', 'http://time.certum.pl', '/td', 'sha256',
+ '/d', 'Filee', '/du', 'https://filee.sh', '/q')
+for ($i = 0; $i -lt $unsigned.Count; $i += $batch) {
+ $files = @($unsigned[$i..([Math]::Min($i + $batch, $unsigned.Count) - 1)])
+ & $signtool @options @files
+ if ($LASTEXITCODE -ne 0) {
+ # The cloud or the timestamp server can drop a request: once more for what is still unsigned.
+ $files = @($files | Where-Object { (Get-AuthenticodeSignature $_).Status -ne 'Valid' })
+ & $signtool @options @files
+ if ($LASTEXITCODE -ne 0) { throw "signtool failed with exit code $LASTEXITCODE" }
+ }
+ Write-Host " $([Math]::Min($i + $batch, $unsigned.Count))/$($unsigned.Count)"
+}
+
+$bad = @($programs | Where-Object { (Get-AuthenticodeSignature $_).Status -ne 'Valid' })
+if ($bad.Count) { throw "Not signed: $($bad -join ', ')" }
+Write-Host "all $($programs.Count) programs are signed"
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 4a7c9e40..afbf19bd 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -320,8 +320,11 @@ have no semibold) instead of the app's embedded Noto fonts.
(`SetupPayload`): ~48 MB segments compressed in parallel with SharpCompress's LZMA (48 MB dictionary), programs
first through the x86 branch filter (`X86Filter`, from the LZMA SDK) as 7-Zip and Inno Setup do. The manifest lists
every file with its size, SHA-256 and filter, the SHA-256 of the compressed data, the version and the engines to
- offer (from `EngineDownloads`). A future signature goes after the trailer (Setup looks
- for the trailer in front of the certificate table), so sign after packing. The code is trim- and AOT-safe
+ offer (from `EngineDownloads`). Setup.exe's signature goes after the trailer (Setup looks
+ for the trailer in front of the certificate table; the manifest is padded so the file ends on the 8-byte boundary
+ signtool needs), so Setup.exe is signed after packing. The Setup program is signed before: its signature stays at
+ the end of the program, Setup.exe's header stops pointing to it, and the manifest's `programSignature` lets the
+ uninstaller copied out of Setup.exe (`CopyProgramTo`) point to it again, so `uninstall.exe` is signed too. The code is trim- and AOT-safe
(compiled bindings, source-generated P/Invoke and COM); Native AOT would need the MSVC linker on the build machine
and still couldn't link SkiaSharp's native libraries in.
- **Rights**: Setup starts unelevated (asInvoker) and, for an install for all users, starts itself again with
diff --git a/src/Filee.Setup/Payload/PayloadManifest.cs b/src/Filee.Setup/Payload/PayloadManifest.cs
index ad940e9b..cf6095b4 100644
--- a/src/Filee.Setup/Payload/PayloadManifest.cs
+++ b/src/Filee.Setup/Payload/PayloadManifest.cs
@@ -18,8 +18,16 @@ public sealed record PayloadFile(string Path, long Size, string Sha256, int Segm
/// <param name="MarkerFolders">Folders under %LocalAppData%\Filee\engines that are all marked when it is installed.</param>
public sealed record EngineOffer(string Id, IReadOnlyList<string> MarkerFolders, long DownloadSize, long InstalledSize, bool Suggested);
+/// <summary>
+/// Where the Setup program's own Authenticode signature (its certificate table) sits: the last bytes of the program,
+/// in front of the payload. Setup.exe doesn't point to it (Setup.exe carries a signature of its own at the end); the
+/// uninstaller copied out of Setup.exe points to it again, so it is signed too.
+/// </summary>
+public sealed record ProgramSignature(long Offset, int Size);
+
/// <param name="Segments">Compressed length of each LZMA stream, one after the other in the payload.</param>
/// <param name="LzmaProperties">The 5 bytes of LZMA properties every stream was written with (base64).</param>
+/// <param name="Signature">The Setup program's signature, when it was signed before the payload was appended.</param>
public sealed record PayloadManifest(
string Version,
IReadOnlyList<PayloadFile> Files,
@@ -27,7 +35,8 @@ public sealed record PayloadManifest(
IReadOnlyList<EngineOffer> Engines,
string EngineMarker,
IReadOnlyList<long> Segments,
- string LzmaProperties)
+ string LzmaProperties,
+ ProgramSignature? Signature = null)
{
/// <summary>Format of the payload; a Setup refuses a payload with another one.</summary>
public const int CurrentFormat = 1;
@@ -46,6 +55,13 @@ public sealed record PayloadManifest(
writer.WriteString("lzmaProperties", LzmaProperties);
writer.WriteString("compressedSha256", CompressedSha256);
writer.WriteString("engineMarker", EngineMarker);
+ if (Signature is not null)
+ {
+ writer.WriteStartObject("programSignature");
+ writer.WriteNumber("offset", Signature.Offset);
+ writer.WriteNumber("size", Signature.Size);
+ writer.WriteEndObject();
+ }
writer.WriteStartArray("segments");
foreach (var segment in Segments)
writer.WriteNumberValue(segment);
@@ -119,6 +135,13 @@ public sealed record PayloadManifest(
e.GetProperty("installedSize").GetInt64(),
e.GetProperty("suggested").GetBoolean())).ToList()
: [];
+ ProgramSignature? signature = null;
+ if (root.TryGetProperty("programSignature", out var signed))
+ {
+ signature = new ProgramSignature(signed.GetProperty("offset").GetInt64(), signed.GetProperty("size").GetInt32());
+ if (signature.Offset <= 0 || signature.Size <= 0)
+ throw new InvalidDataException("Bad program signature in the payload.");
+ }
return new PayloadManifest(
root.GetProperty("version").GetString()!,
files,
@@ -126,7 +149,8 @@ public sealed record PayloadManifest(
engines,
root.TryGetProperty("engineMarker", out var marker) ? marker.GetString() ?? "" : "",
segments,
- properties);
+ properties,
+ signature);
}
catch (Exception ex) when (ex is JsonException or KeyNotFoundException or InvalidOperationException or NullReferenceException or FormatException)
{
diff --git a/src/Filee.Setup/Payload/SetupPayload.cs b/src/Filee.Setup/Payload/SetupPayload.cs
index c1678fe3..17298372 100644
--- a/src/Filee.Setup/Payload/SetupPayload.cs
+++ b/src/Filee.Setup/Payload/SetupPayload.cs
@@ -3,6 +3,10 @@
// [Setup program][LZMA streams: the app's files, one after the other][manifest JSON][trailer, 72 bytes]
// (then, once Setup is signed, the Authenticode signature: the trailer sits right before it)
//
+// A release signs the Setup program first (it becomes the uninstaller) and Setup.exe last. The program's signature
+// stays at the end of the program, Setup.exe's header stops pointing to it, and the manifest says where it is so the
+// uninstaller written from Setup.exe is signed as well.
+//
// Trailer: "FILEE-PAYLOAD-01", payload offset, compressed length, manifest length (little-endian Int64 each) and the
// SHA-256 of the manifest. The manifest holds the SHA-256 of the compressed data and of every file. Files are packed
// into a few large LZMA streams (segments, compressed in parallel; SharpCompress, which the engines use already)
@@ -92,38 +96,69 @@ public sealed class SetupPayload : IDisposable
/// appends the certificate table after the payload).
/// </summary>
internal static long OverlayEnd(Stream file)
+ {
+ var length = file.Length;
+ var signature = Signature(file);
+ return signature is null ? length : signature.Offset;
+ }
+
+ /// <summary>The certificate table a PE file ends with (its Authenticode signature), or null.</summary>
+ internal static ProgramSignature? Signature(Stream file)
+ {
+ var entry = SecurityDirectory(file);
+ if (entry < 0)
+ return null;
+ Span<byte> buffer = stackalloc byte[8];
+ file.Position = entry;
+ file.ReadExactly(buffer);
+ var certificates = BinaryPrimitives.ReadUInt32LittleEndian(buffer);
+ var size = BinaryPrimitives.ReadUInt32LittleEndian(buffer[4..]);
+ // The certificate table's "address" is a file offset.
+ return certificates > 0 && size > 0 && certificates + (long)size == file.Length ? new ProgramSignature(certificates, (int)size) : null;
+ }
+
+ /// <summary>File position of the PE header's security directory entry (IMAGE_DIRECTORY_ENTRY_SECURITY), or -1.</summary>
+ private static long SecurityDirectory(Stream file)
{
var length = file.Length;
try
{
- Span<byte> buffer = stackalloc byte[8];
+ Span<byte> buffer = stackalloc byte[4];
file.Position = 0x3C;
- file.ReadExactly(buffer[..4]);
+ file.ReadExactly(buffer);
var pe = BinaryPrimitives.ReadInt32LittleEndian(buffer);
if (pe <= 0 || pe > length - 24)
- return length;
+ return -1;
file.Position = pe;
- file.ReadExactly(buffer[..4]);
+ file.ReadExactly(buffer);
if (BinaryPrimitives.ReadUInt32LittleEndian(buffer) != 0x00004550) // "PE\0\0"
- return length;
+ return -1;
var optionalHeader = pe + 4 + 20;
file.Position = optionalHeader;
file.ReadExactly(buffer[..2]);
var magic = BinaryPrimitives.ReadUInt16LittleEndian(buffer);
- var directories = optionalHeader + (magic == 0x20B ? 112 : 96);
- file.Position = directories + 4 * 8; // IMAGE_DIRECTORY_ENTRY_SECURITY
- file.ReadExactly(buffer);
- var certificates = BinaryPrimitives.ReadUInt32LittleEndian(buffer);
- var size = BinaryPrimitives.ReadUInt32LittleEndian(buffer[4..]);
- // The certificate table's "address" is a file offset.
- return certificates > 0 && certificates + (long)size == length ? certificates : length;
+ var entry = optionalHeader + (magic == 0x20B ? 112 : 96) + 4 * 8;
+ return entry + 8 <= length ? entry : -1;
}
catch (EndOfStreamException)
{
- return length;
+ return -1;
}
}
+ /// <summary>Points the security directory of the PE file in <paramref name="file"/> at a certificate table (null: none).</summary>
+ private static void SetSecurityDirectory(Stream file, ProgramSignature? signature)
+ {
+ var entry = SecurityDirectory(file);
+ if (entry < 0)
+ throw new InvalidDataException("The Setup program is not a PE file.");
+ Span<byte> buffer = stackalloc byte[8];
+ BinaryPrimitives.WriteUInt32LittleEndian(buffer, (uint)(signature?.Offset ?? 0));
+ BinaryPrimitives.WriteUInt32LittleEndian(buffer[4..], (uint)(signature?.Size ?? 0));
+ file.Position = entry;
+ file.Write(buffer);
+ }
+
/// <summary>Checks the compressed stream against the manifest. Throws <see cref="InvalidDataException"/>.</summary>
public void Verify(IProgress<double>? progress = null, CancellationToken cancellation = default)
{
@@ -249,13 +284,22 @@ public sealed class SetupPayload : IDisposable
}
}
- /// <summary>Writes the Setup program without the payload: the uninstaller.</summary>
+ /// <summary>
+ /// Writes the Setup program without the payload: the uninstaller. A program signed before the payload was
+ /// appended gets its own signature back.
+ /// </summary>
public void CopyProgramTo(string path)
{
_file.Position = 0;
- using var output = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, BufferSize);
- using var program = new BoundedReadStream(_file, Offset);
- program.CopyTo(output, BufferSize);
+ using var output = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, BufferSize);
+ using (var program = new BoundedReadStream(_file, Offset))
+ program.CopyTo(output, BufferSize);
+ if (Manifest.Signature is { } signature)
+ {
+ if (signature.Offset + signature.Size != Offset)
+ throw new InvalidDataException("The program signature in the payload doesn't fit the program.");
+ SetSecurityDirectory(output, signature);
+ }
}
public void Dispose() => _file.Dispose();
@@ -342,13 +386,20 @@ public sealed class SetupPayload : IDisposable
var partial = output + ".partial";
using (var target = new FileStream(partial, FileMode.Create, FileAccess.ReadWrite, FileShare.None, BufferSize))
{
+ // A signed program keeps its signature in front of the payload, but Setup.exe stops pointing to it: the
+ // signature of the whole Setup.exe goes at the end. The uninstaller (CopyProgramTo) points to it again.
+ ProgramSignature? signature;
using (var program = File.OpenRead(setupProgram))
{
- if (SetupPayload.OverlayEnd(program) != program.Length)
- throw new InvalidOperationException("Sign Setup after appending the payload, not before.");
+ signature = Signature(program);
program.Position = 0;
program.CopyTo(target);
}
+ if (signature is not null)
+ {
+ SetSecurityDirectory(target, null);
+ target.Seek(0, SeekOrigin.End);
+ }
var offset = target.Position;
using var compressedHash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
foreach (var segment in compressed)
@@ -358,8 +409,13 @@ public sealed class SetupPayload : IDisposable
}
var length = target.Position - offset;
var manifest = new PayloadManifest(version, hashed.SelectMany(f => f).ToList(), PayloadManifest.Hex(compressedHash.GetHashAndReset()),
- engines, engineMarker, compressed.Select(c => (long)c.Length).ToList(), Convert.ToBase64String(properties ?? []));
+ engines, engineMarker, compressed.Select(c => (long)c.Length).ToList(), Convert.ToBase64String(properties ?? []), signature);
var json = manifest.ToJson();
+ // Spaces after the JSON end the file on an 8-byte boundary: signtool puts the certificate table there and
+ // would pad in front of it otherwise, and the trailer has to sit right before the table.
+ var padding = (int)((8 - (target.Position + json.Length + TrailerLength) % 8) % 8);
+ if (padding > 0)
+ json = [.. json, .. Enumerable.Repeat((byte)' ', padding)];
target.Write(json);
var trailer = new byte[TrailerLength];
Encoding.ASCII.GetBytes(Magic).CopyTo(trailer, 0);
diff --git a/tests/Filee.Setup.Tests/PayloadTests.cs b/tests/Filee.Setup.Tests/PayloadTests.cs
index c8335737..7f2e0656 100644
--- a/tests/Filee.Setup.Tests/PayloadTests.cs
+++ b/tests/Filee.Setup.Tests/PayloadTests.cs
@@ -200,20 +200,35 @@ public class PayloadTests
}
[Fact]
- public void A_signed_program_cannot_get_a_payload()
+ public void A_signed_program_becomes_a_signed_uninstaller()
{
- // Signing has to come last: a payload behind the signature would not be covered by it.
+ // A release signs the Setup program, then Setup.exe: Setup.exe's header no longer points to the program's
+ // signature (its own goes at the end), and the uninstaller copied out of it points to it again.
using var temp = new TempFolder();
temp.Write(@"app\Filee.exe", "Filee");
var program = temp.Sub("program.exe");
var bytes = MinimalPe(0, 0);
var pe = BinaryPrimitives.ReadInt32LittleEndian(bytes.AsSpan(0x3C));
- var withCertificates = new byte[bytes.Length + 64];
- bytes.CopyTo(withCertificates, 0);
- BinaryPrimitives.WriteUInt32LittleEndian(withCertificates.AsSpan(pe + 4 + 20 + 112 + 32), (uint)bytes.Length);
- BinaryPrimitives.WriteUInt32LittleEndian(withCertificates.AsSpan(pe + 4 + 20 + 112 + 36), 64);
- File.WriteAllBytes(program, withCertificates);
- Assert.Throws<InvalidOperationException>(() => SetupPayload.Write(program, temp.Sub("app"), temp.Sub("out.exe"), "2.0.0", [], ""));
+ var security = pe + 4 + 20 + 112 + 32;
+ var signed = new byte[bytes.Length + 64];
+ bytes.CopyTo(signed, 0);
+ BinaryPrimitives.WriteUInt32LittleEndian(signed.AsSpan(security), (uint)bytes.Length);
+ BinaryPrimitives.WriteUInt32LittleEndian(signed.AsSpan(security + 4), 64);
+ File.WriteAllBytes(program, signed);
+
+ var setup = temp.Sub("setup.exe");
+ SetupPayload.Write(program, temp.Sub("app"), setup, "2.0.0", [], "", fast: true);
+ var written = File.ReadAllBytes(setup);
+ Assert.Equal(0u, BinaryPrimitives.ReadUInt64LittleEndian(written.AsSpan(security)));
+ // signtool adds the certificate table at the end without padding in front of it.
+ Assert.Equal(0, written.Length % 8);
+
+ using var payload = SetupPayload.Open(setup)!;
+ Assert.Equal(new ProgramSignature(bytes.Length, 64), payload.Manifest.Signature);
+ payload.Verify(cancellation: TestContext.Current.CancellationToken);
+ var uninstaller = temp.Sub("uninstall.exe");
+ payload.CopyProgramTo(uninstaller);
+ Assert.Equal(signed, File.ReadAllBytes(uninstaller));
}
/// <summary>DOS header + PE32+ headers without sections (enough for the overlay and import readers).</summary>