Skip to content

How-To: Sign Container Images with Cosign

Sign a container image with cosign using a key held in the Keyserver. The signature comes from a normal Keyserver sign order, so the private key stays in the Keyserver.

Internal Authserver for Testing Only

On the trial environment the internal Authserver may be used for testing. Production signing must authenticate through an external OAuth2/OIDC provider, such as Azure Entra ID or GitLab OIDC. See the Authentication Model.

Choosing a method

There are two ways to sign with a Keyserver-held key:

Stock cosign + REST flow PKCS#11-enabled Cosign build
Cosign binary Official release, unmodified Built once from source with Go and gcc, in about a minute
Signing Seven scriptable steps: payload, sign order, attach One cosign sign command
Best when CI policy requires official binaries, or you do not want to build tools You sign often and can keep one built binary in your toolchain

Both methods apply the same custody, approvals, usage counts and audit, and both verify with the same stock-cosign command.

How it works (stock-binary REST flow)

sequenceDiagram
    participant C as cosign
    participant K as Keyserver

    C->>C: generate payload from image manifest
    C->>K: POST /api/signorders (hash of payload)
    K-->>C: signature (hex)
    C->>C: attach signature to image

Diagram: cosign; Keyserver; generate payload from image manifest; POST /api/signorders (hash of payload); signature (hex); attach signature to image

Cosign's key-based mode does not need a live signer. You generate the payload, submit its hash as a normal Keyserver sign order, and hand the returned signature back to cosign to attach. No PKCS#11 module is involved. The private key never reaches this machine: the pipeline sends only the hash, and the Keyserver returns the signature. This holds for KEYSTORE keys too: such a key leaves the Keyserver only through an explicit export.

Prerequisites

  • The cosign binary (v3.x), from the sigstore releases
  • A container registry you can push to, and an image already pushed to it
  • curl, jq, openssl, python3
  • An OAuth2 client whose subject has a role built from the fwsigner nature scoped to the signing key. See Manage Roles in the Keyserver.
  • The signing key's ID: a normal Keyserver FW key. This guide uses an EC/SHA-256 key, fw-quickstart.

Set the base URL and authenticate:

export KSC_API_SERVER="https://keyserver.<UNIQUE-ID>.cryptera-security.io"
export AUTH_CREDS=$(printf '%s' "<CLIENT_ID>:<CLIENT_SECRET>" | base64 | tr -d '\n')

export TOKEN=$(
  curl -sS --tlsv1.3 \
    -X POST \
    -H "Authorization: Basic $AUTH_CREDS" \
    -d "grant_type=client_credentials" \
    https://authserver.<UNIQUE-ID>.cryptera-security.io/oauth2/token \
    | jq -r .access_token
)

[ -n "$TOKEN" ] && [ "$TOKEN" != null ] && echo "token OK (${#TOKEN} chars)"

Expected output: token OK ( followed by the token length. If it prints nothing, the credentials or the Authserver URL are wrong. The check never prints the token itself.

Step 1: Get the Key's Certificate and Public Key

curl -sS --tlsv1.3 \
  -H "Authorization: Bearer $TOKEN" \
  "$KSC_API_SERVER/api/keys/<KEYID>" | jq -r .certificate > cert.pem

openssl x509 -in cert.pem -noout -pubkey > pubkey.pem

pubkey.pem verifies the signature in Step 7. It is not sent to cosign or the registry.

Step 2: Generate the Cosign Signing Payload

cosign generate <REGISTRY>/<IMAGE>:<TAG> > payload.json
HASH=$(sha256sum payload.json | awk '{print $1}')

cosign generate prints a deprecation notice to stderr; ignore it. The payload goes to stdout.

Step 3: Create and Approve a Signing Operation

export OPERATION_ID=$(
  curl -sS --tlsv1.3 \
    -X POST "$KSC_API_SERVER/api/operations" \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
          "validms": 60000,
          "description": "cosign signing of <IMAGE>:<TAG>",
          "new-keyusagerestrictions": [
            { "keyid": "<KEYID>", "maxusagecount": 1 }
          ]
        }' | jq -r .id
)

echo "$OPERATION_ID"

If the key requires approvers, approve the operation before continuing. See Approval Workflow. Confirm before proceeding:

curl -sS --tlsv1.3 -H "Authorization: Bearer $TOKEN" \
  "$KSC_API_SERVER/api/operations/$OPERATION_ID" | jq .approved

Expected output: true. Keys with 0 required approvers are approved immediately.

Step 4: Submit the Sign Order

inputpadding: none tells the Keyserver that inputdata is a bare hash. This is right for both ECDSA and RSA keys: for an RSA key, the Keyserver adds the PKCS#1 DigestInfo itself. Use digestinfo only when you submit a hash that is already DigestInfo-wrapped. description is required and is recorded in the audit log for this sign order.

export SIGHEX=$(
  curl -sS --tlsv1.3 \
    -X POST "$KSC_API_SERVER/api/signorders" \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d "{
          \"operationid\": \"$OPERATION_ID\",
          \"keyid\": \"<KEYID>\",
          \"inputdata\": \"$HASH\",
          \"inputformat\": \"hex\",
          \"inputpadding\": \"none\",
          \"signatureformat\": \"asn1\",
          \"description\": \"cosign signing of <IMAGE>:<TAG>\"
        }" | jq -r .result
)

