Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 25 additions & 5 deletions .github/workflows/build-electron.yml
Original file line number Diff line number Diff line change
Expand Up @@ -133,10 +133,21 @@ jobs:
release:
needs: prepare
runs-on: ${{ matrix.os }}
# Azure's federated credential trusts OIDC tokens whose subject names the `signing` environment (a tag ref
# changes every release), so only the leg that signs with Azure runs there; the others cannot mint such a token.
environment: ${{ matrix.os == 'windows-latest' && !inputs.skip_signing && vars.AZURE_SIGN_ENDPOINT != '' && 'signing' || 'build' }}
permissions:
contents: write
id-token: write
env:
GH_TOKEN: ${{ needs.prepare.outputs.release_repo != github.repository && secrets.RELEASE_TOKEN || secrets.github_token }}
VERSION: ${{ needs.prepare.outputs.version }}
RELEASE_REPO: ${{ needs.prepare.outputs.release_repo }}
# See RELEASE.md, "Windows code signing".
AZURE_SIGN_ENDPOINT: ${{ vars.AZURE_SIGN_ENDPOINT }}
AZURE_SIGN_ACCOUNT: ${{ vars.AZURE_SIGN_ACCOUNT }}
AZURE_SIGN_PROFILE: ${{ vars.AZURE_SIGN_PROFILE }}
AZURE_SIGN_PUBLISHER: ${{ vars.AZURE_SIGN_PUBLISHER }}

strategy:
# One platform failing should not cancel the others - a Linux packaging
Expand Down Expand Up @@ -168,11 +179,19 @@ jobs:

- name: Install SSL.com Sign Tool on Windows
shell: bash
if: matrix.os == 'windows-latest' && !inputs.skip_signing
if: matrix.os == 'windows-latest' && !inputs.skip_signing && vars.AZURE_SIGN_ENDPOINT == ''
run: |
curl https://www.ssl.com/download/codesigntool-for-windows/ --output ~/Downloads/CodeSignTool.zip
unzip ~/Downloads/CodeSignTool.zip -d ~/CodeSignTool

- name: Sign in to Azure for Windows signing
if: matrix.os == 'windows-latest' && !inputs.skip_signing && vars.AZURE_SIGN_ENDPOINT != ''
uses: azure/login@v2
with:
client-id: ${{ secrets.AZURE_CLIENT_ID }}
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}

- name: Install dependencies and build web assets
run: |
npm install
Expand Down Expand Up @@ -201,9 +220,10 @@ jobs:
cd electron
npm run build

