Exemplos — scripts
| Script | Finalidade |
|---|---|
decrypt-bsenc.py | Descriptografar um envelope BSENC v1 — Python 3 |
Decrypt-Bsenc.ps1 | Descriptografar um envelope BSENC v1 — PowerShell 7+ |
Import-PfxToKeyVault.ps1 | Provisionar um PFX para a origem de certificado do Azure Key Vault |
New-BulkSignerEntraApp.ps1 | Provisionar o registro de aplicativo do Microsoft Entra ID para o modo de login opcional |
Import-PfxToKms.ps1 | Provisionar um PFX para a origem de certificado do AWS KMS |
bulksigner-ecs-fargate.yaml | Criar toda a infraestrutura da AWS de uma implantação no ECS Fargate em uma stack do CloudFormation |
Descriptografando envelopes BSENC
Os dois primeiros scripts são implementações de referência do procedimento de descriptografia do BSENC
v1 (veja Criptografia). Os dois recebem a senha, o salt e o número de iterações por
flags de linha de comando, leem o envelope .enc de um caminho e gravam o artefato assinado
descriptografado (em texto claro) em outro caminho.
São implementações de referência — adapte-as ou escreva a sua própria em qualquer linguagem que ofereça primitivas de PBKDF2-HMAC-SHA256 e AES-256-GCM. Os dois usam estes códigos de saída:
| Código de saída | Significado |
|---|---|
0 | sucesso |
1 | erro de formato irrecuperável (magic number inválido, versão sem suporte, arquivo truncado) |
2 | a descriptografia falhou (senha / salt / iterações errados, ou arquivo corrompido) |
3 | erro de linha de comando / E/S |
O código, seus comentários e o texto que eles exibem permanecem em inglês, para que o que você lê aqui seja idêntico, byte a byte, aos arquivos do pacote de implantação.
Python 3 — decrypt-bsenc.py
Requer o pacote cryptography (pip install cryptography).
#!/usr/bin/env python3
# Reference decryption tool for the Lacuna Bulk Signer BSENC v1 envelope.
#
# Envelope layout (see the Encryption page for the authoritative reference):
#
# offset length field
# 0 8 magic = b"BSENC\0\0\0"
# 8 1 version = 0x01
# 9 12 nonce = per-file random (CSPRNG)
# 21 N ciphertext = AES-256-GCM(plaintext, key, nonce, aad=empty)
# 21 + N 16 auth tag = AES-256-GCM tag
#
# Requirements:
# pip install cryptography
#
# Usage:
# python decrypt-bsenc.py \
# --password "$BULK_SIGNER_ENCRYPTION_PASSWORD" \
# --salt-b64 "$BULK_SIGNER_ENCRYPTION_SALT" \
# --iterations 600000 \
# --in report.signed.pdf.enc \
# --out report.signed.pdf
#
# Exit codes:
# 0 success
# 1 unrecoverable format error (bad magic, unsupported version, truncated file)
# 2 decryption failed (wrong password / salt / iterations, or corrupted file)
# 3 CLI / I/O error
from __future__ import annotations
import argparse
import base64
import hashlib
import sys
from pathlib import Path
try:
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.exceptions import InvalidTag
except ImportError as e:
print(
f"error: the 'cryptography' package is required. Install with: pip install cryptography\n"
f"detail: {e}",
file=sys.stderr,
)
sys.exit(3)
BSENC_MAGIC = b"BSENC\x00\x00\x00"
BSENC_VERSION = 0x01
NONCE_LENGTH = 12
TAG_LENGTH = 16
HEADER_LENGTH = len(BSENC_MAGIC) + 1 + NONCE_LENGTH # = 21
FIXED_OVERHEAD = HEADER_LENGTH + TAG_LENGTH # = 37
def derive_key(password: str, salt: bytes, iterations: int) -> bytearray:
"""PBKDF2-HMAC-SHA256, 32-byte output.
Returns a mutable bytearray so callers can zeroize the key after use; CPython's
immutable ``bytes`` cannot be overwritten in place.
"""
return bytearray(hashlib.pbkdf2_hmac(
hash_name="sha256",
password=password.encode("utf-8"),
salt=salt,
iterations=iterations,
dklen=32,
))
def decrypt_envelope(envelope: bytes, key: "bytes | bytearray") -> bytes:
"""Parse a BSENC v1 envelope and return the plaintext signed bytes."""
if len(envelope) < FIXED_OVERHEAD:
raise ValueError(
f"envelope is too short ({len(envelope)} bytes); minimum {FIXED_OVERHEAD}"
)
if envelope[: len(BSENC_MAGIC)] != BSENC_MAGIC:
raise ValueError("unknown magic; not a BSENC envelope")
version = envelope[len(BSENC_MAGIC)]
if version != BSENC_VERSION:
raise ValueError(
f"unsupported envelope version 0x{version:02x}; this tool only reads v1"
)
nonce = envelope[HEADER_LENGTH - NONCE_LENGTH : HEADER_LENGTH]
body = envelope[HEADER_LENGTH:]
# AESGCM.decrypt expects ciphertext-with-tag concatenated, which is exactly what the
# envelope stores after the header — no manual split is needed.
aesgcm = AESGCM(key)
return aesgcm.decrypt(nonce, body, associated_data=None)
def main(argv: list[str]) -> int:
parser = argparse.ArgumentParser(
description="Decrypt a Lacuna Bulk Signer BSENC v1 envelope.",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
"--password",
required=True,
help="PBKDF2 password (matches Encryption:Password / BULK_SIGNER_ENCRYPTION_PASSWORD).",
)
parser.add_argument(
"--salt-b64",
required=True,
help="Base64-encoded PBKDF2 salt (matches Encryption:Salt).",
)
parser.add_argument(
"--iterations",
type=int,
default=600_000,
help="PBKDF2 iteration count (matches Encryption:Iterations). Default: 600000.",
)
parser.add_argument(
"--in",
dest="input_path",
required=True,
type=Path,
help="Path to the .enc envelope.",
)
parser.add_argument(
"--out",
dest="output_path",
required=True,
type=Path,
help="Path to write the decrypted (cleartext) signed artifact.",
)
args = parser.parse_args(argv)
try:
salt = base64.b64decode(args.salt_b64, validate=True)
except (ValueError, base64.binascii.Error) as e: # type: ignore[attr-defined]
print(f"error: --salt-b64 is not valid base64: {e}", file=sys.stderr)
return 3
if len(salt) < 16:
print(
f"error: salt decoded to {len(salt)} bytes; minimum 16 (NIST SP 800-132)",
file=sys.stderr,
)
return 3
if args.iterations < 10_000:
print(
f"error: --iterations {args.iterations} is implausibly low; "
"the server validator rejects anything below 10000",
file=sys.stderr,
)
return 3
try:
envelope = args.input_path.read_bytes()
except OSError as e:
print(f"error: could not read {args.input_path}: {e}", file=sys.stderr)
return 3
key = derive_key(args.password, salt, args.iterations)
try:
try:
plaintext = decrypt_envelope(envelope, key)
except ValueError as e:
print(f"error: {e}", file=sys.stderr)
return 1
except InvalidTag:
print(
"error: authentication-tag mismatch. The password, salt, iteration count, "
"or envelope itself is wrong.",
file=sys.stderr,
)
return 2
try:
args.output_path.write_bytes(plaintext)
except OSError as e:
print(f"error: could not write {args.output_path}: {e}", file=sys.stderr)
return 3
print(
f"decrypted {len(plaintext)} bytes -> {args.output_path}",
file=sys.stderr,
)
return 0
finally:
# Best-effort scrub of the derived 32-byte key.
key[:] = b"\x00" * len(key)
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
PowerShell 7+ — Decrypt-Bsenc.ps1
Usa somente a biblioteca padrão — o PowerShell 7+ é necessário para o
System.Security.Cryptography.AesGcm e para a sobrecarga estática Rfc2898DeriveBytes.Pbkdf2.
#requires -Version 7.0
<#
.SYNOPSIS
Reference decryption tool for the Lacuna Bulk Signer BSENC v1 envelope.
.DESCRIPTION
Envelope layout (see the Encryption page for the authoritative reference):
offset length field
0 8 magic = "BSENC\0\0\0"
8 1 version = 0x01
9 12 nonce = per-file random
21 N ciphertext = AES-256-GCM(plaintext, key, nonce, aad=empty)
21 + N 16 auth tag = AES-256-GCM tag
PowerShell 7+ is required for System.Security.Cryptography.AesGcm and
Rfc2898DeriveBytes.Pbkdf2 (the static one-shot, not the constructor form).
.PARAMETER Password
PBKDF2 password (matches Encryption:Password / BULK_SIGNER_ENCRYPTION_PASSWORD).
.PARAMETER SaltBase64
Base64-encoded PBKDF2 salt (matches Encryption:Salt). Must decode to >= 16 bytes.
.PARAMETER Iterations
PBKDF2 iteration count. Default 600000 (OWASP 2023 for HMAC-SHA256).
.PARAMETER InputPath
Path to the .enc envelope.
.PARAMETER OutputPath
Path to write the decrypted (cleartext) signed artifact.
.EXAMPLE
pwsh ./Decrypt-Bsenc.ps1 `
-Password $env:BULK_SIGNER_ENCRYPTION_PASSWORD `
-SaltBase64 $env:BULK_SIGNER_ENCRYPTION_SALT `
-Iterations 600000 `
-InputPath .\report.signed.pdf.enc `
-OutputPath .\report.signed.pdf
.NOTES
Exit codes:
0 success
1 unrecoverable format error (bad magic, unsupported version, truncated file)
2 decryption failed (wrong password / salt / iterations, or corrupted file)
3 CLI / I/O error
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string] $Password,
[Parameter(Mandatory = $true)]
[string] $SaltBase64,
[Parameter()]
[int] $Iterations = 600000,
[Parameter(Mandatory = $true)]
[string] $InputPath,
[Parameter(Mandatory = $true)]
[string] $OutputPath
)
$ErrorActionPreference = 'Stop'
# Envelope constants
$BsencMagic = [byte[]](0x42, 0x53, 0x45, 0x4E, 0x43, 0x00, 0x00, 0x00) # "BSENC\0\0\0"
$BsencVersion = [byte]0x01
$NonceLength = 12
$TagLength = 16
$HeaderLength = $BsencMagic.Length + 1 + $NonceLength # 21
$FixedOverhead = $HeaderLength + $TagLength # 37
function Write-ErrorMessage {
param([string] $Message)
[Console]::Error.WriteLine("error: $Message")
}
# --- Validate inputs --------------------------------------------------------------------------
try {
$salt = [Convert]::FromBase64String($SaltBase64)
} catch {
Write-ErrorMessage "--SaltBase64 is not valid base64: $($_.Exception.Message)"
exit 3
}
if ($salt.Length -lt 16) {
Write-ErrorMessage "salt decoded to $($salt.Length) bytes; minimum 16 (NIST SP 800-132)"
exit 3
}
if ($Iterations -lt 10000) {
Write-ErrorMessage "Iterations $Iterations is implausibly low; the server validator rejects anything below 10000"
exit 3
}
if (-not (Test-Path -LiteralPath $InputPath -PathType Leaf)) {
Write-ErrorMessage "input file not found: $InputPath"
exit 3
}
# --- Read and validate the envelope -----------------------------------------------------------
try {
$envelope = [System.IO.File]::ReadAllBytes($InputPath)
} catch {
Write-ErrorMessage "could not read ${InputPath}: $($_.Exception.Message)"
exit 3
}
if ($envelope.Length -lt $FixedOverhead) {
Write-ErrorMessage "envelope is too short ($($envelope.Length) bytes); minimum $FixedOverhead"
exit 1
}
for ($i = 0; $i -lt $BsencMagic.Length; $i++) {
if ($envelope[$i] -ne $BsencMagic[$i]) {
Write-ErrorMessage "unknown magic; not a BSENC envelope"
exit 1
}
}
if ($envelope[$BsencMagic.Length] -ne $BsencVersion) {
$found = "0x{0:x2}" -f $envelope[$BsencMagic.Length]
Write-ErrorMessage "unsupported envelope version $found; this tool only reads v1"
exit 1
}
# Slice fields out of the envelope.
$nonce = New-Object byte[] $NonceLength
[Array]::Copy($envelope, $HeaderLength - $NonceLength, $nonce, 0, $NonceLength)
$ciphertextLength = $envelope.Length - $HeaderLength - $TagLength
$ciphertext = New-Object byte[] $ciphertextLength
[Array]::Copy($envelope, $HeaderLength, $ciphertext, 0, $ciphertextLength)
$tag = New-Object byte[] $TagLength
[Array]::Copy($envelope, $envelope.Length - $TagLength, $tag, 0, $TagLength)
# --- Derive the key and decrypt ---------------------------------------------------------------
try {
$passwordBytes = [System.Text.Encoding]::UTF8.GetBytes($Password)
$key = [System.Security.Cryptography.Rfc2898DeriveBytes]::Pbkdf2(
$passwordBytes,
$salt,
$Iterations,
[System.Security.Cryptography.HashAlgorithmName]::SHA256,
32
)
} catch {
Write-ErrorMessage "key derivation failed: $($_.Exception.Message)"
exit 3
}
$plaintext = New-Object byte[] $ciphertextLength
$aesGcm = $null
try {
$aesGcm = [System.Security.Cryptography.AesGcm]::new($key, $TagLength)
$aesGcm.Decrypt($nonce, $ciphertext, $tag, $plaintext)
} catch [System.Security.Cryptography.AuthenticationTagMismatchException] {
Write-ErrorMessage "authentication-tag mismatch. The password, salt, iteration count, or envelope itself is wrong."
exit 2
} catch [System.Security.Cryptography.CryptographicException] {
Write-ErrorMessage "cryptographic error during decryption: $($_.Exception.Message)"
exit 2
} catch {
Write-ErrorMessage "unexpected error during decryption: $($_.Exception.Message)"
exit 3
} finally {
if ($null -ne $aesGcm) { $aesGcm.Dispose() }
# Best-effort scrub of secret-bearing buffers from managed memory.
if ($null -ne $key) { [Array]::Clear($key, 0, $key.Length) }
if ($null -ne $passwordBytes) { [Array]::Clear($passwordBytes, 0, $passwordBytes.Length) }
}
# --- Write the plaintext ----------------------------------------------------------------------
try {
[System.IO.File]::WriteAllBytes($OutputPath, $plaintext)
} catch {
Write-ErrorMessage "could not write ${OutputPath}: $($_.Exception.Message)"
exit 3
} finally {
if ($null -ne $plaintext) { [Array]::Clear($plaintext, 0, $plaintext.Length) }
}
[Console]::Error.WriteLine("decrypted $($plaintext.Length) bytes -> $OutputPath")
exit 0
PowerShell 7+ — Import-PfxToKeyVault.ps1
Provisiona um PFX existente para uso com a origem de certificado AzureKeyVault (veja
Certificados). Em uma única execução, ele importa a chave
privada para o cofre como uma chave não exportável, grava o certificado público como um .cer,
registra um aplicativo no Microsoft Entra ID, concede a ele permissão para assinar com essa chave,
verifica o par e exibe um bloco de configuração pronto para colar.
Requer o PowerShell 7+ e os módulos Az.Accounts, Az.KeyVault e Az.Resources. Autentique-se antes
com Connect-AzAccount. Aceita -WhatIf — execute-o assim uma vez para ver o que ele faria.
O script não cria o cofre; aponte-o para um que já exista.
O Key Vault pode armazenar um PFX das duas formas, e apenas uma delas é realmente não exportável. Quando
o PFX é importado como key, o material privado nunca pode ser recuperado — a assinatura acontece
dentro do cofre. Quando é importado como certificate, ele é marcado como exportável, e o PFX inteiro
pode ser baixado do segredo associado a ele, então qualquer pessoa com secrets/get pode levar a chave
embora. Este script importa uma chave, e é por isso que o Bulk Signer precisa que o certificado público
seja fornecido separadamente, como um .cer local.
O PFX continua no disco depois que o script é executado. Depois de confirmar que a assinatura funciona,
mova-o para um backup offline e remova-o do host — deixá-lo lá anula o propósito de colocar a chave em um
cofre. Não destrua sua única cópia: o Key Vault não devolve a chave, então o PFX (ou um blob de
Backup-AzKeyVaultKey) é o seu único artefato de recuperação de desastres.
O operador que executa o script precisa de: Key Vault Crypto Officer no cofre (para importar uma chave), Application Developer ou superior no Entra ID (para registrar um aplicativo) e User Access Administrator ou Owner no cofre (para criar a atribuição de role — desnecessário em um cofre com políticas de acesso).
#requires -Version 7.0
#requires -Modules Az.Accounts, Az.KeyVault, Az.Resources
<#
.SYNOPSIS
Provisions a PFX for use with Bulk Signer's `Source = AzureKeyVault` certificate source:
imports the private key into Azure Key Vault as a non-exportable key, writes the public
certificate out as a .cer, registers a Microsoft Entra ID application, and grants that
application permission to sign with the key.
.DESCRIPTION
Produces everything the AzureKeyVault certificate source needs (see the Certificates page),
in one pass:
1. Reads the PFX locally and verifies it carries a private key.
2. Writes the public certificate to a .cer file — this is `CerPath`.
3. Imports the private key into the vault as a KEY object — this is `KeyName`.
4. Confirms the imported key's public half matches the .cer, the same check the service
performs at boot, so a mismatch is caught here rather than at startup.
5. Registers an Entra ID application + service principal — this is `AppId`.
6. Creates a client secret on it — this is `AppSecret`.
7. Grants the service principal permission to read and sign with that key.
8. Prints a ready-to-paste configuration block.
WHY A KEY OBJECT AND NOT A CERTIFICATE OBJECT
Key Vault can hold this PFX either way, and only one of them is actually non-exportable:
* As a KEY (what this script does). Key Vault never returns private key material for a key
object under any permission. Signing happens inside the vault.
* As a CERTIFICATE. A certificate imported from a PFX is marked exportable, and its private
key can then be downloaded in full from the secret that backs it
(`Get-AzKeyVaultSecret -Name <certName>` returns a complete PFX). Anyone holding the
secrets/get permission can walk away with the key.
Bulk Signer's AzureKeyVault source is deliberately key-only for exactly this reason, which is
also why the public certificate has to be supplied separately as a local .cer.
PERMISSIONS THE OPERATOR RUNNING THIS NEEDS
* On the vault: import a key — "Key Vault Crypto Officer" (RBAC), or a "create/import" key
access policy on a legacy access-policy vault.
* In Entra ID: register applications — "Application Developer" or higher.
* On the vault or its resource group: create role assignments — "User Access Administrator"
or "Owner". Not needed on an access-policy vault.
.PARAMETER PfxPath
Path to the .pfx / .p12 holding the signing certificate and its private key.
.PARAMETER PfxPassword
Password protecting the PFX. Prompted for securely when omitted. Pass
`(ConvertTo-SecureString -String '' -AsPlainText -Force)` for a passwordless PFX.
.PARAMETER VaultName
Name of an existing Azure Key Vault. The script does not create the vault.
.PARAMETER KeyName
Name to give the imported key inside the vault. Becomes `KeyName` in configuration.
.PARAMETER AppDisplayName
Display name for the Entra ID application to register.
.PARAMETER CerPath
Where to write the public certificate. Defaults to the PFX path with a .cer extension.
Becomes `CerPath` in configuration — place it where the service can read it.
.PARAMETER SecretValidityYears
Lifetime of the generated client secret, in years. Default 1. An expired secret fails the
service at boot with an Azure authentication error, so pair rotation with a restart.
.PARAMETER GrantScope
`Key` (default) scopes the role assignment to this one key — the tightest grant, and what you
want when a vault holds keys for more than one consumer. `Vault` scopes it to the whole vault,
which is Microsoft's recommendation for manageability when the vault serves a single
application. Ignored on access-policy vaults, which can only grant at vault level.
.PARAMETER Destination
`Software` (default) or `HSM` for the imported key. `HSM` requires a Premium vault.
.PARAMETER ExistingAppId
Reuse an existing application instead of registering a new one. A fresh client secret is still
created. Use when several vault keys should share one identity.
.EXAMPLE
pwsh ./Import-PfxToKeyVault.ps1 `
-PfxPath ./signer.pfx `
-VaultName my-vault `
-KeyName bulk-signer-signing-key `
-AppDisplayName bulk-signer-prod
.EXAMPLE
# Least-privilege variant on a vault shared with other consumers, HSM-backed, 2-year secret.
pwsh ./Import-PfxToKeyVault.ps1 `
-PfxPath ./signer.pfx -VaultName shared-vault -KeyName bulksigner-key `
-AppDisplayName bulk-signer-prod -GrantScope Key -Destination HSM -SecretValidityYears 2
.NOTES
The client secret is printed once and never written to disk. Capture it before closing the
session; if it is lost, create a replacement with `New-AzADAppCredential`.
The PFX still exists on disk after this runs. Once you have verified signing works, move it to
offline backup and remove it from the host — leaving it in place defeats the point of putting
the key in a vault. Do not destroy your only copy: Key Vault will not give the key back, so the
PFX is your disaster-recovery artifact (as is `Backup-AzKeyVaultKey`).
Exit codes:
0 success
1 precondition failed (bad PFX, missing vault, not signed in)
2 Azure operation failed (import, app registration, or role assignment)
#>
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory)]
[ValidateScript({ Test-Path -LiteralPath $_ -PathType Leaf })]
[string]$PfxPath,
[Parameter()]
[System.Security.SecureString]$PfxPassword,
[Parameter(Mandatory)]
[string]$VaultName,
[Parameter(Mandatory)]
[string]$KeyName,
[Parameter(Mandatory, ParameterSetName = 'NewApp')]
[string]$AppDisplayName,
[Parameter(Mandatory, ParameterSetName = 'ExistingApp')]
[string]$ExistingAppId,
[Parameter()]
[string]$CerPath,
[Parameter()]
[ValidateRange(1, 2)]
[int]$SecretValidityYears = 1,
[Parameter()]
[ValidateSet('Key', 'Vault')]
[string]$GrantScope = 'Key',
[Parameter()]
[ValidateSet('Software', 'HSM')]
[string]$Destination = 'Software'
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$script:CryptoUserRole = 'Key Vault Crypto User'
function Write-Step { param([string]$Message) Write-Host "==> $Message" -ForegroundColor Cyan }
function Write-Ok { param([string]$Message) Write-Host " $Message" -ForegroundColor Green }
function Write-Note { param([string]$Message) Write-Host " $Message" -ForegroundColor DarkGray }
function Stop-WithError {
param([string]$Message, [int]$Code = 1)
Write-Host "ERROR: $Message" -ForegroundColor Red
exit $Code
}
# ---------------------------------------------------------------------------------------------
# 1. Preconditions
# ---------------------------------------------------------------------------------------------
Write-Step 'Checking prerequisites'
$context = Get-AzContext
if (-not $context) {
Stop-WithError 'Not signed in to Azure. Run Connect-AzAccount (and Set-AzContext to pick the subscription holding the vault).'
}
Write-Ok "Subscription: $($context.Subscription.Name) ($($context.Subscription.Id))"
Write-Ok "Tenant: $($context.Tenant.Id)"
$vault = Get-AzKeyVault -VaultName $VaultName -ErrorAction SilentlyContinue
if (-not $vault) {
Stop-WithError "Key vault '$VaultName' not found in subscription $($context.Subscription.Id). Create it first, or Set-AzContext to the right subscription."
}
# EnableRbacAuthorization decides how step 6 grants access; the two models are mutually exclusive.
$usesRbac = [bool]$vault.EnableRbacAuthorization
Write-Ok "Vault: $($vault.VaultName) (permission model: $(if ($usesRbac) { 'Azure RBAC' } else { 'access policy' }))"
if (-not $PfxPassword) {
$PfxPassword = Read-Host -AsSecureString "Password for '$([System.IO.Path]::GetFileName($PfxPath))' (empty if none)"
}
if (-not $CerPath) {
$CerPath = [System.IO.Path]::ChangeExtension((Resolve-Path -LiteralPath $PfxPath).Path, '.cer')
}
# ---------------------------------------------------------------------------------------------
# 2. Read the PFX locally, before touching Azure
# ---------------------------------------------------------------------------------------------
Write-Step 'Reading the PFX'
$pfxFullPath = (Resolve-Path -LiteralPath $PfxPath).Path
$certificate = $null
try {
$pfxBytes = [System.IO.File]::ReadAllBytes($pfxFullPath)
# EphemeralKeySet keeps the private key out of the OS key store while we inspect it. Some
# PFX/platform combinations reject it, so fall back to default handling.
try {
$certificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new(
$pfxBytes, $PfxPassword, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::EphemeralKeySet)
}
catch {
$certificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($pfxBytes, $PfxPassword)
}
}
catch {
Stop-WithError "Could not open '$pfxFullPath'. Wrong password, or the file is not a PKCS#12 archive. ($($_.Exception.Message))"
}
if (-not $certificate.HasPrivateKey) {
Stop-WithError "'$pfxFullPath' contains no private key. Re-export the PFX including the private key."
}
$thumbprint = $certificate.Thumbprint
Write-Ok "Subject: $($certificate.Subject)"
Write-Ok "Thumbprint: $thumbprint"
Write-Ok "Valid: $($certificate.NotBefore.ToString('yyyy-MM-dd')) .. $($certificate.NotAfter.ToString('yyyy-MM-dd'))"
if ($certificate.NotAfter -lt (Get-Date)) {
Write-Warning "This certificate expired on $($certificate.NotAfter.ToString('yyyy-MM-dd')). Signatures produced with it will not validate."
}
$certRsa = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPublicKey($certificate)
if (-not $certRsa) {
Write-Warning 'Certificate does not carry an RSA public key. The automatic key-match check in step 5 will be skipped; verify manually per the Certificates page.'
}
# ---------------------------------------------------------------------------------------------
# 3. Write the public certificate (CerPath)
# ---------------------------------------------------------------------------------------------
Write-Step "Writing the public certificate to $CerPath"
if ($PSCmdlet.ShouldProcess($CerPath, 'Write DER-encoded public certificate')) {
$derBytes = $certificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert)
[System.IO.File]::WriteAllBytes($CerPath, $derBytes)
Write-Ok "$($derBytes.Length) bytes (DER). Public material only — no private key."
}
# ---------------------------------------------------------------------------------------------
# 4. Import the private key as a non-exportable vault KEY
# ---------------------------------------------------------------------------------------------
Write-Step "Importing the private key into '$VaultName' as key '$KeyName'"
$existingKey = Get-AzKeyVaultKey -VaultName $VaultName -Name $KeyName -ErrorAction SilentlyContinue
if ($existingKey) {
Write-Warning "Key '$KeyName' already exists in '$VaultName'. Importing creates a NEW VERSION; the current version is retained and reachable by its version-specific id."
}
$vaultKey = $null
if ($PSCmdlet.ShouldProcess("$VaultName/keys/$KeyName", 'Import key from PFX')) {
try {
# KeyOps is restricted to sign/verify so the key cannot be used to encrypt, decrypt, wrap,
# or unwrap even by a caller who holds a broader role than intended. Bulk Signer only ever
# signs; the public-key side of verification happens locally from the .cer.
$vaultKey = Add-AzKeyVaultKey `
-VaultName $VaultName `
-Name $KeyName `
-KeyFilePath $pfxFullPath `
-KeyFilePassword $PfxPassword `
-Destination $Destination `
-KeyOps 'sign', 'verify'
}
catch {
Stop-WithError "Key import failed: $($_.Exception.Message)`nThe signed-in identity needs 'Key Vault Crypto Officer' (RBAC) or key create/import permission (access policy) on '$VaultName'." 2
}
Write-Ok "Key id: $($vaultKey.Id)"
Write-Ok "Key ops: $($vaultKey.Key.KeyOps -join ', ')"
Write-Ok 'Exportable: no — Key Vault never returns private key material for a key object.'
}
# ---------------------------------------------------------------------------------------------
# 5. Confirm the imported key matches the certificate (mirrors the service's boot check)
# ---------------------------------------------------------------------------------------------
if ($vaultKey -and $certRsa) {
Write-Step 'Verifying the vault key matches the certificate'
$certModulus = $certRsa.ExportParameters($false).Modulus
# JWK 'n' and RSAParameters.Modulus are both unsigned big-endian with no leading zero padding,
# so a direct byte comparison is valid.
$vaultModulus = $vaultKey.Key.N
$matches = $vaultModulus -and $certModulus.Length -eq $vaultModulus.Length
if ($matches) {
for ($i = 0; $i -lt $certModulus.Length; $i++) {
if ($certModulus[$i] -ne $vaultModulus[$i]) { $matches = $false; break }
}
}
if (-not $matches) {
Stop-WithError "The imported key's public half does not match '$CerPath'. This should not happen when both come from the same PFX — inspect key '$KeyName' in '$VaultName' before configuring the service." 2
}
Write-Ok 'Public keys match. The service will accept this CerPath + KeyName pair at boot.'
}
# ---------------------------------------------------------------------------------------------
# 6. Register the application and create a client secret
# ---------------------------------------------------------------------------------------------
$appId = $null
$servicePrincipalObjectId = $null
$clientSecret = $null
if ($PSCmdlet.ParameterSetName -eq 'ExistingApp') {
Write-Step "Reusing existing application $ExistingAppId"
$app = Get-AzADApplication -ApplicationId $ExistingAppId -ErrorAction SilentlyContinue
if (-not $app) { Stop-WithError "No application with appId '$ExistingAppId' in tenant $($context.Tenant.Id)." }
$appId = $app.AppId
$sp = Get-AzADServicePrincipal -ApplicationId $appId -ErrorAction SilentlyContinue
if (-not $sp) {
Write-Note 'Application has no service principal in this tenant; creating one.'
$sp = New-AzADServicePrincipal -ApplicationId $appId
}
$servicePrincipalObjectId = $sp.Id
Write-Ok "Display name: $($app.DisplayName)"
}
else {
Write-Step "Registering Entra ID application '$AppDisplayName'"
if ($PSCmdlet.ShouldProcess($AppDisplayName, 'Register Entra ID application and service principal')) {
try {
$app = New-AzADApplication -DisplayName $AppDisplayName
$appId = $app.AppId
Write-Ok "Application (client) id: $appId"
# The service principal is the security object role assignments target; the application
# alone cannot hold one.
$sp = New-AzADServicePrincipal -ApplicationId $appId
$servicePrincipalObjectId = $sp.Id
Write-Ok "Service principal object id: $servicePrincipalObjectId"
}
catch {
Stop-WithError "Application registration failed: $($_.Exception.Message)`nThe signed-in identity needs the 'Application Developer' Entra role (or higher)." 2
}
}
}
if ($appId -and $PSCmdlet.ShouldProcess("application $appId", 'Create client secret')) {
Write-Step 'Creating a client secret'
try {
$startDate = Get-Date
$credential = New-AzADAppCredential `
-ApplicationId $appId `
-StartDate $startDate `
-EndDate $startDate.AddYears($SecretValidityYears)
$clientSecret = $credential.SecretText
Write-Ok "Expires: $($startDate.AddYears($SecretValidityYears).ToString('yyyy-MM-dd'))"
}
catch {
Stop-WithError "Client secret creation failed: $($_.Exception.Message)" 2
}
}
# ---------------------------------------------------------------------------------------------
# 7. Grant sign permission on the key
# ---------------------------------------------------------------------------------------------
if ($servicePrincipalObjectId) {
Write-Step 'Granting permission to sign with the key'
if ($usesRbac) {
$scope = if ($GrantScope -eq 'Key') { "$($vault.ResourceId)/keys/$KeyName" } else { $vault.ResourceId }
Write-Note "Role '$script:CryptoUserRole' at scope: $scope"
Write-Note "'$script:CryptoUserRole' is the narrowest built-in role granting keys/sign; restricting the key to sign+verify in step 4 is what actually bounds it to signing."
if ($PSCmdlet.ShouldProcess($scope, "Assign '$script:CryptoUserRole'")) {
# A freshly created service principal is not immediately visible to the role-assignment
# API ("Principal {id} does not exist in the directory"). Retry rather than fail.
$assigned = $false
foreach ($attempt in 1..12) {
try {
New-AzRoleAssignment -ObjectId $servicePrincipalObjectId `
-RoleDefinitionName $script:CryptoUserRole -Scope $scope -ErrorAction Stop | Out-Null
$assigned = $true
break
}
catch {
if ($_.Exception.Message -match 'already exists') { $assigned = $true; break }
if ($attempt -eq 12) { Stop-WithError "Role assignment failed after $attempt attempts: $($_.Exception.Message)`nThe signed-in identity needs 'User Access Administrator' or 'Owner' on the vault." 2 }
Write-Note "Directory replication pending (attempt $attempt/12); retrying in 5s."
Start-Sleep -Seconds 5
}
}
if ($assigned) { Write-Ok 'Role assigned.' }
}
}
else {
Write-Note 'Access-policy vault: granting key get + sign. This model cannot scope to an individual key.'
if ($PSCmdlet.ShouldProcess($VaultName, 'Set key access policy (get, sign)')) {
try {
Set-AzKeyVaultAccessPolicy -VaultName $VaultName `
-ObjectId $servicePrincipalObjectId -PermissionsToKeys get, sign
Write-Ok 'Access policy set.'
}
catch {
Stop-WithError "Setting the access policy failed: $($_.Exception.Message)" 2
}
}
}
}
# ---------------------------------------------------------------------------------------------
# 8. Report
# ---------------------------------------------------------------------------------------------
if (-not $WhatIfPreference) {
$vaultUri = $vault.VaultUri
if (-not $vaultUri.EndsWith('/')) { $vaultUri += '/' }
Write-Host ''
Write-Host '─────────────────────────────────────────────────────────────────────────' -ForegroundColor Cyan
Write-Host ' Bulk Signer configuration' -ForegroundColor Cyan
Write-Host '─────────────────────────────────────────────────────────────────────────' -ForegroundColor Cyan
Write-Host @"
"Signing": {
"Certificate": {
"Source": "AzureKeyVault",
"AzureKeyVault": {
"Endpoint": "$vaultUri",
"AppId": "$appId",
"AppSecret": "",
"KeyName": "$KeyName",
"CerPath": "$CerPath"
}
}
}
Supply the secret via environment variable rather than the config file:
Signing__Certificate__AzureKeyVault__AppSecret
"@
Write-Host '─────────────────────────────────────────────────────────────────────────' -ForegroundColor Yellow
Write-Host ' Client secret — shown once, not stored anywhere' -ForegroundColor Yellow
Write-Host '─────────────────────────────────────────────────────────────────────────' -ForegroundColor Yellow
Write-Host ''
Write-Host " $clientSecret"
Write-Host ''
Write-Host 'Next steps:' -ForegroundColor Cyan
Write-Host " 1. Copy the secret above into your secret store or the environment variable now."
Write-Host " 2. Place $CerPath where the service account can read it."
Write-Host " 3. Start the service. It verifies the certificate/key pair at boot and fails loudly on mismatch."
Write-Host " 4. Once signing is confirmed, move $pfxFullPath to offline backup and remove it from this host."
Write-Host " Keep that backup: Key Vault will not return the key, so the PFX is your only recovery path."
Write-Host ''
if ($usesRbac) {
Write-Host 'Role assignments can take a minute or two to propagate; an immediate first sign attempt may fail with Forbidden.' -ForegroundColor DarkGray
}
}
exit 0
PowerShell 7+ — New-BulkSignerEntraApp.ps1
Vem no pacote de implantação, junto com os dois acima. Ele automatiza os passos 1, 2 e 4 do passo a passo do Microsoft Entra ID por meio do Microsoft Graph, cria o client secret e exibe um bloco de configuração pronto para colar. O passo 3 — atribuir pessoas às roles — continua manual, no centro de administração do Entra, em Enterprise applications → Users and groups.
Pré-requisitos:
Install-Module Microsoft.Graph.Applications -Scope CurrentUser
além de uma conta capaz de dar consentimento ao escopo delegado Application.ReadWrite.All — Cloud
Application Administrator é a role de menor privilégio que consegue fazer isso; Application
Administrator e Global Administrator também conseguem.
pwsh ./New-BulkSignerEntraApp.ps1 -BaseUrl https://signer.example.com
| Parâmetro | Obrigatório | Padrão | Observações |
|---|---|---|---|
-BaseUrl | sim | — | A origem pública a partir da qual o dashboard é servido. A URI de redirecionamento é derivada dela como <BaseUrl>/signin-oidc. Precisa ser uma origem http(s) absoluta. |
-DisplayName | não | Lacuna Bulk Signer | Nome de exibição do registro de aplicativo. |
-SecretValidityMonths | não | 12 | Validade do client secret, de 1 a 24 meses. |
O que ele cria:
- Um aplicativo de tenant único, com as permissões delegadas
openid/profile/emailque o handler OIDC solicita. A claimemailtambém é declarada como claim opcional do ID token, porque a correspondência com o pool de aprovadores é feita por ela e não há alternativa por UPN. - As duas app roles, com os valores exatos que o host usa na correspondência —
AdministratoreApprover. - O aplicativo empresarial (enterprise application) com Assignment required = Yes, para que contas não atribuídas sejam barradas já no login da Microsoft. O host exige a presença da role de qualquer forma.
Ele se recusa a criar uma duplicata: um segundo registro com o mesmo nome de exibição quase sempre é
uma reexecução, e dois aplicativos com as mesmas roles são uma armadilha de gestão, e não redundância.
Informe um -DisplayName diferente ou exclua antes o registro existente.
Armazene-o como a variável de ambiente Auth__EntraId__ClientSecret (recomendado) ou em um
appsettings.Production.json não versionado — nunca no controle de versão. Veja
Segurança para saber onde cada alvo de implantação deve armazená-lo.
Um segredo expirado provoca falha no login, com um erro AADSTS, e não no boot. Faça a rotação antes
que ele expire.
PowerShell 7+ — Import-PfxToKms.ps1
Prepara um PFX existente para a origem de certificado AwsKms — o equivalente na AWS do
Import-PfxToKeyVault.ps1, e o script que o passo 2 do Amazon ECS Fargate
executa. Em uma passada, ele cria no AWS KMS uma chave RSA de assinatura com material de chave
importado, encapsula localmente a chave privada do PFX com RSA_AES_KEY_WRAP_SHA_256 (o único algoritmo
de encapsulamento que o KMS aceita para chaves privadas RSA), importa-a, grava o certificado público em um
.cer, opcionalmente faz upload dele para o S3, compara a chave pública do KMS com o certificado
exatamente como o Bulk Signer faz no boot e mostra as configurações do perfil e a política do IAM de que o
role do serviço precisa.
Requer PowerShell 7+, o AWS CLI v2 autenticado e OpenSSL 3.x — o Git for Windows traz um; passe
-OpenSslPath quando ele não estiver no PATH. A própria origem AwsKms requer o Bulk Signer 2.20.0 ou
posterior. O script pede a senha do PFX por conta própria, então ela nunca aparece em uma linha de comando.
Aceita -WhatIf, que lê o PFX e grava o .cer, mas para antes de criar qualquer coisa na AWS.
pwsh ./Import-PfxToKms.ps1 -PfxPath ./signer.pfx -Region sa-east-1 -Alias bulksigner \
-S3Bucket <bucket> -SignerPrincipalArn arn:aws:iam::<conta>:role/bulksigner-task
| Parâmetro | Obrigatório | Padrão | Observações |
|---|---|---|---|
-PfxPath | sim | — | O .pfx / .p12 com o certificado e a chave privada. RSA 2048, 3072 ou 4096. |
-Region | sim | — | Onde a chave é criada. Nunca vem do padrão do CLI, para que a chave fique onde a configuração vai dizer que ela está. |
-Alias | sim | — | O alias a criar, com ou sem alias/. Vira KeyId na configuração. O script para se o alias já existir, em vez de redirecioná-lo. |
-PfxPassword | não | perguntada | Uma SecureString. Se omitida, o script pergunta. |
-CerPath | não | o caminho do PFX com .cer | Onde gravar o certificado público. |
-S3Bucket, -S3Key | não | — / signing-material/<alias>.cer | Faz upload do .cer para um host sem disco durável. |
-SignerPrincipalArn | não | — | Os únicos usuários ou roles do IAM autorizados a chamar kms:Sign com a chave — normalmente o task role do serviço. Um role pode ser citado antes de existir. |
-OpenSslPath | não | openssl no PATH, depois a cópia do Git for Windows | Um executável do OpenSSL 3.x. |
Com -SignerPrincipalArn, a chave é criada com a política padrão do KMS mais uma negação explícita de
kms:Sign para qualquer entidade de segurança (principal) não citada. Um administrador da conta continua
podendo gerenciar a chave — então isso não tranca a conta fora dela —, mas não consegue assinar com ela sem
antes alterar a política da chave, o que o CloudTrail registra. Sem o parâmetro, qualquer principal cuja
política do IAM permita kms:Sign consegue assinar.
A identidade que executa o script precisa de kms:CreateKey, kms:CreateAlias, kms:ListAliases,
kms:GetParametersForImport, kms:ImportKeyMaterial, kms:GetPublicKey e kms:DescribeKey, mais
s3:PutObject no objeto quando -S3Bucket é informado.
A chave privada é gravada uma vez, em PKCS#8, em uma pasta nova dentro do seu diretório temporário, lida pelo OpenSSL para o encapsulamento, depois sobrescrita com zeros e apagada — inclusive quando um passo falha. Se a importação falhar depois de a chave ter sido criada, o script mostra a chave (deixada em Pending import) e os dois comandos que a removem.
O KMS nunca devolve a chave privada, então o PFX é a única forma de importar a chave de novo — em uma chave nova, em outra região ou em outra conta. Mantenha exatamente uma cópia em backup offline e exclua as demais: a chave no KMS é tão segura quanto cada cópia do PFX.
#requires -Version 7.0
<#
.SYNOPSIS
Provisions a PFX for use with Bulk Signer's `Source = AwsKms` certificate source: imports the
private key into AWS KMS as a non-exportable SIGN_VERIFY key, writes the public certificate out
as a .cer, and optionally uploads that .cer to S3.
.DESCRIPTION
The AWS counterpart of Import-PfxToKeyVault.ps1. Produces everything the AwsKms certificate
source needs (see docs/certificates.md#source--awskms and ADR-0041), in one pass:
1. Reads the PFX locally and checks it carries an RSA 2048/3072/4096 private key.
2. Writes the public certificate to a .cer file — this is `CerPath` (or the S3 object).
3. Creates a KMS key with Origin=EXTERNAL, SIGN_VERIFY, and the PFX's RSA size, and an alias
— this is `KeyId`.
4. Downloads a wrapping key and import token, wraps the private key locally with
RSA_AES_KEY_WRAP_SHA_256 (the only wrapping algorithm KMS accepts for RSA private keys),
and imports it with KEY_MATERIAL_DOES_NOT_EXPIRE.
5. Confirms the key's public half (GetPublicKey) matches the .cer — the same check the
service performs at boot, so a mismatch is caught here rather than at startup.
6. Optionally uploads the .cer to s3://<S3Bucket>/<S3Key>.
7. Prints the configuration block and the IAM policy the service's role needs.
WHAT THIS DOES AND DOES NOT PROTECT
After the import, KMS never returns the private key to anybody, and every signature is a
CloudTrail event. But the key existed outside an HSM before this ran, so the KMS key is only as
safe as every copy of the PFX. Keep one copy in offline backup (KMS will not give the key back,
and deleting imported key material is recoverable only by re-importing it) and remove the rest.
WHERE THE PLAINTEXT KEY GOES
The PKCS#8 private key is written once to a fresh directory under the user's temp folder, read
by OpenSSL for the AES key wrap, then overwritten with zeros and deleted in a `finally` block —
including when a step fails. The 256-bit AES wrapping key is passed to OpenSSL on its command
line as AWS's own instructions do; it is single-use and protects nothing once the import is done.
PREREQUISITES
* PowerShell 7+, the AWS CLI v2 signed in (`aws login`, `aws configure sso` or an access key),
and OpenSSL 3.x (Git for Windows ships one; pass -OpenSslPath if it is not on PATH).
* IAM permissions for whoever runs this: kms:CreateKey, kms:CreateAlias, kms:ListAliases (to
refuse an alias that already exists), kms:GetParametersForImport, kms:ImportKeyMaterial,
kms:GetPublicKey, kms:DescribeKey, and s3:PutObject on the target object when -S3Bucket is
given.
.PARAMETER PfxPath
Path to the .pfx / .p12 holding the signing certificate and its private key.
.PARAMETER PfxPassword
Password protecting the PFX. Prompted for securely when omitted.
.PARAMETER Region
The AWS region for the key, e.g. sa-east-1. Never taken from the CLI's default, so the key
lands where the configuration will say it is.
.PARAMETER Alias
The alias to create, with or without the `alias/` prefix. Becomes `KeyId` in configuration.
The script stops if the alias already exists rather than re-pointing it.
.PARAMETER CerPath
Where to write the public certificate. Defaults to the PFX path with a .cer extension.
.PARAMETER S3Bucket
Optional. Upload the .cer to this bucket, for a host with no durable disk (ECS/Fargate).
.PARAMETER S3Key
Object key for the upload. Defaults to `signing-material/<alias name>.cer`.
.PARAMETER OpenSslPath
Path to an OpenSSL 3.x executable. Defaults to `openssl` on PATH, then Git for Windows' copy.
.PARAMETER SignerPrincipalArn
Optional. The only IAM principals allowed to call kms:Sign with this key — typically the
service's role (an ECS task role or an EC2 instance role) and, for testing, your own user.
When given, the key is created with its default policy plus an explicit Deny of kms:Sign for
every other principal, so an account administrator cannot sign with it without first changing
the key policy (which CloudTrail records). Administration of the key is unaffected, so this
cannot lock the account out of it. A role may be named before it exists. Omitted, the key gets
KMS's default policy and any principal whose IAM policy allows kms:Sign can sign.
.EXAMPLE
pwsh ./Import-PfxToKms.ps1 -PfxPath ./signer.pfx -Region sa-east-1 -Alias bulksigner-hml `
-S3Bucket bulksigner-hml-111122223333 `
-SignerPrincipalArn arn:aws:iam::111122223333:role/bulksigner-hml-task
.NOTES
Exit codes:
0 success
1 precondition failed (bad PFX, unsupported key, CLI or OpenSSL missing, alias taken)
2 AWS or OpenSSL operation failed (the KMS key, if created, is left Pending import — see
the message for how to retry or schedule its deletion)
#>
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory)]
[ValidateScript({ Test-Path -LiteralPath $_ -PathType Leaf })]
[string]$PfxPath,
[Parameter()]
[System.Security.SecureString]$PfxPassword,
[Parameter(Mandatory)]
[string]$Region,
[Parameter(Mandatory)]
[string]$Alias,
[Parameter()]
[string]$CerPath,
[Parameter()]
[string]$S3Bucket,
[Parameter()]
[string]$S3Key,
[Parameter()]
[string]$OpenSslPath,
[Parameter()]
[ValidatePattern('^arn:aws[a-z-]*:iam::\d{12}:(user|role)/.+')]
[string[]]$SignerPrincipalArn
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
function Write-Step { param([string]$Message) Write-Host "==> $Message" -ForegroundColor Cyan }
function Write-Ok { param([string]$Message) Write-Host " $Message" -ForegroundColor Green }
function Write-Note { param([string]$Message) Write-Host " $Message" -ForegroundColor DarkGray }
function Stop-WithError {
param([string]$Message, [int]$Code = 1)
Write-Host "ERROR: $Message" -ForegroundColor Red
exit $Code
}
# Runs the AWS CLI, returning parsed JSON (or nothing for commands without output). A non-zero exit
# becomes a terminating error carrying the CLI's own message.
# A simple function (no param block) on purpose: `--key-id` and friends land in $args verbatim.
function Invoke-Aws {
$output = & aws @args --region $Region --output json 2>&1
if ($LASTEXITCODE -ne 0) { throw "aws $($args[0]) $($args[1]) failed: $($output -join ' ')" }
$text = ($output | Where-Object { $_ -is [string] }) -join "`n"
if ($text.Trim()) { return $text | ConvertFrom-Json }
}
$aliasName = if ($Alias.StartsWith('alias/')) { $Alias } else { "alias/$Alias" }
# ---------------------------------------------------------------------------------------------
# 1. Preconditions
# ---------------------------------------------------------------------------------------------
Write-Step 'Checking prerequisites'
if (-not (Get-Command aws -ErrorAction SilentlyContinue)) {
Stop-WithError 'The AWS CLI v2 is not on PATH. Install it (winget install Amazon.AWSCLI) and sign in.'
}
if (-not $OpenSslPath) {
$candidates = @(
(Get-Command openssl -ErrorAction SilentlyContinue)?.Source,
"$env:ProgramFiles\Git\mingw64\bin\openssl.exe",
"$env:ProgramFiles\Git\usr\bin\openssl.exe"
) | Where-Object { $_ -and (Test-Path -LiteralPath $_) }
$OpenSslPath = $candidates | Select-Object -First 1
}
if (-not $OpenSslPath) {
Stop-WithError 'OpenSSL 3.x not found. Install Git for Windows or OpenSSL, or pass -OpenSslPath.'
}
$opensslVersion = & $OpenSslPath version
if ($opensslVersion -notmatch '^OpenSSL 3\.') {
Stop-WithError "RSA_AES_KEY_WRAP needs OpenSSL 3.x; '$OpenSslPath' reports '$opensslVersion'."
}
Write-Ok "OpenSSL: $opensslVersion"
try {
$identity = Invoke-Aws sts get-caller-identity
}
catch {
Stop-WithError "The AWS CLI is not signed in: $($_.Exception.Message)"
}
Write-Ok "Account: $($identity.Account)"
Write-Ok "Identity: $($identity.Arn)"
Write-Ok "Region: $Region"
$existingAliases = (Invoke-Aws kms list-aliases).Aliases
if ($existingAliases | Where-Object { $_.AliasName -eq $aliasName }) {
Stop-WithError "$aliasName already exists in $Region. Choose another -Alias; this script never re-points one."
}
if (-not $PfxPassword) {
$PfxPassword = Read-Host -AsSecureString "Password for '$([System.IO.Path]::GetFileName($PfxPath))' (empty if none)"
}
$pfxFullPath = (Resolve-Path -LiteralPath $PfxPath).Path
if (-not $CerPath) { $CerPath = [System.IO.Path]::ChangeExtension($pfxFullPath, '.cer') }
if ($S3Bucket -and -not $S3Key) { $S3Key = "signing-material/$($aliasName.Substring(6)).cer" }
# ---------------------------------------------------------------------------------------------
# 2. Read the PFX locally, before touching AWS
# ---------------------------------------------------------------------------------------------
Write-Step 'Reading the PFX'
$certificate = $null
try {
$pfxBytes = [System.IO.File]::ReadAllBytes($pfxFullPath)
$flags = [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]'Exportable, EphemeralKeySet'
try {
$certificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($pfxBytes, $PfxPassword, $flags)
}
catch {
$certificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new(
$pfxBytes, $PfxPassword, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)
}
}
catch {
Stop-WithError "Could not open '$pfxFullPath'. Wrong password, or the file is not a PKCS#12 archive. ($($_.Exception.Message))"
}
if (-not $certificate.HasPrivateKey) {
Stop-WithError "'$pfxFullPath' contains no private key. Re-export the PFX including the private key."
}
$certRsa = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($certificate)
if (-not $certRsa) {
Stop-WithError 'The certificate does not carry an RSA key. Bulk Signer accepts only RSA KMS keys (ADR-0041).'
}
$keySpec = "RSA_$($certRsa.KeySize)"
if ($keySpec -notin 'RSA_2048', 'RSA_3072', 'RSA_4096') {
Stop-WithError "The key is $($certRsa.KeySize)-bit RSA; KMS and Bulk Signer accept 2048, 3072 or 4096."
}
Write-Ok "Subject: $($certificate.Subject)"
Write-Ok "Thumbprint: $($certificate.Thumbprint)"
Write-Ok "Valid: $($certificate.NotBefore.ToString('yyyy-MM-dd')) .. $($certificate.NotAfter.ToString('yyyy-MM-dd'))"
Write-Ok "Key: $keySpec"
if ($certificate.NotAfter -lt (Get-Date)) {
Write-Warning "This certificate expired on $($certificate.NotAfter.ToString('yyyy-MM-dd')). Signatures produced with it will not validate."
}
# ---------------------------------------------------------------------------------------------
# 3. Write the public certificate (CerPath)
# ---------------------------------------------------------------------------------------------
Write-Step "Writing the public certificate to $CerPath"
if ($PSCmdlet.ShouldProcess($CerPath, 'Write DER-encoded public certificate')) {
$derBytes = $certificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert)
[System.IO.File]::WriteAllBytes($CerPath, $derBytes)
Write-Ok "$($derBytes.Length) bytes (DER). Public material only — no private key."
}
if ($WhatIfPreference) {
Write-Note 'What-if: stopping before anything is created in AWS.'
exit 0
}
# ---------------------------------------------------------------------------------------------
# 4. Create the KMS key (Origin = EXTERNAL) and its alias
# ---------------------------------------------------------------------------------------------
Write-Step "Creating a $keySpec SIGN_VERIFY key with imported key material"
$keyId = $null
$policyFile = $null
try {
$createArguments = @('kms', 'create-key', '--origin', 'EXTERNAL', '--key-spec', $keySpec, '--key-usage', 'SIGN_VERIFY',
'--description', "Bulk Signer signing key imported from $($certificate.Thumbprint)")
if ($SignerPrincipalArn) {
# KMS's default key policy (the account may delegate to IAM) plus one Deny: kms:Sign by anybody
# not named. aws:PrincipalArn is the role's ARN for an assumed-role session, so a task role
# matches whatever its session is called.
$policy = [ordered]@{
Version = '2012-10-17'
Statement = @(
[ordered]@{
Sid = 'EnableIamUserPermissions'
Effect = 'Allow'
Principal = @{ AWS = "arn:aws:iam::$($identity.Account):root" }
Action = 'kms:*'
Resource = '*'
},
[ordered]@{
Sid = 'OnlyNamedPrincipalsMaySign'
Effect = 'Deny'
Principal = '*'
Action = 'kms:Sign'
Resource = '*'
Condition = @{ StringNotEquals = @{ 'aws:PrincipalArn' = @($SignerPrincipalArn) } }
}
)
}
$policyFile = Join-Path ([System.IO.Path]::GetTempPath()) ("bulksigner-kms-policy-" + [guid]::NewGuid().ToString('N') + '.json')
[System.IO.File]::WriteAllText($policyFile, ($policy | ConvertTo-Json -Depth 8))
$createArguments += @('--policy', "file://$policyFile")
Write-Note "Key policy: kms:Sign denied to everyone except $($SignerPrincipalArn -join ', ')"
}
$created = Invoke-Aws @createArguments
$keyId = $created.KeyMetadata.KeyId
Write-Ok "Key id: $keyId"
Write-Ok "Key ARN: $($created.KeyMetadata.Arn)"
Invoke-Aws kms create-alias --alias-name $aliasName --target-key-id $keyId | Out-Null
Write-Ok "Alias: $aliasName"
}
catch {
Stop-WithError "Creating the key failed: $($_.Exception.Message)" 2
}
finally {
if ($policyFile) { Remove-Item -LiteralPath $policyFile -Force -ErrorAction SilentlyContinue }
}
# ---------------------------------------------------------------------------------------------
# 5. Wrap the private key locally and import it
# ---------------------------------------------------------------------------------------------
Write-Step 'Wrapping the private key and importing it into KMS'
$work = Join-Path ([System.IO.Path]::GetTempPath()) ("bulksigner-kms-" + [guid]::NewGuid().ToString('N'))
New-Item -ItemType Directory -Path $work | Out-Null
$plainKeyFile = Join-Path $work 'private-key.der'
$aesKey = $null
$pkcs8 = $null
try {
# PKCS#8 DER, unencrypted — the format KMS imports. A PFX-loaded Windows CNG key may refuse a
# plaintext export even when marked exportable; copying its parameters into a fresh in-memory RSA
# gives a key that allows it. (Only span-free .NET APIs here: PowerShell cannot pass a Span.)
try {
$pkcs8 = $certRsa.ExportPkcs8PrivateKey()
}
catch {
$rsaParameters = $certRsa.ExportParameters($true)
$rsaCopy = [System.Security.Cryptography.RSA]::Create()
$rsaCopy.ImportParameters($rsaParameters)
$pkcs8 = $rsaCopy.ExportPkcs8PrivateKey()
$rsaCopy.Dispose()
}
[System.IO.File]::WriteAllBytes($plainKeyFile, $pkcs8)
$params = Invoke-Aws kms get-parameters-for-import --key-id $keyId `
--wrapping-algorithm RSA_AES_KEY_WRAP_SHA_256 --wrapping-key-spec RSA_4096
$wrappingKeyFile = Join-Path $work 'wrapping-public-key.der'
$importTokenFile = Join-Path $work 'import-token.bin'
[System.IO.File]::WriteAllBytes($wrappingKeyFile, [Convert]::FromBase64String($params.PublicKey))
[System.IO.File]::WriteAllBytes($importTokenFile, [Convert]::FromBase64String($params.ImportToken))
Write-Ok "Import token valid until $($params.ParametersValidTo)"
# RSA_AES_KEY_WRAP_SHA_256, as AWS documents it: AES-256 key wrap with padding (RFC 5649) of the
# key material, RSAES-OAEP-SHA256 of the AES key under KMS's wrapping key, and the import file is
# the two concatenated, wrapped AES key first.
$aesKey = [System.Security.Cryptography.RandomNumberGenerator]::GetBytes(32)
$aesKeyFile = Join-Path $work 'aes-key.bin'
[System.IO.File]::WriteAllBytes($aesKeyFile, $aesKey)
$keyMaterialWrapped = Join-Path $work 'key-material-wrapped.bin'
& $OpenSslPath enc -id-aes256-wrap-pad -K ([Convert]::ToHexString($aesKey)) -iv A65959A6 `
-in $plainKeyFile -out $keyMaterialWrapped
if ($LASTEXITCODE -ne 0) { throw 'openssl enc -id-aes256-wrap-pad failed.' }
$aesKeyWrapped = Join-Path $work 'aes-key-wrapped.bin'
& $OpenSslPath pkeyutl -encrypt -in $aesKeyFile -out $aesKeyWrapped -inkey $wrappingKeyFile `
-keyform DER -pubin -pkeyopt rsa_padding_mode:oaep -pkeyopt rsa_oaep_md:sha256 -pkeyopt rsa_mgf1_md:sha256
if ($LASTEXITCODE -ne 0) { throw 'openssl pkeyutl (RSAES-OAEP-SHA256) failed.' }
$encryptedMaterial = Join-Path $work 'encrypted-key-material.bin'
[System.IO.File]::WriteAllBytes($encryptedMaterial,
[byte[]]([System.IO.File]::ReadAllBytes($aesKeyWrapped) + [System.IO.File]::ReadAllBytes($keyMaterialWrapped)))
Invoke-Aws kms import-key-material --key-id $keyId `
--encrypted-key-material "fileb://$encryptedMaterial" `
--import-token "fileb://$importTokenFile" `
--expiration-model KEY_MATERIAL_DOES_NOT_EXPIRE | Out-Null
Write-Ok 'Key material imported. KMS will not return it.'
}
catch {
Stop-WithError ("Import failed: $($_.Exception.Message)`n" +
"The key $keyId ($aliasName) exists without key material (state PendingImport). Either fix the cause " +
"and import into it by hand, or remove it: aws kms delete-alias --alias-name $aliasName --region $Region; " +
"aws kms schedule-key-deletion --key-id $keyId --pending-window-in-days 7 --region $Region") 2
}
finally {
foreach ($secretFile in $plainKeyFile, (Join-Path $work 'aes-key.bin')) {
if (Test-Path -LiteralPath $secretFile) {
$length = (Get-Item -LiteralPath $secretFile).Length
[System.IO.File]::WriteAllBytes($secretFile, [byte[]]::new($length))
}
}
if ($pkcs8) { [Array]::Clear($pkcs8) }
if ($aesKey) { [Array]::Clear($aesKey) }
Remove-Item -LiteralPath $work -Recurse -Force -ErrorAction SilentlyContinue
}
# ---------------------------------------------------------------------------------------------
# 6. Confirm the KMS key matches the certificate (mirrors the service's boot check)
# ---------------------------------------------------------------------------------------------
Write-Step 'Verifying the KMS key matches the certificate'
$description = (Invoke-Aws kms describe-key --key-id $keyId).KeyMetadata
$kmsPublicKeyFile = Join-Path ([System.IO.Path]::GetTempPath()) ("bulksigner-kms-pub-" + [guid]::NewGuid().ToString('N') + '.der')
try {
[System.IO.File]::WriteAllBytes($kmsPublicKeyFile,
[Convert]::FromBase64String((Invoke-Aws kms get-public-key --key-id $keyId).PublicKey))
# Compare moduli rather than SPKI bytes: two encoders may spell the same RSA key differently.
$kmsModulus = & $OpenSslPath rsa -pubin -inform DER -in $kmsPublicKeyFile -noout -modulus
$cerModulus = & $OpenSslPath x509 -inform DER -in $CerPath -noout -modulus
}
finally {
Remove-Item -LiteralPath $kmsPublicKeyFile -Force -ErrorAction SilentlyContinue
}
if (-not $kmsModulus -or $kmsModulus -ne $cerModulus) {
Stop-WithError "The KMS key's public half does not match '$CerPath'. Do not configure the service with this pair; inspect $keyId." 2
}
Write-Ok "State: $($description.KeyState), usage $($description.KeyUsage), spec $($description.KeySpec), origin $($description.Origin)"
Write-Ok 'Public keys match. The service will accept this certificate and key at boot.'
# ---------------------------------------------------------------------------------------------
# 7. Optionally upload the .cer to S3
# ---------------------------------------------------------------------------------------------
if ($S3Bucket) {
Write-Step "Uploading the certificate to s3://$S3Bucket/$S3Key"
& aws s3 cp $CerPath "s3://$S3Bucket/$S3Key" --region $Region --only-show-errors
if ($LASTEXITCODE -ne 0) { Stop-WithError "Upload failed; the key is ready, upload $CerPath by hand." 2 }
Write-Ok 'Uploaded. Public material only.'
}
# ---------------------------------------------------------------------------------------------
# 8. Report
# ---------------------------------------------------------------------------------------------
$location = if ($S3Bucket) {
@"
"S3": {
"Bucket": "$S3Bucket",
"Key": "$S3Key",
"Region": "$Region",
"Credential": "InstanceRole"
}
"@
} else {
" `"CerPath`": `"$($CerPath -replace '\\', '\\')`""
}
$s3Statement = if ($S3Bucket) {
@"
,
{
"Effect": "Allow",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::$S3Bucket/$S3Key"
}
"@
} else { '' }
Write-Host ''
Write-Host '─────────────────────────────────────────────────────────────────────────' -ForegroundColor Cyan
Write-Host ' Bulk Signer profile (seed or the dashboard''s New profile → AWS KMS)' -ForegroundColor Cyan
Write-Host '─────────────────────────────────────────────────────────────────────────' -ForegroundColor Cyan
Write-Host @"
"Certificate": {
"Source": "AwsKms",
"AwsKms": {
"Region": "$Region",
"KeyId": "$aliasName",
"Credential": "InstanceRole",
$location
}
}
IAM policy for the service's role (the ECS task role, EC2 instance profile, …):
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["kms:DescribeKey", "kms:GetPublicKey", "kms:Sign"],
"Resource": "$($description.Arn)"
}$s3Statement
]
}
"@
Write-Host 'Next steps:' -ForegroundColor Cyan
Write-Host " 1. Attach the policy above to the role the service runs as."
Write-Host " 2. Configure the profile and restart; the boot repeats the key-match check above."
Write-Host " 3. Once a signature is confirmed, move $pfxFullPath to offline backup and remove other copies."
Write-Host ' KMS will not return the key: that backup is the only way to re-import it.'
Write-Host ''
exit 0
Voltar para: Criptografia · Certificados · Instalação.
CloudFormation — bulksigner-ecs-fargate.yaml
Baixar bulksigner-ecs-fargate.yaml.
Um template do CloudFormation que cria, em uma única stack, a infraestrutura especificada em
Amazon ECS Fargate + Lacuna Signer (CloudFormation): o bucket do S3, três security groups, o
RDS for SQL Server com o banco BulkSigner e o login dele, os segredos gerados, os dois roles, o
balanceador de carga com HTTPS, o cluster, a definição de task e o serviço de uma única task. Uma pequena
função Lambda dentro da stack faz o que o CloudFormation não tem tipo de recurso para fazer: encontra a VPC
padrão, confere o certificado com a chave do KMS antes de enviá-lo e executa a task de criação do banco.
Recebe o alias da chave do KMS e o certificado do Import-PfxToKms.ps1, a imagem do ECR e os ARNs dos
segredos cujos valores são digitados — nunca uma licença ou uma chave como valor de parâmetro. O Lacuna
Signer e o Microsoft Entra ID são parâmetros opcionais, então o mesmo template atende a uma implantação que
só assina arquivos. O bucket e um snapshot final do banco são mantidos quando a stack é excluída. Exige o
Bulk Signer 2.20.0 ou posterior e CAPABILITY_NAMED_IAM.