Architecture

This page traces how the pieces actually fit together, down to the specific types and files, so it stays checkable against the source rather than being a generic description.

Components

Sources/
├── scdaemon-se/
│   └── main.swift            Entry point: CLI flags, or run as the daemon
└── SCDaemonLib/
    ├── Assuan.swift            Assuan protocol: request/response types,
    │                           the AssuanServer actor, line-based stdin reader
    ├── OpenPGPCard.swift        Command dispatch (OpenPGPCardHandler),
    │                           DangerConfig env-var gates, active-card model
    ├── SecureEnclave.swift      CryptoKit + Keychain wrapper (SecureEnclaveManager),
    │                           Touch ID prompts, key pinning
    ├── CardRegistry.swift       Pure model: the set of virtual cards
    ├── KeyPinStore.swift        Pure model: per-tag expected-keygrip pins
    ├── Keygrip.swift            libgcrypt-compatible keygrip computation
    ├── AuthPrompts.swift        Builds the Touch ID prompt reason string
    ├── CardInspection.swift     Pure formatter for `--inspect` output
    ├── OpenPGPPacket.swift      RFC 4880 packet construction (export only)
    └── Logger.swift             stderr logger, gated by SCDAEMON_SE_DEBUG

SCDaemonLib is a library target; scdaemon-se is a thin executable that either handles a CLI flag directly or starts the Assuan server. This split is also what lets the unit test target (scdaemon-seTests) exercise OpenPGPCardHandler directly, without going through stdin/stdout.

Request flow

gpg-agent
   │  spawns
   ▼
scdaemon-se (main.swift)
   │  no CLI flag matched → runs the daemon
   ▼
AssuanServer.run()  (actor, Assuan.swift)
   │  reads stdin line-by-line via AsyncLineSequence
   │  for each line: builds an AssuanRequest, calls handler.handle(request)
   ▼
OpenPGPCardHandler.handle(_:)  (OpenPGPCard.swift)
   │  switches on request.command, dispatches to a handleXxx(...) method
   ▼
SecureEnclaveManager  (SecureEnclave.swift)
   │  loads/creates keys, verifies key pins, performs the actual
   │  CryptoKit operation (may raise a Touch ID / passcode prompt)
   ▼
response written back to gpg-agent over stdout

AssuanServer is a Swift actor— it awaits handler.handle(_:) for one request at a time and only starts reading the next line afterward, so OpenPGPCardHandler’s mutable state (which signing/decryption/auth keys are currently loaded, the active card, pending SETDATA bytes) is never accessed concurrently even though the handler itself isn’t an actor.

Every line read and every line sent is logged via Logger.debug, gated by the SCDAEMON_SE_DEBUG environment variable, through redactForLog — which strips the payload out of D ... and SETDATA ... lines (including SCD-wrapped and lowercased variants) before logging, so raw digests, signatures, and shared secrets never reach the log even in debug mode.

Worked example: PKSIGN

A real git commit -S (or any gpg --sign) drives roughly this sequence. Line references are to the current source.

  1. gpg-agent sends SETDATA <hex> — handleSetData hex-decodes the argument into pendingData.
  2. gpg-agent sends PKSIGN <keygrip> (or PKSIGN with no keygrip, for a client that only knows about one signing key).
  3. handlePkSign calls ensureKeys() (loads the primary signing/auth key, and the decryption key only if present or explicitly allowed — see Security Model), then resolves the keygrip:
    • No keygrip given → falls back to the primary signing key.
    • Keygrip matches a signing-role key (primary, or an additional card’s signing key) → uses that key.
    • Keygrip matches the auth key → refused outright (ERR 119), before any Secure Enclave interaction. PKSIGN must not be able to drive the authentication key.
  4. extractDigest validates pendingData: it must be exactly 32 bytes (a raw SHA-256 digest) or 51 bytes starting with the standard SHA-256 DigestInfo prefix, in which case the prefix is stripped. Anything else is rejected — this is the boundary that stops a malformed or hostile SETDATA payload from ever reaching the signing call.
  5. AuthPrompts.touchIDReason(action: .sign, slot: "OPENPGP.1", serial:) builds the reason string shown in the Touch ID prompt — it names the action, the slot, and which card, resolved by keygrip if one was given.
  6. SecureEnclaveManager.signDigest reloads the key bound to an LAContext carrying that reason (so the same stored key handle produces a prompt naming the right operation) and calls CryptoKit’s signature(for:), which is where the actual Touch ID / passcode prompt happens.
  7. The response is the signature’s rawRepresentation — raw r‖s (64 bytes for P-256), not DER — because that’s the format gpg-agent expects back from PKSIGN/PKAUTH. (The one place a DER signature is built is inside OpenPGPPacketBuilder, for the self-signatures on an exported public key — see below.)
  8. pendingData is cleared (defer) whether the operation succeeds or fails.