echo "$SIGHEX"

A null result means the call failed, and the error body says why. See If something fails.

Step 5: Convert the Signature to Base64

Cosign expects a base64-encoded signature file; the Keyserver returned hex:

python3 -c "import base64;open('sig.b64','w').write(base64.b64encode(bytes.fromhex('$SIGHEX')).decode())"

Step 6: Attach the Signature to the Image

Use --allow-http-registry only with a local test registry

For a registry served over plain HTTP, add --allow-http-registry to each cosign command that contacts it, here cosign attach and cosign verify. The flag sends image references, registry credentials and signatures unencrypted, where they can be intercepted or altered. A production registry must use HTTPS; omit the flag there.

cosign attach signature --payload payload.json --signature sig.b64 <REGISTRY>/<IMAGE>:<TAG>

Step 7: Verify

cosign verify --key pubkey.pem --insecure-ignore-tlog=true <REGISTRY>/<IMAGE>:<TAG>

--insecure-ignore-tlog=true is required because key-based signing with the Keyserver creates no transparency-log entry. The flag skips only the log lookup; cosign still verifies the signature against pubkey.pem.

If something fails

Symptom Cause and fix
Token check prints nothing Wrong credentials or Authserver URL
401 "The user/client is not valid" The client ID does not match a registered subject
403 "Access forbidden" on /api/signorders The subject lacks the fwsigner permission for the key, or for another key in the operation
409 on /api/signorders "Need more approvers": the operation is not yet approved. "The key has already been used the allowed number of times": the usage count is exhausted. A creatorowns message: another client created the operation
404 "The key is not associated with the given operation" <KEYID> is not part of the operation
410 "Operation has expired" validms elapsed. Create a new operation
410 "Operation is cancelled" An approver revoked the operation, or its creator cancelled it. Create a new operation
410 "Signing key has been revoked" The key is revoked and cannot sign. Use another key
400 on /api/signorders inputdata is not valid hex, or a field has a value the API does not accept
cosign attach rejects the signature file sig.b64 is not base64-encoded: Step 5 was skipped or produced hex
cosign verify fails payload.json changed after signing, HASH came from a different payload, the wrong pubkey.pem was extracted, or an RSA sign order used inputpadding: digestinfo with a bare hash. Re-generate the payload and sign again

Full status-code reference: Error Codes.

Building a PKCS#11-enabled Cosign

Official Cosign releases ship without PKCS#11 support; cosign sign --key "pkcs11:..." fails with "unimplemented". A PKCS#11-enabled build signs through the Keyserver PKCS#11 module with one cosign sign command.

Build

Requires Go 1.26 or later and gcc:

git clone --depth 1 --branch v3.1.2 https://github.com/sigstore/cosign
cd cosign
CGO_ENABLED=1 go build -tags=pkcs11key -o cosign-pkcs11 ./cmd/cosign

The build takes about a minute. The binary is portable across recent glibc Linux systems.

Configuration

The module reads its Keyserver connection from the environment once, when it loads, per the PKCS#11 Library Reference: KSC_API_SERVER, KSC_ID_TOKEN (the access token) and KSC_OPERATION_ID. The operation must be approved, as in Step 3.

Cosign also needs:

  • A dummy, non-empty PIN. Cosign always performs a PKCS#11 login, although the Keyserver module needs no PIN. An empty PIN fails with CKR_ARGUMENTS_BAD. Any non-empty value works: pin-value=1234 in the PKCS#11 URI, or COSIGN_PKCS11_PIN.
  • COSIGN_PKCS11_IGNORE_CERTIFICATE=1, so Cosign produces a plain key signature that cosign verify --key pubkey.pem accepts. Without it, Cosign embeds the token's certificate object, and key-based verification fails with "expected key signature, not certificate".

Key discovery

./cosign-pkcs11 pkcs11-tool list-keys-uris --module-path /path/to/libpkcs11ks.so --pin 1234

Sign

Pass both flags, or Cosign uploads to the public transparency log

By default, Cosign v3 signing and attestation commands upload signature metadata, such as artifact digests and a public-key fingerprint, to the public Sigstore transparency log (rekor.sigstore.dev), permanently. cosign attest and cosign attest-blob also fetch an RFC 3161 timestamp from a public timestamp authority. Passing --use-signing-config=false --tlog-upload=false together disables both. With either flag missing, Cosign still uploads. --tlog-upload is deprecated and hidden from --help, but it works.

./cosign-pkcs11 sign \
  --key "pkcs11:token=KEYSERVER;object=<KEYID>;type=private?module-path=/path/to/libpkcs11ks.so&pin-value=1234" \
  --use-signing-config=false --tlog-upload=false \
  <REGISTRY>/<IMAGE>@<DIGEST>

Verify

Verification uses the stock-cosign command from Step 7:

cosign verify --key pubkey.pem --insecure-ignore-tlog=true <REGISTRY>/<IMAGE>@<DIGEST>