devsecops

Implementing Code Signing for Artifacts

This skill covers implementing code signing for build artifacts to ensure integrity and authenticity throughout the software supply chain. It addresses signing binaries, packages, and containers using GPG, Sigstore, and platform-specific signing tools, establishing trust chains, and verifying signatures in deployment pipelines.

cicdcode-signingdevsecopssecure-sdlcsigstoresupply-chain
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

When to Use

  • When establishing artifact integrity verification to prevent supply chain tampering
  • When compliance requires cryptographic proof that build artifacts are authentic and unmodified
  • When distributing software to customers who need to verify publisher identity
  • When implementing zero-trust deployment pipelines that reject unsigned artifacts
  • When meeting SLSA Level 2+ requirements for provenance and integrity

Do not use for encrypting artifacts (signing provides integrity, not confidentiality), for container image signing specifically (use cosign), or for source code authentication (use commit signing).

Prerequisites

  • GPG key pair for traditional signing or Sigstore account for keyless signing
  • Code signing certificate from a Certificate Authority for public distribution
  • CI/CD pipeline with access to signing keys or identity provider
  • Verification infrastructure in deployment pipelines

Workflow

Step 1: Generate and Manage Signing Keys

# Generate GPG key for artifact signing
gpg --full-generate-key --batch <<EOF
Key-Type: eddsa
Key-Curve: ed25519
Subkey-Type: eddsa
Subkey-Curve: ed25519
Name-Real: CI Build System
Name-Email: ci-signing@company.com
Expire-Date: 1y
%no-protection
EOF
 
# Export public key for distribution
gpg --armor --export ci-signing@company.com > signing-key.pub
 
# Export private key for CI/CD (store in secrets manager)
gpg --armor --export-secret-keys ci-signing@company.com > signing-key.priv

Step 2: Sign Build Artifacts in CI/CD

# .github/workflows/build-sign.yml
name: Build and Sign
 
on:
  push:
    tags: ['v*']
 