PKAUTH and PKDECRYPT follow the same shape: PKAUTH mirrors step 3 in the other direction (refuses a signing-role keygrip), and PKDECRYPT does ECDH key agreement (performKeyAgreement) instead of signing, returning the raw shared secret bytes for gpg-agent to derive the symmetric key from.

Multi-card model

scdaemon-se can present more than one virtual OpenPGP card (see Guides → Multiple signing keys). This is modeled by CardRegistry: a list of CardRecords, each with a serial and the Keychain tags of its key(s). The primary card (index 0) is the only one with decryption and authentication slots; every other card is signing-only.

gpg-agent only ever drives one active card at a time — it doesn’t ask for a list and pick one; it either uses whatever’s active, or switches with SCD SERIALNO --demand=<serial>. OpenPGPCardHandler tracks activeCardSerial accordingly, and SERIALNO --all deliberately reports only the active card (reporting every card here breaks gpg-agent’s own keygrip → card bookkeeping during subkey binding — this was verified against real gpg behavior, not assumed). Once a subkey is bound, ordinary signing routes to the right card purely by keygrip, with no --demand needed.

Card serials and AIDs

The AID gpg --card-status prints (e.g. D276000124010304D3FB65E9498AA2E30000) is three concatenated pieces, built by SecureEnclaveManager.aid(forSerial:) in SecureEnclave.swift:

D276000124010304   D3FB65E9498AA2E3   0000
└── fixed prefix ──┘└── serial ──────┘└ suffix ┘
   (8 bytes)          (8 bytes)        (2 bytes)
  • The prefix and suffix are fixed by the OpenPGP card spec (RID + application + version, and a reserved trailer) — every OpenPGP card, real or emulated, has them.
  • The serial in the middle is the only part scdaemon-se controls: randomSerial() draws 8 random bytes from SecRandomCopyBytes.

A real smartcard vendor gets a manufacturer ID assigned centrally and just increments a counter, so collisions are impossible by construction. scdaemon-se has no such authority — every --add-signing-card mints a serial locally with no coordination — so it needs enough entropy that two independently-generated serials are very unlikely to collide. A collision would matter: CardRegistry and SecureEnclaveManager key Keychain storage tags off the serial, so two cards colliding would fight over the same signing-key storage slot. 8 random bytes (64 bits) makes that essentially impossible, at no real cost — the serial isn’t meant to be typed from memory, only copy-pasted from --list-cards/--card-status output or scripted against with --demand=<serial>.

Key storage and identity

Every Secure Enclave key is referenced only by an opaque handle (SecureEnclave.P256.*.PrivateKey.dataRepresentation) stored as a generic password in the macOS Keychain under the service scdaemon-se, tagged by account (e.g. com.scdaemon-se.gpg.signing, or com.scdaemon-se.card.<serial>.signing for an additional card). Alongside that, SecureEnclaveManager maintains:

  • A card registry (com.scdaemon-se.cards) — which cards exist and which tags belong to which slot.
  • A key pin store (com.scdaemon-se.keypins) — the expected keygrip for each tag, recorded the first time a key is generated or loaded. Every subsequent load recomputes the keygrip and compares it; a mismatch is refused rather than silently used. See Security Model for why this exists and what it does and doesn’t protect against.

Every Keychain write (storeData) checks the actual SecItemAdd status and reads the value back to confirm it round-tripped before treating the write as successful — a freshly-generated Secure Enclave key has no other way to be located, so a silently-failed write would otherwise orphan it permanently.

The one thing that isn’t Assuan traffic: --export-public-key

Everything above is the daemon path (stdin/stdout, driven by gpg-agent). OpenPGPPacketBuilder (OpenPGPPacket.swift) is only used by scdaemon-se --export-public-key, which builds a full RFC 4880 transferable public key (primary key packet, user ID packet, self-signature, subkey packets and binding signatures) locally and prints it armored — gpg --import consumes the output, it’s never sent over the Assuan protocol. See CLI Reference and Guides → Subkeys under an external master for why exporting a standalone identity this way is gated and generally not the recommended pattern.


scdaemon-se is licensed under the MIT License.

This site uses Just the Docs, a documentation theme for Jekyll.