# nsis7z silently skips payload entries it cannot decode (3.47.1/3.48.1 ARM64). electron-builder
# has already attached the installers to the draft, so a failure pulls them back out.
- name: Verify Windows installers extract with nsis7z
# nsis7z silently skips payload entries it cannot decode (3.47.1/3.48.1 ARM64), and a signed build
# must be signed by the expected publisher throughout. electron-builder has already attached the
# installers to the draft, so a failure pulls them back out.
- name: Verify Windows installers (payload, signatures)
if: matrix.os == 'windows-latest'
run: |
cd electron
Expand All @@ -212,7 +232,7 @@ jobs:
for f in dist/*-Installer-*.exe dist/*-Installer-*.exe.blockmap dist/latest.yml; do
[ -e "$f" ] && gh release delete-asset "$VERSION" "$(basename "$f")" --repo "$RELEASE_REPO" --yes 2>/dev/null || true
done
echo "::error::Windows installers removed from draft $VERSION in $RELEASE_REPO - their payload cannot be extracted by nsis7z (see above)"
echo "::error::Windows installers removed from draft $VERSION in $RELEASE_REPO - they failed verification (see above)"
fi
exit 1
fi
Expand Down
51 changes: 51 additions & 0 deletions RELEASE.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,8 @@ publishes into it. Checking `build_main` builds `main` itself instead; that, and
a run on any other branch, compiles and discards everything, so with
`skip_signing` off the `prepare` job refuses to start rather than pay for
signatures nobody receives.
Which certificate signs a Windows build, and how the result is checked, is under
[Windows code signing](#windows-code-signing).

A `prepare` job first resolves the release repository for the selected brand
(`brands/<brand>/config.ts` — `cachengo` publishes to `cachengo/desktop`) and
Expand Down Expand Up @@ -229,6 +231,55 @@ back into `main` first.
Amplify builds the branch from `amplify.yml` in this repo. A branch that
contains it ignores the build settings in the Amplify console.

## Windows code signing

electron-builder reads a config file _instead of_ package.json's `build`, never
both, so `electron/electron-builder.config.js` spreads the branded `build` and
adds only the signing part, chosen from the environment by
`electron/scripts/win-signing.js`:

- **`SKIP_SIGNING=true`** (the `skip_signing` input): no signing configuration
at all. Nothing is signed and nothing is verified. The config file also loads
`electron/.env`, which electron-builder itself would not, so a local build
that sets it there is unsigned too.
- **`AZURE_SIGN_*` set**: `win.azureSignOptions` — Microsoft Artifact Signing.
- **Otherwise**: package.json's `build` untouched, i.e. the SSL.com eSigner hook
in `scripts/sign.js`.

The Azure side is four repository **variables** — `AZURE_SIGN_ENDPOINT` (the
per-region URL, e.g. `https://wus2.codesigning.azure.net`), `AZURE_SIGN_ACCOUNT`,
`AZURE_SIGN_PROFILE`, and `AZURE_SIGN_PUBLISHER` (the certificate subject,
verbatim) — and three **secrets** for `azure/login`: `AZURE_CLIENT_ID`,
`AZURE_TENANT_ID`, `AZURE_SUBSCRIPTION_ID`. Login is OIDC through the `signing`
environment the `release` job runs in, so there is no client secret anywhere.
Setting all four variables is the switch; unset, SSL.com keeps signing; set only
some of them and the build fails rather than guess.

An Azure-signed build also writes `publisherName` into the app's
`app-update.yml`: the new subject and the SSL.com name `remot3.it, Inc.`. From
that build on, the updater verifies the **next** installer's signature against
that list before running it. Nothing shipped since 3.15 verifies anything today
(the eSigner hook gave electron-builder no certificate to derive a name from), so
the first Azure-signed release installs everywhere and the second is the one that
proves the list. Keep the SSL.com name in the list until that certificate is
retired, so a hotfix signed with it still installs over an Azure-signed release.

After every signed Windows build, `verify-win-installers.js` runs
`Get-AuthenticodeSignature` — the cmdlet electron-updater's own check is built
on — over each installer and the executables inside its payload
(`Remote.It.exe`, `remoteit.exe`, `connectd.exe`, `muxer.exe`, `demuxer.exe`;
electron-builder signs all of them) and reports any signature that is not valid,
timestamped, and from an expected publisher. Under Azure that fails the build
and removes the installers from the draft; under SSL.com it is a `::warning::`
annotation only, because eSigner bills per signature and a finding must never
force a re-sign. This is the guard; electron-builder's `forceCodeSigning` cannot
be, since it only fires when no signing configuration exists at all. The
expected publisher is `AZURE_SIGN_PUBLISHER` when set and the SSL.com name
otherwise — under Azure the SSL.com name is *not* accepted, so a build that was
still signed by eSigner cannot pass as migrated — matched by electron-updater's
rule: a full distinguished name must agree on every attribute it lists, a bare
name must equal the certificate's CN.

## Windows installer payloads

The app payload inside each NSIS installer is a 7z archive that NSIS extracts with
Expand Down
8 changes: 8 additions & 0 deletions electron/electron-builder.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// electron-builder loads electron-builder.env, not the .env that sign.js reads; without this a local
// SKIP_SIGNING=true build would be configured to sign while the hook skips.
require('dotenv').config()
// electron-builder reads either a config file or package.json's `build`, never both, so this
// spreads the branded package.json config and adds only what depends on the environment.
const { withSigning } = require('./scripts/win-signing')

module.exports = withSigning(require('./package.json').build, process.env)
2 changes: 1 addition & 1 deletion electron/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
"build": "cross-env NODE_ENV=production run-s build-frontend brand copy-install copy-entitlements compile verify-binaries build-electron",
"build-local": "cross-env NODE_ENV=production run-s copy-env clean build-frontend brand copy-install copy-entitlements compile verify-binaries build-electron",
"build-frontend": "cd ../ && npm run build-frontend",
"build-electron": "cross-env NODE_ARCH=$npm_config_arch ELECTRON_BUILDER_7Z_FILTER=BCJ2 electron-builder",
"build-electron": "cross-env NODE_ARCH=$npm_config_arch ELECTRON_BUILDER_7Z_FILTER=BCJ2 electron-builder --config electron-builder.config.js",
"clean": "rimraf build/* dist/*",
"compile": "run-s typecheck-common typecheck sync-assets",
"verify-binaries": "node ./scripts/verify-binaries.js",
Expand Down
76 changes: 70 additions & 6 deletions electron/scripts/verify-win-installers.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
#!/usr/bin/env node

// nsis7z (built 2019) silently skips payload entries it cannot decode; 3.47.1 and 3.48.1 lost
// every executable on Windows ARM64 that way. See RELEASE.md, "Windows installer payloads".
// every executable on Windows ARM64 that way. See RELEASE.md, "Windows installer payloads" and
// "Windows code signing".

const fs = require('fs')
const os = require('os')
const path = require('path')
const { spawnSync } = require('child_process')
const { archsOf, binaryNames } = require('./verify-binaries')
const { signingMode, expectedPublisher, publisherMatches } = require('./win-signing')

const NSIS7Z_CODERS = new Set([
'LZMA',
Expand All @@ -30,8 +32,14 @@ const PRODUCT_NAME = process.env.PRODUCT_NAME || require(path.join(__dirname, '.
const INSTALLER = new RegExp(
`^${PRODUCT_NAME.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}-Installer-(${archsOf('win').join('|')})\\.exe$`
)
const REQUIRED = [`${PRODUCT_NAME}.exe`, 'resources/app.asar', ...binaryNames.map(name => `resources/${name}.exe`)]
const EXECUTABLES = [`${PRODUCT_NAME}.exe`, ...binaryNames.map(name => `resources/${name}.exe`)]
const REQUIRED = [...EXECUTABLES, 'resources/app.asar']
const SEVEN_Z_MAGIC = Buffer.from([0x37, 0x7a, 0xbc, 0xaf, 0x27, 0x1c])
const MODE = signingMode(process.env)
const CHECK_SIGNATURES = MODE !== 'skip' && process.platform === 'win32'
// eSigner bills per signature: under SSL.com a signature finding is reported, never a reason to re-sign.
const ENFORCE_SIGNATURES = MODE === 'azure'
const PUBLISHER = MODE === 'skip' ? null : expectedPublisher(process.env)

function sevenZip() {
if (process.env.SEVEN_ZIP) return process.env.SEVEN_ZIP
Expand Down Expand Up @@ -72,8 +80,53 @@ function listEntries(tool, archive) {
return entries
}

// The cmdlet electron-updater's own check is built on (windowsExecutableCodeSignatureVerifier); one
// PowerShell start covers every file of an installer, and the results come back in input order.
function authenticode(files) {
const list = files.map(f => `'${f.replace(/'/g, "''")}'`).join(',')
const command =
'[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false; ' +
`ConvertTo-Json -Compress -InputObject @(Get-AuthenticodeSignature -LiteralPath ${list} | ` +
"Select-Object Status, StatusMessage, @{n='Subject';e={$_.SignerCertificate.Subject}}, " +
"@{n='TimeStamped';e={$null -ne $_.TimeStamperCertificate}})"
const result = spawnSync(
'powershell.exe',
['-NoProfile', '-NonInteractive', '-InputFormat', 'None', '-Command', command],
{
encoding: 'utf8',
timeout: 120000,
}
)
if (result.status !== 0) {
throw new Error(`Get-AuthenticodeSignature failed: ${result.error || result.stderr || result.stdout}`)
}
const signatures = JSON.parse(result.stdout.replace(/^\uFEFF/, ''))
if (signatures.length !== files.length) {
throw new Error(`Get-AuthenticodeSignature returned ${signatures.length} results for ${files.length} files`)
}
return signatures
}

function signatureProblems(tool, installer, payload, dir) {
const out = path.join(dir, path.basename(installer, '.exe'))
const names = EXECUTABLES.map(f => f.split('/').join(path.sep))
const result = spawnSync(tool, ['x', '-y', `-o${out}`, payload, ...names], { encoding: 'utf8' })
if (result.status !== 0) throw new Error(`${tool} x failed for ${payload}: ${result.stderr || result.stdout}`)
const files = [[installer, path.basename(installer)], ...EXECUTABLES.map(f => [path.join(out, ...f.split('/')), f])]
const signatures = authenticode(files.map(([file]) => file))
return files.flatMap(([, label], i) => {
const s = signatures[i]
if (s.Status !== 0) return [`${label}: signature ${s.StatusMessage || s.Status}`]
if (!publisherMatches(s.Subject, [PUBLISHER]))
return [`${label}: signed by "${s.Subject}", expected "${PUBLISHER}"`]
if (!s.TimeStamped) return [`${label}: no timestamp countersignature`]
return []
})
}

function verify(tool, installer, dir) {
const entries = listEntries(tool, extractPayload(installer, dir))
const payload = extractPayload(installer, dir)
const entries = listEntries(tool, payload)
const problems = []
for (const e of entries) {
const bad = e.method
Expand All @@ -84,8 +137,12 @@ function verify(tool, installer, dir) {
}
const present = new Set(entries.map(e => e.path))
for (const f of REQUIRED) if (!present.has(f)) problems.push(`${f}: missing from payload`)
const warnings = []
if (CHECK_SIGNATURES && problems.length === 0) {
;(ENFORCE_SIGNATURES ? problems : warnings).push(...signatureProblems(tool, installer, payload, dir))
}
const coders = [...new Set(entries.flatMap(e => e.method.split(' ').map(t => t.split(':')[0])))].sort().join(' ')
return { entries: entries.length, coders, problems }
return { entries: entries.length, coders, problems, warnings }
}

const distDir = path.resolve(process.argv[2] || 'dist')
Expand All @@ -94,19 +151,26 @@ if (installers.length === 0) {
console.error(`[verify-win-installers] no ${PRODUCT_NAME}-Installer-*.exe in ${distDir}`)
process.exit(1)
}
if (MODE !== 'skip' && !CHECK_SIGNATURES) {
console.log(
'[verify-win-installers] signatures are checked on Windows only (Get-AuthenticodeSignature); skipping that part'
)
}

const tool = sevenZip()
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'win-installers-'))
let failed = false
try {
for (const name of installers) {
const { entries, coders, problems } = verify(tool, path.join(distDir, name), tmp)
const { entries, coders, problems, warnings } = verify(tool, path.join(distDir, name), tmp)
for (const w of warnings) console.log(`::warning::[verify-win-installers] ${name}: ${w}`)
if (problems.length) {
failed = true
console.error(`[verify-win-installers] ${name}: ${entries} entries, coders: ${coders}`)
for (const p of problems) console.error(` - ${p}`)
} else {
console.log(`[verify-win-installers] ${name}: OK (${entries} entries, coders: ${coders})`)
const signed = !CHECK_SIGNATURES ? '' : warnings.length ? ', signature warnings above' : ', signatures verified'
console.log(`[verify-win-installers] ${name}: OK (${entries} entries, coders: ${coders}${signed})`)
}
}
} finally {
Expand Down
61 changes: 61 additions & 0 deletions electron/scripts/win-signing.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// See RELEASE.md, "Windows code signing".

const { parseDn } = require('builder-util-runtime')

// CN of the SSL.com certificate; desktop <= 3.13.4 accepts an update only from exactly this name.
const LEGACY_PUBLISHER = 'remot3.it, Inc.'

const AZURE_VARS = {
endpoint: 'AZURE_SIGN_ENDPOINT',
codeSigningAccountName: 'AZURE_SIGN_ACCOUNT',
certificateProfileName: 'AZURE_SIGN_PROFILE',
publisherName: 'AZURE_SIGN_PUBLISHER',
}

function azureSignOptions(env) {
const options = Object.entries(AZURE_VARS).map(([key, name]) => [key, env[name]])
const missing = options.filter(([, value]) => !value).map(([key]) => AZURE_VARS[key])
if (missing.length === options.length) return null
if (missing.length) throw new Error(`Azure signing is configured but ${missing.join(', ')} not set`)
return Object.fromEntries(options)
}

/** 'skip' | 'azure' | 'signtool' */
function signingMode(env) {
if (env.SKIP_SIGNING === 'true') return 'skip'
return azureSignOptions(env) ? 'azure' : 'signtool'
}