jobs:
  build-sign:
    runs-on: ubuntu-latest
    permissions:
      contents: write
      id-token: write  # For Sigstore keyless signing
    steps:
      - uses: actions/checkout@v4
 
      - name: Build artifacts
        run: |
          make build
          sha256sum dist/* > dist/checksums.sha256
 
      - name: Import GPG Key
        run: |
          echo "${{ secrets.GPG_PRIVATE_KEY }}" | gpg --batch --import
          gpg --list-secret-keys
 
      - name: Sign artifacts
        run: |
          for file in dist/*; do
            gpg --detach-sign --armor --local-user ci-signing@company.com "$file"
          done
 
      - name: Install cosign for keyless signing
        uses: sigstore/cosign-installer@v3
 
      - name: Keyless sign with Sigstore
        run: |
          for file in dist/*.tar.gz; do
            cosign sign-blob "$file" \
              --output-signature "${file}.sig" \
              --output-certificate "${file}.cert" \
              --yes
          done
 
      - name: Create Release with signed artifacts
        uses: softprops/action-gh-release@v2
        with:
          files: |
            dist/*
            dist/*.asc
            dist/*.sig
            dist/*.cert

Step 3: Verify Signatures in Deployment Pipeline

# Verify GPG signature
gpg --import signing-key.pub
gpg --verify artifact.tar.gz.asc artifact.tar.gz
 
# Verify Sigstore keyless signature
cosign verify-blob artifact.tar.gz \
  --signature artifact.tar.gz.sig \
  --certificate artifact.tar.gz.cert \
  --certificate-identity ci-signing@company.com \
  --certificate-oidc-issuer https://token.actions.githubusercontent.com
 
# Verify checksums
sha256sum --check checksums.sha256

Step 4: Sign npm Packages with Provenance

{
  "scripts": {
    "prepublishOnly": "npm run build && npm run test"
  },
  "publishConfig": {
    "provenance": true
  }
}
# Publish npm package with provenance attestation
npm publish --provenance

Key Concepts

Term Definition
Code Signing Cryptographic process of signing software artifacts to verify publisher identity and artifact integrity
Detached Signature Signature stored in a separate file from the artifact, allowing independent distribution
Keyless Signing Sigstore's approach using short-lived certificates tied to OIDC identities instead of long-lived keys
Provenance Metadata describing how, where, and by whom an artifact was built
Transparency Log Append-only log (Rekor) that records all signing events for public auditability
Trust Chain Hierarchical chain from root CA to signing certificate establishing trust in the signer's identity
SLSA Supply-chain Levels for Software Artifacts — framework defining levels of supply chain security

Tools & Systems

  • GPG/PGP: Traditional asymmetric cryptography tool for signing and verifying artifacts
  • Sigstore (cosign): Modern keyless signing infrastructure using OIDC identity and transparency logs
  • Rekor: Sigstore's transparency log recording all signing events immutably
  • Fulcio: Sigstore's certificate authority issuing short-lived certificates bound to OIDC identities
  • notation: Microsoft's artifact signing tool for OCI registries (Project Notary v2)

Common Scenarios

Scenario: Establishing Signed Release Pipeline

Context: An open-source project needs to sign release artifacts so users can verify authenticity and detect tampering.

Approach:

  1. Use Sigstore keyless signing in GitHub Actions (no key management overhead)
  2. Sign all release binaries with cosign sign-blob using OIDC identity
  3. Generate and sign checksums file for bulk verification
  4. Upload signatures, certificates, and checksums alongside release artifacts
  5. Document verification instructions in the project README
  6. Add verification step to the Homebrew formula or apt repository

Pitfalls: GPG key compromise requires revoking and re-signing all artifacts. Sigstore keyless signing avoids this by using ephemeral keys. Long-lived signing keys in CI/CD secrets are a supply chain risk if the CI system is compromised.

Output Format

Artifact Signing Report
========================
Pipeline: Build and Sign v2.3.0
Date: 2026-02-23
Signing Method: Sigstore Keyless + GPG
 
SIGNED ARTIFACTS:
  app-v2.3.0-linux-amd64.tar.gz
    GPG:      PASS (ci-signing@company.com, EdDSA/Ed25519)
    Sigstore: PASS (Rekor entry: 24658135, Fulcio cert issued)
    SHA256:   a1b2c3d4...
 
  app-v2.3.0-darwin-arm64.tar.gz
    GPG:      PASS
    Sigstore: PASS (Rekor entry: 24658136)
    SHA256:   e5f6g7h8...
 
  checksums.sha256
    GPG:      PASS (detached signature)
 
TRANSPARENCY LOG:
  Entries recorded: 3
  Log index range: 24658135-24658137
  Verification: https://search.sigstore.dev
Source materials

References and resources

Everything below is rendered for inspection. Script files are read-only and never run.

References 3

api-reference.md1.8 KB

API Reference: Code Signing Verification Agent

Dependencies

Library Version Purpose
cryptography >=41.0 Ed25519 key generation, signing, and verification

CLI Usage

# Generate keypair
python scripts/agent.py --generate-keys --output-dir /keys/
 
# Sign artifact
python scripts/agent.py --sign build/app.tar.gz --private-key /keys/signing_key.pem
 
# Verify artifacts
python scripts/agent.py \
  --artifacts build/app.tar.gz build/lib.so \
  --public-key /keys/signing_key.pub \
  --output-dir /reports/

Functions

generate_ed25519_keypair(output_dir) -> dict

Calls Ed25519PrivateKey.generate(), serializes to PEM using private_bytes() and public_bytes().

sign_artifact(file_path, private_key_path) -> dict

Loads PEM key via serialization.load_pem_private_key(), calls private_key.sign(data). Writes 64-byte signature to .sig file.

verify_signature(file_path, signature_path, public_key_path) -> dict

Loads public key, calls public_key.verify(signature, data). Catches InvalidSignature.

verify_cosign_signature(image) -> dict

Runs cosign verify <image> via subprocess for container image signature verification.

batch_verify(artifacts, public_key_path) -> list

Verifies multiple artifacts against the same public key.

cryptography API Used

Class/Method Purpose
Ed25519PrivateKey.generate() Generate signing keypair
private_key.sign(data) Sign data (returns 64 bytes)
public_key.verify(signature, data) Verify signature
serialization.load_pem_private_key() Load PEM private key

Output Schema

{
  "summary": {"total": 3, "valid": 2, "invalid": 1},
  "verifications": [{"file": "app.tar.gz", "valid": true, "algorithm": "Ed25519"}]
}
standards.md1.5 KB

Standards Reference: Code Signing for Artifacts

SLSA Framework

Level 1: Build Provenance

  • Document the build process (source, builder, dependencies)
  • Provenance metadata available for all artifacts

Level 2: Signed Provenance

  • Build provenance is signed by the build platform
  • Signatures tied to authenticated builder identity

Level 3: Hardened Build Platform

  • Build process runs on a hardened, isolated platform
  • Provenance is non-falsifiable by the build service

NIST SSDF (SP 800-218)

PS.2: Provide Mechanism for Verifying Software Release Integrity

  • PS.2.1: Make integrity verification information available to consumers
  • Code signing provides cryptographic proof of artifact integrity
  • Transparency logs provide public auditability of signing events

PW.4: Reuse Existing, Well-Secured Software

  • Verify signatures of third-party dependencies before integration
  • Establish trust anchors for acceptable signing identities

CIS Software Supply Chain Security

Artifacts (AR) Controls

  • AR-1: Sign all build artifacts using cryptographic signatures
  • AR-2: Verify artifact signatures before deployment
  • AR-3: Use transparency logs for signing event auditability
  • AR-4: Rotate signing keys on a defined schedule

Executive Order 14028

  • Section 4(e): Agencies shall employ tools and processes to maintain trusted source code supply chains
  • SBOM and artifact signing required for federal software suppliers
  • Sigstore adoption recommended by CISA for open-source supply chain security
workflows.md1.8 KB

Workflow Reference: Code Signing for Artifacts

Signing Pipeline Flow

Build Artifacts


┌──────────────────┐
│ Generate          │
│ Checksums         │
└──────┬───────────┘

       ├──────────────────────┐
       ▼                      ▼
┌──────────────┐    ┌──────────────┐
│ GPG Sign     │    │ Sigstore     │
│ (detached)   │    │ Keyless Sign │
└──────┬───────┘    └──────┬───────┘
       │                    │
       │                    ▼
       │            ┌──────────────┐
       │            │ Rekor Log    │
       │            │ Entry        │
       │            └──────┬───────┘
       │                    │
       └──────────┬─────────┘

       ┌──────────────────┐
       │ Publish Release  │
       │ + Signatures     │
       └──────────────────┘

Signing Methods Comparison

Method Key Management Identity Verification Best For
GPG Manual key lifecycle Key fingerprint gpg --verify Traditional projects
Sigstore Keyless No keys to manage OIDC identity cosign verify-blob Modern CI/CD
Code Signing Cert CA-issued certificate Organization name Platform-specific Windows/macOS apps
npm Provenance Automated GitHub Actions OIDC npm audit signatures npm packages

Scripts 2

agent.py5.9 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Code signing verification agent using cryptography library for Ed25519/RSA signature operations."""

import argparse
import hashlib
import json
import logging
import os
import subprocess
import sys
from datetime import datetime
from typing import List

try:
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
    from cryptography.hazmat.primitives import serialization
    from cryptography.exceptions import InvalidSignature
except ImportError:
    sys.exit("cryptography required: pip install cryptography")

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)


def compute_file_hash(file_path: str, algorithm: str = "sha256") -> str:
    """Compute hash digest of a file."""
    h = hashlib.new(algorithm)
    with open(file_path, "rb") as f:
        for chunk in iter(lambda: f.read(8192), b""):
            h.update(chunk)
    return h.hexdigest()


def generate_ed25519_keypair(output_dir: str) -> dict:
    """Generate Ed25519 signing keypair."""
    private_key = Ed25519PrivateKey.generate()
    private_bytes = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption(),
    )
    public_bytes = private_key.public_key().public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo,
    )
    priv_path = os.path.join(output_dir, "signing_key.pem")
    pub_path = os.path.join(output_dir, "signing_key.pub")
    with open(priv_path, "wb") as f:
        f.write(private_bytes)
    with open(pub_path, "wb") as f:
        f.write(public_bytes)
    return {"private_key": priv_path, "public_key": pub_path, "algorithm": "Ed25519"}


def sign_artifact(file_path: str, private_key_path: str) -> dict:
    """Sign a file artifact using Ed25519."""
    with open(private_key_path, "rb") as f:
        private_key = serialization.load_pem_private_key(f.read(), password=None)
    with open(file_path, "rb") as f:
        data = f.read()
    signature = private_key.sign(data)
    sig_path = file_path + ".sig"
    with open(sig_path, "wb") as f:
        f.write(signature)
    return {
        "file": file_path,
        "signature_file": sig_path,
        "hash_sha256": hashlib.sha256(data).hexdigest(),
        "algorithm": "Ed25519",
    }


def verify_signature(file_path: str, signature_path: str, public_key_path: str) -> dict:
    """Verify an Ed25519 signature against a file."""
    with open(public_key_path, "rb") as f:
        public_key = serialization.load_pem_public_key(f.read())
    with open(file_path, "rb") as f:
        data = f.read()
    with open(signature_path, "rb") as f:
        signature = f.read()
    try:
        public_key.verify(signature, data)
        return {"file": file_path, "valid": True, "algorithm": "Ed25519"}
    except InvalidSignature:
        return {"file": file_path, "valid": False, "error": "Invalid signature"}


def verify_cosign_signature(image: str) -> dict:
    """Verify container image signature using cosign CLI."""
    try:
        result = subprocess.run(
            ["cosign", "verify", image], capture_output=True, text=True, timeout=30)
        return {"image": image, "verified": result.returncode == 0,
                "output": result.stdout[:500]}
    except FileNotFoundError:
        return {"image": image, "error": "cosign not installed"}


def batch_verify(artifacts: List[dict], public_key_path: str) -> List[dict]:
    """Verify signatures for multiple artifacts."""
    results = []
    for art in artifacts:
        result = verify_signature(art["file"], art["signature"], public_key_path)
        results.append(result)
    return results


def generate_report(artifacts: List[str], public_key_path: str) -> dict:
    """Generate code signing verification report."""
    report = {"analysis_date": datetime.utcnow().isoformat(), "verifications": []}
    for art_path in artifacts:
        sig_path = art_path + ".sig"
        if os.path.isfile(sig_path):
            result = verify_signature(art_path, sig_path, public_key_path)
        else:
            result = {"file": art_path, "valid": False, "error": "No signature file found"}
        result["hash_sha256"] = compute_file_hash(art_path)
        report["verifications"].append(result)
    valid = sum(1 for v in report["verifications"] if v.get("valid"))
    report["summary"] = {
        "total": len(report["verifications"]),
        "valid": valid,
        "invalid": len(report["verifications"]) - valid,
    }
    return report


def main():
    parser = argparse.ArgumentParser(description="Code Signing Verification Agent")
    parser.add_argument("--artifacts", nargs="+", help="Files to verify")
    parser.add_argument("--public-key", help="Path to public key PEM")
    parser.add_argument("--generate-keys", action="store_true", help="Generate new keypair")
    parser.add_argument("--sign", help="File to sign (requires --private-key)")
    parser.add_argument("--private-key", help="Path to private key PEM")
    parser.add_argument("--output-dir", default=".")
    parser.add_argument("--output", default="signing_report.json")
    args = parser.parse_args()

    os.makedirs(args.output_dir, exist_ok=True)
    if args.generate_keys:
        keys = generate_ed25519_keypair(args.output_dir)
        print(json.dumps(keys, indent=2))
        return
    if args.sign and args.private_key:
        result = sign_artifact(args.sign, args.private_key)
        print(json.dumps(result, indent=2))
        return
    if args.artifacts and args.public_key:
        report = generate_report(args.artifacts, args.public_key)
        out_path = os.path.join(args.output_dir, args.output)
        with open(out_path, "w") as f:
            json.dump(report, f, indent=2)
        print(json.dumps(report["summary"], indent=2))


if __name__ == "__main__":
    main()
process.py7.3 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""
Artifact Code Signing Pipeline Script

Signs build artifacts using GPG and/or Sigstore cosign,
generates checksums, and produces a signing report.

Usage:
    python process.py --artifacts-dir ./dist --method gpg --gpg-key ci-signing@company.com
    python process.py --artifacts-dir ./dist --method sigstore --output signing-report.json
"""

import argparse
import hashlib
import json
import os
import subprocess
import sys
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path


@dataclass
class SigningResult:
    artifact: str
    sha256: str
    gpg_signature: str = ""
    gpg_verified: bool = False
    sigstore_signature: str = ""
    sigstore_certificate: str = ""
    sigstore_log_index: str = ""
    error: str = ""


def compute_sha256(file_path: str) -> str:
    """Compute SHA256 hash of a file."""
    sha256 = hashlib.sha256()
    with open(file_path, "rb") as f:
        for chunk in iter(lambda: f.read(8192), b""):
            sha256.update(chunk)
    return sha256.hexdigest()


def sign_with_gpg(file_path: str, gpg_key: str) -> dict:
    """Sign a file with GPG detached signature."""
    sig_path = f"{file_path}.asc"
    cmd = [
        "gpg", "--batch", "--yes",
        "--detach-sign", "--armor",
        "--local-user", gpg_key,
        "--output", sig_path,
        file_path
    ]

    try:
        proc = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
        if proc.returncode == 0:
            return {"signature": sig_path, "error": ""}
        return {"signature": "", "error": proc.stderr[:200]}
    except (subprocess.TimeoutExpired, FileNotFoundError) as e:
        return {"signature": "", "error": str(e)}


def sign_with_cosign(file_path: str) -> dict:
    """Sign a file with Sigstore cosign keyless signing."""
    sig_path = f"{file_path}.sig"
    cert_path = f"{file_path}.cert"

    cmd = [
        "cosign", "sign-blob", file_path,
        "--output-signature", sig_path,
        "--output-certificate", cert_path,
        "--yes"
    ]

    try:
        proc = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
        if proc.returncode == 0:
            log_index = ""
            for line in proc.stderr.split("\n"):
                if "tlog entry" in line.lower() or "log index" in line.lower():
                    parts = line.split(":")
                    if len(parts) > 1:
                        log_index = parts[-1].strip()
            return {
                "signature": sig_path,
                "certificate": cert_path,
                "log_index": log_index,
                "error": ""
            }
        return {"signature": "", "certificate": "", "log_index": "", "error": proc.stderr[:200]}
    except (subprocess.TimeoutExpired, FileNotFoundError) as e:
        return {"signature": "", "certificate": "", "log_index": "", "error": str(e)}


def verify_gpg_signature(file_path: str, sig_path: str) -> bool:
    """Verify a GPG detached signature."""
    cmd = ["gpg", "--verify", sig_path, file_path]
    try:
        proc = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
        return proc.returncode == 0
    except (subprocess.TimeoutExpired, FileNotFoundError):
        return False


def generate_checksums(artifacts_dir: str, artifacts: list) -> str:
    """Generate checksums file for all artifacts."""
    checksums_path = os.path.join(artifacts_dir, "checksums.sha256")
    lines = []
    for result in artifacts:
        filename = os.path.basename(result.artifact)
        lines.append(f"{result.sha256}  {filename}")

    with open(checksums_path, "w") as f:
        f.write("\n".join(lines) + "\n")

    return checksums_path


def main():
    parser = argparse.ArgumentParser(description="Artifact Code Signing Pipeline")
    parser.add_argument("--artifacts-dir", required=True, help="Directory containing artifacts to sign")
    parser.add_argument("--method", default="both", choices=["gpg", "sigstore", "both"])
    parser.add_argument("--gpg-key", default=None, help="GPG key identity for signing")
    parser.add_argument("--output", default="signing-report.json")
    parser.add_argument("--extensions", nargs="*", default=[".tar.gz", ".zip", ".whl", ".deb", ".rpm"],
                        help="File extensions to sign")
    args = parser.parse_args()

    artifacts_dir = os.path.abspath(args.artifacts_dir)
    results = []

    files_to_sign = []
    for f in sorted(Path(artifacts_dir).iterdir()):
        if f.is_file() and any(str(f).endswith(ext) for ext in args.extensions):
            files_to_sign.append(str(f))

    if not files_to_sign:
        print(f"[WARN] No artifacts found matching extensions: {args.extensions}")
        sys.exit(0)

    print(f"[*] Signing {len(files_to_sign)} artifacts in {artifacts_dir}")

    for file_path in files_to_sign:
        filename = os.path.basename(file_path)
        result = SigningResult(artifact=file_path, sha256=compute_sha256(file_path))

        if args.method in ("gpg", "both") and args.gpg_key:
            gpg_result = sign_with_gpg(file_path, args.gpg_key)
            result.gpg_signature = gpg_result["signature"]
            if gpg_result["signature"]:
                result.gpg_verified = verify_gpg_signature(file_path, gpg_result["signature"])
                print(f"  [GPG] {filename}: {'OK' if result.gpg_verified else 'FAILED'}")
            else:
                print(f"  [GPG] {filename}: ERROR - {gpg_result['error']}")

        if args.method in ("sigstore", "both"):
            cosign_result = sign_with_cosign(file_path)
            result.sigstore_signature = cosign_result.get("signature", "")
            result.sigstore_certificate = cosign_result.get("certificate", "")
            result.sigstore_log_index = cosign_result.get("log_index", "")
            if result.sigstore_signature:
                print(f"  [Sigstore] {filename}: OK (log: {result.sigstore_log_index})")
            else:
                print(f"  [Sigstore] {filename}: ERROR - {cosign_result.get('error', 'unknown')}")
                result.error = cosign_result.get("error", "")

        results.append(result)

    checksums_path = generate_checksums(artifacts_dir, results)
    print(f"\n[*] Checksums: {checksums_path}")

    report = {
        "metadata": {
            "signing_date": datetime.now(timezone.utc).isoformat(),
            "method": args.method,
            "artifacts_count": len(results)
        },
        "artifacts": [
            {
                "file": os.path.basename(r.artifact),
                "sha256": r.sha256,
                "gpg_signed": bool(r.gpg_signature),
                "gpg_verified": r.gpg_verified,
                "sigstore_signed": bool(r.sigstore_signature),
                "sigstore_log_index": r.sigstore_log_index
            }
            for r in results
        ]
    }

    output_path = os.path.abspath(args.output)
    with open(output_path, "w") as f:
        json.dump(report, f, indent=2)
    print(f"[*] Report: {output_path}")

    all_signed = all(
        (r.gpg_verified or args.method == "sigstore") and
        (bool(r.sigstore_signature) or args.method == "gpg")
        for r in results
    )
    print(f"\n[{'PASS' if all_signed else 'FAIL'}] All artifacts signed: {all_signed}")
    if not all_signed:
        sys.exit(1)


if __name__ == "__main__":
    main()

Assets 1

template.mdtext/markdown · 1.2 KB
Keep exploring