/** The one publisher a build under `env` must be signed by. */
function expectedPublisher(env) {
const azure = azureSignOptions(env)
return azure ? azure.publisherName : LEGACY_PUBLISHER
}

// electron-updater's rule (windowsExecutableCodeSignatureVerifier): a full DN matches when every
// attribute it names equals the signer's; a bare name matches the signer's CN.
function publisherMatches(subject, names) {
const signer = parseDn(subject || '')
return names.some(name => {
const dn = parseDn(name)
return dn.size ? [...dn].every(([key, value]) => signer.get(key) === value) : name === signer.get('CN')
})
}

/** The electron-builder config for this build; `base` is package.json's `build` after branding. */
function withSigning(base, env) {
const win = { ...base.win }
delete win.signtoolOptions
if (env.SKIP_SIGNING === 'true') return { ...base, win }
const azure = azureSignOptions(env)
if (!azure) return base
return {
...base,
win: { ...win, azureSignOptions: azure },
// Lands in app-update.yml as the list an installed app verifies its NEXT update against. The
// SSL.com name stays until that certificate is retired so a hotfix signed with it still installs.
publish: { provider: 'github', ...base.publish, publisherName: [azure.publisherName, LEGACY_PUBLISHER] },
}
}

module.exports = { LEGACY_PUBLISHER, signingMode, expectedPublisher, publisherMatches, withSigning }
3 changes: 2 additions & 1 deletion electron/scripts/windows-upgrade-recover.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ try {
$content = Get-Content $yamlPath -Raw

# REMOVE EXACT BLOCK
$pattern = "(?ms)^publisherName:\s*\n\s*-\s*'.*'\r?\n?"
# electron-builder 23 wrote the entry unquoted (`- remot3.it, Inc.`); the block is the header plus every list line under it.
$pattern = "(?m)^publisherName:[ \t]*\r?\n(?:[ \t]+-[^\r\n]*\r?\n?)+"
$contentModified = [Regex]::Replace($content, $pattern, "")

if ($content -ne $contentModified) {
Expand Down
Loading
Loading