fido

package module
v0.17.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2026 License: BSD-3-Clause Imports: 25 Imported by: 6 modules, 6 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

fido

Go Reference License CI

Speaks the FIDO client-to-authenticator protocol to a security key, in pure Go with CGO_ENABLED=0, on any operating system.

k, err := fido.Open(ctx, transport)   // handshake, channel, capabilities
defer k.Close()
fmt.Println(k)                        // YubiKey FIDO (CTAPHID v2, firmware 5.7.4, wink, ctap2, ctap1) on channel 0x…
err = k.Wink(ctx)                     // the key blinks: which one is this?

Nothing here is platform-specific. A Transport moves 64-byte reports to and from one authenticator, and where those come from — IOKit on macOS, hidraw on Linux, WebHID in a browser — is somebody else's problem. The macOS one is go-macos/fido.

The second factor

An operating system already offers the first: Touch ID, a watch, a passcode. Those answer is the person at this machine the one who unlocked it? A security key answers a different question: is the thing they carry present, right now, and did a human touch it? Multi-factor means asking both and getting two independent answers.

Reading the reference first

In pure Go, client-side, there was nothing to reuse. The reference of the field is Yubico's libfido2, written in C; its one serious Go binding wraps it through cgo and has not moved in ten months, and the pure-Go candidates are small and young. So libfido2 and the CTAP specification are read here as documentation, and the code is owned.

Reading them first caught two faults that testing against a key would not have, because a short ping comes back the same either way:

  • CTAPHID_KEEPALIVE is not an answer. A key waiting for a finger sends one about every hundred milliseconds for as long as the person takes. A reader that returns the first complete message hands back a status byte instead of the reply — and does it early, so it reads as the key talking nonsense rather than as a missing feature.
  • The message limit is the framing's, not the length field's. Two length bytes would allow 65535; the framing reaches 7609, because past that the sequence numbers run into the high bit and a key reads them as the start of a new message. An earlier draft used 65535 and carried a comment asserting the framing reached it. The arithmetic was wrong.

A key is not trusted to answer what it was asked, either. A reply is refused unless it carries the command that was sent (CTAP 2.1 §11.2.9 gives each command's response its own CMD, and libfido2 checks it too). A PIN token is refused unless it has its protocol's length: 16 or 32 bytes under protocol one, exactly 32 under protocol two (§6.5.6, §6.5.7). Both checks came from a security review: neither had a demonstrated impact, but nothing else stood between what a forged key sends and the parser that reads it.

What is here

The CTAPHID framing, the handshake, channel negotiation, capabilities, ping and wink — covered to 100%, with a fake transport that reassembles what it is sent, so a key that refuses, a key that stalls, a key that keeps saying it is busy and another program talking on the same key are all ordinary tests.

The framing is exported for whoever drives a key some other way: Split cuts a message into 64-byte reports, NewReassembler and Reassembler.Feed put replies back together into a Message, ParseInit reads the INIT reply, and Key.CBOR sends a raw CTAP2 command and returns the body, a failing Status turned into an error. go-authn/keyfactor's tests drive their fake key with exactly these.

GetInfo asks a CTAP2 authenticator to describe itself -- versions, extensions, AAGUID, options -- and is decoded against a reply CAPTURED FROM A REAL KEY rather than one written by hand from the specification. A fixture written from the spec only proves the code agrees with whoever wrote the fixture.

CBOR comes from fxamacker/cbor, which is what go-webauthn/webauthn depends on and which ships CTAP2EncOptions for exactly this. Unlike the CTAP client space, CBOR in Go has a reference, so this uses it.

MakeCredential registers a credential and GetAssertion asks the authenticator to sign, with the parameters numbered as the specification numbers them and the authenticator data parsed -- flags, sign count, credential id, COSE public key, extensions.

The authenticator-data parser is checked against a sample from go-webauthn/webauthn's own tests: an EXTERNAL witness. Every other fixture here came from hardware or from this code, so it is the only one that can catch those two agreeing with each other and both being wrong. It caught something immediately -- the prose describing that sample says its flags are 0x45, and the bytes say 0x41. The bytes win.

AuthData.PublicKey turns the credential's COSE key into a *ecdsa.PublicKey, so a caller can check the signature with the standard library and nothing else. That is a CONVERSION, not a verification: what counts as valid -- which algorithms, what to do about a sign counter that went backwards -- belongs to whoever is protecting something.

All of it has been run against a real YubiKey FIDO 5.7.4: registered, asserted, and the signature verified against the public key the key itself handed out.

authenticatorClientPIN (CmdClientPIN) is here: both PIN/UV auth protocols, PINRetries, KeyAgreement and PINToken, and a token wires into MakeCredential and GetAssertion to turn "somebody touched the key" into "somebody who knows its PIN touched it".

PINToken with permissions sends the permissions at key 0x09 and the RP id at 0x0A, as CTAP 2.1 (6.5.5) numbers them; before v0.6.4 it used 0x07 and 0x08, which a YubiKey answers with CTAP2_ERR_MISSING_PARAMETER. A test checks the request's map keys against the specification's table.

The two protocols are not a version number. Protocol one hashes the ECDH output once and uses the same 32 bytes as both AES and HMAC key, with a zero initialisation vector and a 16-byte truncated HMAC; protocol two derives two separate keys through HKDF, prepends a fresh IV, and truncates nothing. A package that treated them as interchangeable would pass every round-trip test and be wrong on the wire, so a test plays the AUTHENTICATOR's side and checks that both sides derive the same secret.

The status-code table comes from libfido2's err.h, and it had to: an earlier version was written from memory and five of its entries were wrong. A real key caught it by answering 0x35 -- no PIN set -- which the table did not name while claiming 0x2F meant that.

Extensions, hmac-secret, credProtect and built-in verification

MakeCredentialRequest.Extensions and GetAssertionRequest.Extensions carry the extensions parameter, and AuthData.ExtensionOutputs reads what comes back. hmac-secret (CTAP 2.1, 12.5) works under both PIN/UV auth protocols: register with Extensions{HMACSecret: true}, then ask for one or two secrets with GetAssertionRequest.HMACSecret (32-byte salts) and read Assertion.HMACSecret. credProtect takes the policies 1, 2 and 3, and ExtensionOutputs refuses a key that reports any other value.

Key.UVToken obtains a pinUvAuthToken by built-in user verification, such as a fingerprint sensor (getPinUvAuthTokenUsingUvWithPermissions, subcommand 0x06); Key.PINToken is the PIN alternative, and either token goes into the same request.

Two traps are covered by tests against a software authenticator written from the specification (and, with FIDO_REAL=1, by go-macos/fido's test on a real key): an authenticator derives a DIFFERENT hmac-secret for a verified request than for an unverified one, with nothing in the output to tell them apart, so HMACSecret.RequireUV refuses to return the unverified one; and a credProtect 3 credential answers "no credentials" to a probe made before verification, so verify first. Which salts, which protocol, and whether a PIN is accepted in place of a finger are the caller's choices; this package encodes and decodes.

Setting a PIN, and enrolling fingerprints

Key.SetPIN (key has no PIN) and Key.ChangePIN implement clientPIN subcommands 0x03 and 0x04 (CTAP 2.1 6.5.5.5 and 6.5.5.6); give them Info.MinPINLength so a PIN the key would refuse costs no exchange. Info.ForcePINChange says the PIN must be changed before it is used again.

A PIN you hold as a []byte goes through Key.PINTokenBytes, Key.SetPINBytes and Key.ChangePINBytes (and CheckNewPINBytes): the PIN is hashed in place, no string is made of it, nothing is kept, and the copies made on the way (the digest, the padded block) are wiped, so defer clear(pin) in the caller leaves no copy behind. The string forms (PINToken, SetPIN, ChangePIN) are deprecated: a string cannot be wiped. The requests are identical, in the same order.

Key.Bio(info) drives authenticatorBioEnrollment (6.7) on a key that declares bioEnroll (command 0x09, token with PermBioEnrollment) or the prototype userVerificationMgmtPreview (command 0x40, a plain getPinToken token):

b, _ := k.Bio(info)
tok, _ := k.PINTokenBytes(ctx, pin, proto, b.Permissions(), "") // pin is a []byte
id, err := b.Enroll(ctx, tok, 0, func(s fido.EnrollStep) {
	fmt.Println(s.Status, s.Remaining, "samples left")
})
b.Rename(ctx, tok, id, "right index")

A bad sample (finger too fast, off-centre, not lifted) does not count and the loop asks again; an enrollment that fails or is cancelled is cancelled on the key. Tested against a software authenticator that checks the MACed bytes; not run against a real key.

Several keys: choose, never "the first"

The transports list keys (go-macos/fido and go-gnulinux/fido: Devices/OpenDevice), and Select chooses among them by touch: every key is asked for user presence at once (authenticatorSelection, CTAP 2.1 6.9), the first touched wins and the rest get CTAPHID_CANCEL. Selected.AlsoTouched names keys touched in the same instant, so a caller about to change something can refuse an ambiguous choice; Key.Identity says, without a touch, which key is which (aaguid, PIN set, fingerprints enrolled).

Naming a key, on the key

The port a key sits in is not the key, the AAGUID names a model, and most keys publish no serial. Key.SetName stores a name IN the key: a discoverable credential under the reserved relying party name.fido (credProtect 1) whose user handle is the name (at most 64 bytes of UTF-8, no control characters). Key.ReadName reads it with no touch and no PIN (getAssertion, up false, no pinUvAuthParam). CTAP 2.1 does not make every key answer that, so a refused read is ErrNameRefused and a caller needs a fallback. SetName replaces: the old name is deleted first (credential management, 6.8), so a key never holds two.

What a key is: the FIDO Metadata Service (package mds)

getInfo reports an AAGUID, but the key says it itself: only a verified attestation proves it. github.com/go-authn/fido/mds turns an AAGUID into what the FIDO Alliance publishes about that model (MDS3, spec v3.0 PS 2021-05-18): description, authenticator version, attestation types, key protection, user verification methods, the certification history (statusReports) and the attestationRootCertificates a relying party should chain an attestation to.

The blob is never used unverified, and there is no option that turns that off: mds.Verify accepts it only if the JWS is RS256 or ES256 with an x5c chain that verifies, at the time asked for, against the pinned GlobalSign Root R46 (the root the FIDO Alliance names; SHA-256 4fa3126d...40c9, checked on every use); the leaf is valid for mds.fidoalliance.org (it is a TLS certificate, so without that any GlobalSign EV site could sign a blob); no certificate of the chain is revoked (each CRL is fetched, its signature and window checked; a certificate without a reachable valid CRL is a refusal, the check fails closed); and nextUpdate has not passed. The download is bounded (64 MiB; the blob is about 11 MB). mds.Client keeps the blob in a directory for as long as nextUpdate allows, verifies it again on every load, and refuses a download whose serial no is lower than the cached one. The parser is fuzzed, and so is the claim that no input verifies against the pinned root.

c := &mds.Client{Dir: cacheDir}
blob, err := c.Load(ctx, false)
e := blob.Lookup(hex.EncodeToString(info.AAGUID[:]))   // nil: not in the list
roots, err := e.RootCertificates()

YubiKey device information (ykman info, read-only)

Key.YubiKeyInfo reads what ykman info shows over the HID transport the library already has, with Yubico's vendor CTAPHID command 0x42 (read config, paged): serial, firmware, form factor, the applications supported and ENABLED over USB and NFC (OTP, U2F, FIDO2, OATH, PIV, OpenPGP, HSMAUTH), the FIPS and Security Key flags, config lock, part number. It is a port of yubikit 5.8.0 management.py and the TLV reader of core/__init__.py. Only the read is implemented: the write command (0x43) is not, so nothing here can change a key's configuration. The command is Yubico's, so call it on a key whose USB vendor id is 0x1050; firmware older than 4.1.0 is refused. ParseYubiKeyPages is the parser alone, fuzzed.

The fido command

cmd/fido (its own module: go install github.com/go-authn/fido/cmd/fido@latest) sets a PIN and enrols fingerprints; macOS and Linux (Windows refuses raw HID to a process that is not elevated).

fido list                                 # every key: id, product, serial, aaguid, PIN?, fingerprints? (no touch)
fido info                                 # one key in detail
fido pin set | change
fido fingerprint add [--name N] | list | rename ID NAME | remove ID
fido name set NAME | show | remove          # a name stored ON the key
fido identify [--refresh]                   # the key's model from the FIDO MDS (read-only)
fido attest [--pin-file F | --pin-from REF] [--save-to FILE]   # a verified attestation of the key (asks for a touch + fingerprint/PIN)
fido attest --verify-file FILE [--refresh]  # re-verify a saved envelope offline, no key
fido mds lookup AAGUID | search WORD [--refresh]   # the verified FIDO MDS3 blob, no key needed
fido yubikey info                           # like `ykman info` (read-only), with a PIV/CCID verdict

fido mds lookup AAGUID prints the model, its certification history and the attestationRootCertificates (subject and SHA-256) from the FIDO Metadata Service; fido mds search WORD lists the models whose name or AAGUID contains WORD. The blob (about 11 MB) is cached in the user cache directory, and is verified on every use against the pinned GlobalSign Root R46: there is no flag that skips the verification. fido identify reads the AAGUID the key reports in getInfo and looks it up; it says each time that this AAGUID is the key's own claim, and that only a verified attestation proves the model.

fido attest is that attestation. It makes a throwaway, non-resident credential for the reserved relying party fido-attest.invalid (nothing is stored on the key; a PIN is read like everywhere else, never from an argument), with user verification required, and prints the format, the authData AAGUID, the flags and, for every certificate of the statement, subject, issuer, serial, validity and whether it carries the id-fido-gen-ce-aaguid extension (1.3.6.1.4.1.45724.1.1.4), its value and whether it equals authData's. It then verifies the statement's signature and the chain to the attestation roots the verified MDS lists for that AAGUID, and exits 1 if either fails. --save-to FILE keeps an envelope (CBOR, mode 0600, never overwriting): one canonical CBOR map {v: 1, rpId, clientDataJSON, clientDataHash, attestationObject}. The envelope carries what the attestation signature covers (authData || clientDataHash), so fido attest --verify-file FILE redoes the whole verification later, offline and without the key: statement signature, certificate rules and the MDS chain (from the cache; --refresh fetches it). A file of another version, with an unknown member, a duplicate key or trailing bytes is refused, and so is a clientDataHash that is not the SHA-256 of clientDataJSON. The file holds the attestation certificate, hence the key's attestation serial number: that identifies the key (or its batch); it is not a secret.

fido yubikey info reads Yubico's device info (firmware, serial, form factor, the applications supported and enabled over USB and NFC, FIPS/Security Key series, lock) and ends with two plain lines, PIV: and CCID:, saying whether the smart-card interface and PIV are present, disabled or enabled. It writes nothing, and refuses a key whose USB vendor id is not Yubico's (0x1050) before sending it anything. A YubiKey Bio, for example, reports FIDO U2F and FIDO2 only: no PIV, no CCID.

fido name set NAME stores a name in the key itself (a credential under name.fido; asks for the PIN, and replaces any earlier name so a key never holds two). fido name show and the NAME column of fido list read it with no touch and no PIN, and --device accepts a name as well as an id (exactly; a name on two keys is refused, naming both). A key that will not answer that silent read (CTAP 2.1 does not make every key do so) is given a LOCAL alias instead, in <user config dir>/fido/names (mode 0600), bound to its serial number or, when it has none, to its USB port; every command says which of the two a key uses ("stored on the key" or "local alias").

With several keys attached, --device ID names the one to act on (IDs come from fido list; they are matched exactly). Without it the person touches the key to use; a command that WRITES never runs on "the first", refuses if two keys were touched together, and always prints which key it is about to change.

Where the PIN comes from

The terminal (echo off), a 0600 file (--pin-file, --new-pin-file), or a secret manager, so no plaintext file has to sit on disk (--pin-from, --new-pin-from; each excludes the -file flag of the same PIN):

fido fingerprint list --pin-from keychain:fido/yubikey-5c          # macOS Keychain
fido fingerprint list --pin-from secretservice:fido/yubikey-5c     # GNOME Keyring, KWallet, KeePassXC (Secret Service Integration)
fido fingerprint list --pin-from 'keepassxc:https://fido.invalid/yubikey-5c'   # KeePassXC (macOS, Linux): the entry's URL field; once: secretsource keepassxc associate
fido fingerprint list --pin-from file:/run/user/1000/pin           # same as --pin-file

KeePassXC has no Secret Service on macOS; keepassxc: talks to its browser-integration socket. Enable Browser Integration in KeePassXC, run secretsource keepassxc associate once and approve it there, then check with secretsource check 'keepassxc:https://fido.invalid/yubikey-5c'; the entry must carry that URL in its URL field (lookups by UUID or path are refused: KeePassXC 2.8.0 crashes on an entry without a URL) (go install github.com/go-authn/secretsource/cmd/secretsource@latest).

The reference holds no secret; there is no scheme that runs a command. See go-authn/secretsource for how to store the item (security add-generic-password -s fido -a yubikey-5c -w, secret-tool store --label PIN service fido account yubikey-5c).

Saving the PIN as it is set

fido pin set and fido pin change can put the new PIN straight into a secret manager, so it never exists as a plaintext file or on the terminal:

fido pin set --save-to 'keepassxc:https://fido.invalid/yubikey-5c' --generate 12
fido pin change --pin-from 'keepassxc:https://fido.invalid/yubikey-5c' \
    --save-to 'keepassxc:https://fido.invalid/yubikey-5c' --generate 12 --replace

--generate N draws N letters and digits (from the key's minimum to 63) and needs --save-to; --replace overwrites an existing entry. The PIN is stored BEFORE the key is touched: a failed store changes nothing. If the key then refuses, pin set says the PIN stays stored for a key that has none, and pin change --replace puts the current PIN back in the entry. Nothing secret is printed.

Every discoverable credential: GetAssertions

Key.GetAssertions(ctx, req, max) sends one getAssertion and then one authenticatorGetNextAssertion (0x08, CTAP 2.1 §6.3) per further credential the authenticator announced (numberOfCredentials). With an empty Allow list, that reaches every discoverable credential of the relying party, newest first. max bounds the count, which is the authenticator's word: a larger announcement is refused before any further command.

§6.3 does not say whether a next assertion carries extension outputs. An hmac-secret output found in one is decrypted with the first request's session; a next assertion without one has a nil HMACSecret, so the caller sees what the authenticator actually does. What a real key does is measured by go-macos/fido's FIDO_REAL=1 test. An authenticator with a display may instead let the person pick one credential, and then announces none (§6.2.2, step 12).

Documentation

Overview

Package fido speaks the FIDO client-to-authenticator protocol to a security key, in pure Go with CGO_ENABLED=0 and on any operating system.

Nothing here is platform-specific. A Transport carries 64-byte reports to and from one authenticator, and where those reports come from -- IOKit on macOS, hidraw on Linux, WebHID in a browser -- is somebody else's problem. See go-macos/fido for the macOS one.

The second factor

An operating system already offers the first factor: Touch ID, a watch, a passcode. Those answer one question -- is the person at this machine the one who unlocked it? A security key answers a different one: is the thing they carry present, right now, and did a human touch it? Multi-factor means asking both, and getting two independent answers.

CTAPHID

A message is cut into 64-byte reports: one INITIALISATION packet carrying the command and the total length, then CONTINUATION packets numbered from zero. A channel id is negotiated first, with CmdInit, and every later message carries it.

Yubico's libfido2 and the CTAP specification were read as documentation for this, and the reading caught two faults that testing against a key would not have: see CmdKeepalive and MaxMessage.

Index

Constants

View Source
const (
	// CmdBioEnrollment is authenticatorBioEnrollment.
	CmdBioEnrollment byte = 0x09
	// CmdBioEnrollmentPreview is the prototype command of CTAP 2.1 PS keys that
	// declare userVerificationMgmtPreview instead of bioEnroll.
	CmdBioEnrollmentPreview byte = 0x40
)

authenticatorBioEnrollment (CTAP 2.1 6.7), fingerprint modality.

Which command byte depends on what getInfo declares (6.4): the option "bioEnroll" present (true: enrollments exist, false: none yet) means the final command 0x09 and a token with the be permission; "bioEnroll" absent but "userVerificationMgmtPreview" present means the prototype command, 0x40 in libfido2 (src/fido/param.h, CTAP_CBOR_BIO_ENROLL_PRE; the CTAP 2.1 PS text printed 0x41 for both prototype commands), and a token from the CTAP 2.0 getPinToken, which has no permissions.

View Source
const (
	// CmdCredentialManagement is authenticatorCredentialManagement.
	CmdCredentialManagement byte = 0x0A
	// CmdCredentialManagementPreview is the prototype command.
	CmdCredentialManagementPreview byte = 0x41
)

authenticatorCredentialManagement (CTAP 2.1 6.8), the part this package needs: list the credentials of one relying party and delete one.

Which command byte depends on getInfo (6.4, 6.13): "credMgmt" present means the final command 0x0A and a token with the cm permission; otherwise "credentialMgmtPreview" present means the prototype, 0x41, which needs no permissions and so takes a plain getPinToken token.

View Source
const (
	CmdMakeCredential byte = 0x01
	CmdGetAssertion   byte = 0x02
	// CmdGetNextAssertion is authenticatorGetNextAssertion (CTAP 2.1 §6.3).
	CmdGetNextAssertion byte = 0x08
)

The CTAP2 commands that make and use credentials.

View Source
const (
	// CmdPing echoes its payload back. It is the honest way to check that a
	// channel works, because a key that answers a ping with the same bytes has
	// received, framed and returned them.
	CmdPing byte = 0x01
	// CmdInit negotiates a channel. Sent on [BroadcastChannel] with an
	// eight-byte nonce, it comes back with that nonce, a fresh channel id, and
	// what the key can do.
	CmdInit byte = 0x06
	// CmdWink makes the key blink or flash. It changes nothing and stores
	// nothing, and it is the cheapest way to ask a person WHICH of the keys in
	// front of them is this one.
	CmdWink byte = 0x08
	// CmdCBOR carries a CTAP2 message. Not used yet; named so the capability
	// below is not a number without a meaning.
	CmdCBOR byte = 0x10
	// CmdMsg carries an older CTAP1/U2F message.
	CmdMsg byte = 0x03
	// CmdLock reserves the key for one channel. Optional, and not used here.
	CmdLock byte = 0x04
	// CmdCancel abandons a request the key is still working on -- which for
	// anything needing a touch means the person never touched it.
	CmdCancel byte = 0x11
	// CmdKeepalive is what a key sends WHILE it works, and it is not an answer.
	// A key waiting for a finger sends one about every hundred milliseconds for
	// as long as the person takes, and a reader that returns the first complete
	// message it sees returns THAT instead of the reply. libfido2 skips them in
	// its receive loop and keeps waiting; so does this.
	CmdKeepalive byte = 0x3B
	// CmdError is what a key answers with when it will not do something.
	CmdError byte = 0x3F
)

The CTAPHID commands used here. The command byte travels with its high bit set, which is what distinguishes an initialisation packet from a continuation one -- a continuation packet carries a sequence number in the same position, and sequence numbers never reach 0x80.

View Source
const (
	// DefaultMinPINLength is the minimum when getInfo has no minPINLength.
	DefaultMinPINLength = 4
	// MaxPINBytes is the longest PIN, in UTF-8 bytes.
	MaxPINBytes = 63
)

The PIN limits of CTAP 2.1 6.5.5.5: a PIN is at least minPINLength code points (4 when the authenticator does not say) and its UTF-8 form at most 63 bytes, so that the 64-byte block it is padded into always keeps one zero byte.

View Source
const AlgES256 int64 = -7

AlgES256 is the COSE identifier for ECDSA over P-256 with SHA-256. It is the one algorithm every FIDO authenticator supports, which is why it is the default here: asking for something else and being refused is a worse first experience than asking for the thing that always works.

View Source
const BroadcastChannel uint32 = 0xFFFFFFFF

BroadcastChannel is the channel a key is addressed on before it has given one out. Only CmdInit may be sent there.

View Source
const CmdClientPIN byte = 0x06

CmdClientPIN is authenticatorClientPIN.

View Source
const (
	// CmdGetInfo asks the authenticator to describe itself. It takes no
	// parameters at all -- the message is the command byte and nothing else --
	// which is why it is the first CTAP2 command worth having: it needs a CBOR
	// DECODER and no encoder.
	CmdGetInfo byte = 0x04
)

The CTAP2 commands. Only the ones this package sends are named; a constant for something unsent would be a claim about behaviour nothing here has.

View Source
const CmdSelection byte = 0x0B

CmdSelection is authenticatorSelection (CTAP 2.1 6.9): the authenticator asks for user presence and answers CTAP2_OK when it gets it. It exists for exactly this, a platform choosing among several authenticators.

View Source
const CmdYubiKeyReadConfig byte = 0x42

CmdYubiKeyReadConfig is Yubico's vendor CTAPHID command that returns one page of the management "device info" (CTAP_READ_CONFIG = CTAP_VENDOR_FIRST + 2 in yubikit/management.py l.567-570). The CTAPHID vendor range is 0x40-0x7F.

Only a YubiKey knows it: another vendor may give the same number a meaning of its own, so Key.YubiKeyInfo must be called on a key known to be Yubico's (USB vendor id 0x1050), never to probe an unknown one.

View Source
const MaxContinuations = 128

MaxContinuations is how many continuation packets one message may use. The sequence number shares its byte with the command, and a command is marked by its high bit, so a sequence number may never reach 0x80. libfido2 checks the same thing when it sends.

View Source
const MaxMessage = initPayload + MaxContinuations*contPayload

MaxMessage is the largest message CTAPHID can actually carry.

The two length bytes would allow 65535, and an earlier version of this file used that -- with a comment claiming the framing reached it. It does not: 57 bytes in the initialisation packet plus 128 continuations of 59 is 7609, and a longer message would need sequence numbers past 0x7F, which the key would read as initialisation packets. The arithmetic was wrong and the comment asserted it anyway.

View Source
const MaxNameBytes = 64

MaxNameBytes is the longest name, in UTF-8 bytes: the 64 bytes CTAP allows a user handle.

View Source
const NameRP = "name.fido"

NameRP is the reserved relying party id of the name credential. CTAP treats a relying party id as an opaque string; WebAuthn's origin rules (not opened here) mean no web page can ask for "name.fido".

View Source
const ReportSize = 64

ReportSize is the size of every CTAPHID report, in bytes. The specification fixes it at 64 and every authenticator observed publishes exactly that in both directions.

Variables

View Source
var (
	// ErrNoKey means no FIDO authenticator is attached.
	ErrNoKey = errors.New("fido: no security key is attached")
	// ErrTooLong means the message will not fit in a CTAPHID transfer.
	ErrTooLong = errors.New("fido: the message is longer than CTAPHID can carry")
	// ErrShortPacket means a report arrived that is not a whole CTAPHID packet.
	ErrShortPacket = errors.New("fido: a report was shorter than a CTAPHID packet")
	// ErrWrongChannel means a report arrived for a different channel, which is
	// what happens when two programs talk to one key at once.
	ErrWrongChannel = errors.New("fido: the report belongs to another channel")
	// ErrOutOfOrder means continuation packets did not arrive in sequence.
	ErrOutOfOrder = errors.New("fido: a continuation packet arrived out of order")
	// ErrTruncated means the key stopped sending before the length it promised.
	ErrTruncated = errors.New("fido: the key sent less than it said it would")
)

Errors this package returns for what a caller can act on.

View Source
var (
	// ErrNoName means the key has no name credential.
	ErrNoName = errors.New("fido: this key has no name")
	// ErrNameRefused means the key would not answer the silent read (no touch,
	// no PIN). It wraps the key's own status.
	ErrNameRefused = errors.New("fido: this key does not answer a read of its name without verification")
	// ErrNameAmbiguous means the key holds more than one name credential.
	ErrNameAmbiguous = errors.New("fido: this key holds more than one name")
)
View Source
var ErrHMACSecretNotVerified = errors.New("fido: the authenticator did not verify the user, so its hmac-secret output is the unverified one")

ErrHMACSecretNotVerified is returned when HMACSecret.RequireUV was set and the authenticator did not verify the user.

View Source
var ErrNoCandidates = errors.New("fido: no security key to choose from")

ErrNoCandidates is returned by Select when it is given nothing to choose from.

View Source
var ErrYubiKeyData = errors.New("fido: the YubiKey's device information is malformed")

ErrYubiKeyData means a YubiKey's device information is not well formed.

Functions

func CheckName added in v0.12.0

func CheckName(name string) error

CheckName refuses a name that cannot be stored: empty, not UTF-8, longer than MaxNameBytes, or containing a control or format character (a name is shown in terminals).

func CheckNewPIN added in v0.10.0

func CheckNewPIN(pin string, minLen uint) error

CheckNewPIN applies the platform's half of the PIN policy before the authenticator is asked, so a PIN that cannot be accepted costs no exchange and no retry. minLen is Info.MinPINLength; zero means DefaultMinPINLength. The authenticator may still refuse a PIN on a policy of its own (CTAP2_ERR_PIN_POLICY_VIOLATION).

CTAP 2.1 asks for the PIN in Unicode Normalization Form C. This package does not normalise (the standard library has no NFC): a PIN with composed and decomposed spellings must be given in NFC by the caller.

func CheckNewPINBytes added in v0.15.0

func CheckNewPINBytes(pin []byte, minLen uint) error

CheckNewPINBytes is CheckNewPIN for a PIN held as a slice. It only reads pin and keeps nothing of it.

func DecodeName added in v0.12.0

func DecodeName(id []byte) (string, error)

DecodeName reads a name from a user handle a key returned. What a key holds is input from a device the program does not control, so it is checked as a name is on the way in.

func Split

func Split(channel uint32, cmd byte, data []byte) ([][]byte, error)

Split cuts a message into the reports that carry it: one initialisation packet then as many continuation packets as are needed, each exactly ReportSize bytes and zero-padded.

Every packet is padded to the full report size deliberately. A short output report is legal HID and some keys accept it, but the specification says the transfer is report-sized and a key that reads past the bytes given would read whatever the previous transfer left there.

Types

type Assertion added in v0.3.0

type Assertion struct {
	// Credential says which credential answered. An authenticator may leave it
	// out when the request named exactly one.
	Credential Credential
	AuthData   []byte
	Parsed     AuthData
	// Signature covers the authenticator data followed by the client data
	// hash, in that order. Verifying it is the caller's, with the public key
	// from the registration.
	Signature []byte
	// UserID is the user handle, present for a discoverable credential.
	UserID []byte
	// Available is how many credentials could have answered, when the
	// authenticator said. More than one means the caller may ask for the next.
	Available uint
	// Extensions are the extension outputs the authenticator reported.
	Extensions ExtensionOutputs
	// HMACSecret is the decrypted hmac-secret output, when it was asked for.
	HMACSecret *HMACSecretOutput
}

Assertion is what an authenticator answers with.

type Attestation added in v0.3.0

type Attestation struct {
	// Format names the attestation statement's shape: "packed", "none", and
	// others.
	Format string
	// AuthData is the raw authenticator data, kept because a signature is over
	// these bytes and re-encoding [Parsed] would not reproduce them.
	AuthData []byte
	Parsed   AuthData
	// Statement is the attestation statement, left as CBOR: verifying it means
	// choosing a certificate library, and that choice is not this package's.
	Statement cbor.RawMessage
	// Extensions are the extension outputs the authenticator reported.
	Extensions ExtensionOutputs
}

Attestation is what a registration returns.

type AuthData added in v0.3.0

type AuthData struct {
	// RPIDHash is SHA-256 of the relying party id. It is a hash, not a name:
	// the authenticator never learns the name.
	RPIDHash [32]byte
	Flags    Flags
	// SignCount rises with use on authenticators that keep one. A count that
	// goes BACKWARDS is the classic sign of a cloned credential -- and a count
	// that stays at zero means this authenticator does not keep one, which is
	// allowed and is not evidence of anything.
	SignCount uint32

	// The rest is present only when [FlagAT] is set, which is a registration.
	AAGUID       [16]byte
	CredentialID []byte
	// COSEKey is the credential's public key, as COSE_Key CBOR. It is kept
	// encoded because that is what arrived; [AuthData.PublicKey] turns it into
	// an ECDSA key when it is one.
	COSEKey cbor.RawMessage

	// Extensions is present only when [FlagED] is set.
	Extensions cbor.RawMessage
}

AuthData is the authenticator data an authenticator signs over.

It is the part of a FIDO answer that says what happened: which relying party it was for, whether a person was present and whether they were verified. The signature covers it, so reading it is how a caller learns anything at all beyond "the key answered".

func ParseAuthData added in v0.3.0

func ParseAuthData(b []byte) (AuthData, error)

ParseAuthData reads authenticator data.

The layout is fixed-width up to the flag byte and then conditional on it, which is where the mistakes live: a parser that assumes attested data is present reads a credential id out of an assertion's extensions, and one that assumes it is absent silently ignores a registration. Both flags are obeyed here, and a length that does not add up is an error rather than a slice.

func (AuthData) ExtensionOutputs added in v0.7.0

func (a AuthData) ExtensionOutputs() (ExtensionOutputs, error)

ExtensionOutputs decodes the extension data of the authenticator data. With no extension data it returns the zero value.

func (AuthData) PublicKey added in v0.3.0

func (a AuthData) PublicKey() (*ecdsa.PublicKey, error)

PublicKey turns the credential's COSE key into an ECDSA public key.

Only P-256 with ES256 is decoded, which is not a limitation in practice: it is the one algorithm every FIDO authenticator supports and the one this package asks for by default. Anything else is refused by name rather than half-decoded, because a key of the wrong curve that verified nothing would be worse than no key at all.

This is a CONVERSION and not a verification. Checking a signature needs a decision about what counts as valid -- which algorithms, what to do with a sign counter that went backwards -- and that decision belongs to whoever is protecting something. crypto/ecdsa is the standard library, so returning one of its keys imposes no choice on anybody.

The signature an assertion carries is over the authenticator data followed by the client data hash, in that order, hashed with SHA-256:

signed := append(append([]byte{}, a.AuthData...), clientDataHash...)
digest := sha256.Sum256(signed)
ok := ecdsa.VerifyASN1(pub, digest[:], a.Signature)

func (AuthData) String added in v0.3.0

func (a AuthData) String() string

String renders the authenticator data the way a log line reads.

type Bio added in v0.10.0

type Bio struct {
	// contains filtered or unexported fields
}

Bio drives the fingerprint enrollment of one key.

func (*Bio) Enroll added in v0.10.0

func (b *Bio) Enroll(ctx context.Context, tok Token, timeout time.Duration, progress func(EnrollStep)) (id []byte, err error)

Enroll enrols a fingerprint: enrollBegin, then enrollCaptureNextSample until the key wants no more, calling progress after each sample (nil is allowed). It returns the new template id. If the context ends or a call fails midway, the enrollment is cancelled on the key, so none is left half-made.

A sample that is not good (a finger too fast, off-centre, or not lifted) does not count: Remaining stays and the loop asks again. At most 256 rounds are made, whatever the key says.

func (*Bio) EnrollBegin added in v0.10.0

func (b *Bio) EnrollBegin(ctx context.Context, tok Token, timeout time.Duration) (EnrollStep, error)

EnrollBegin starts an enrollment and takes its first sample: enrollBegin (6.7.4). It cancels any enrollment the key had under way. timeout is the key's per-sample wait; zero leaves it to the key.

func (*Bio) EnrollCancel added in v0.10.0

func (b *Bio) EnrollCancel(ctx context.Context) error

EnrollCancel abandons the enrollment under way (6.7.5). It takes no token.

func (*Bio) EnrollNext added in v0.10.0

func (b *Bio) EnrollNext(ctx context.Context, tok Token, id []byte, timeout time.Duration) (EnrollStep, error)

EnrollNext takes the next sample of the enrollment id: enrollCaptureNextSample.

func (*Bio) Enumerate added in v0.10.0

func (b *Bio) Enumerate(ctx context.Context, tok Token) ([]Enrollment, error)

Enumerate lists the enrolled fingerprints (6.7.6). A key with none answers CTAP2_ERR_INVALID_OPTION, which is an empty list here, not an error.

func (*Bio) Permissions added in v0.10.0

func (b *Bio) Permissions() Permissions

Permissions is what to ask Key.PINToken for: the be permission on a key with the final command, and zero (the CTAP 2.0 token, which has none) on a prototype one.

func (*Bio) Remove added in v0.10.0

func (b *Bio) Remove(ctx context.Context, tok Token, id []byte) error

Remove deletes an enrollment (6.7.8).

func (*Bio) Rename added in v0.10.0

func (b *Bio) Rename(ctx context.Context, tok Token, id []byte, name string) error

Rename gives an enrollment a friendly name (6.7.7). A name longer than SensorInfo.MaxNameLength is refused by the key (CTAP1_ERR_INVALID_LENGTH).

func (*Bio) SensorInfo added in v0.10.0

func (b *Bio) SensorInfo(ctx context.Context) (SensorInfo, error)

SensorInfo asks about the sensor. It needs no token.

type BioMode added in v0.10.0

type BioMode int

BioMode says which bio enrollment command a key speaks.

const (
	// BioUnsupported: getInfo mentions neither option.
	BioUnsupported BioMode = iota
	// BioFinal is authenticatorBioEnrollment 0x09 ("bioEnroll" declared).
	BioFinal
	// BioPreview is the prototype command ("userVerificationMgmtPreview").
	BioPreview
)

The modes.

type Candidate added in v0.11.0

type Candidate struct {
	// Label is how the key is named to a person, in messages.
	Label string
	// Open opens the key and does the CTAPHID handshake (see [Open]).
	Open func(context.Context) (*Key, error)
}

Candidate is a key that may be chosen: how to open it and what to call it.

Open is a function rather than a device so that this package stays free of every operating system: go-macos/fido and go-gnulinux/fido list their keys and a caller turns each one into a Candidate with a closure over its OpenDevice.

type CandidateError added in v0.11.0

type CandidateError struct {
	// Index is the position in the list given to Select.
	Index int
	Label string
	Err   error
}

CandidateError is one key's failure during Select.

func (CandidateError) Error added in v0.11.0

func (e CandidateError) Error() string

func (CandidateError) Unwrap added in v0.11.0

func (e CandidateError) Unwrap() error

type Capabilities

type Capabilities byte

Capabilities is what a key said it can do, in the CTAPHID_INIT reply.

const (
	// CapWink means [CmdWink] does something visible.
	CapWink Capabilities = 0x01
	// CapCBOR means the key speaks CTAP2.
	CapCBOR Capabilities = 0x04
	// CapNoMsg means the key does NOT speak the older CTAP1/U2F messages. It is
	// spelled as an absence in the specification, and kept that way here rather
	// than inverted, so a reader comparing this with the specification does not
	// have to hold two conventions at once.
	CapNoMsg Capabilities = 0x08
)

The capability bits.

func (Capabilities) Has

func (c Capabilities) Has(want Capabilities) bool

Has reports whether every bit in c is set.

func (Capabilities) String

func (c Capabilities) String() string

String lists what the key can do, in the order the bits are defined.

type CredMgmt added in v0.12.0

type CredMgmt struct {
	// contains filtered or unexported fields
}

CredMgmt manages the credentials of one key.

func (*CredMgmt) Credentials added in v0.12.0

func (c *CredMgmt) Credentials(ctx context.Context, tok Token, rpID string) ([]ManagedCredential, error)

Credentials lists the credentials of rpID: enumerateCredentialsBegin then enumerateCredentialsGetNextCredential for the rest (6.8). A relying party with none is an empty list. At most 256 are read, whatever the key claims.

func (*CredMgmt) Delete added in v0.12.0

func (c *CredMgmt) Delete(ctx context.Context, tok Token, credentialID []byte) error

Delete removes one credential by id: deleteCredential (6.8).

func (*CredMgmt) Permissions added in v0.12.0

func (c *CredMgmt) Permissions() Permissions

Permissions is what to ask Key.PINToken for: cm on a key with the final command, zero (the CTAP 2.0 token) on a prototype one. The token must carry NO relying party id for the commands here (6.8).

type CredMgmtMode added in v0.12.0

type CredMgmtMode int

CredMgmtMode says which credential management command a key speaks.

const (
	CredMgmtUnsupported CredMgmtMode = iota
	CredMgmtFinal
	CredMgmtPreview
)

The modes.

type CredProtect added in v0.7.0

type CredProtect uint

CredProtect is a credential protection policy (CTAP 2.1, 12.1): when an authenticator may reveal that a credential exists, and use it.

const (
	// CredProtectOptional (1, userVerificationOptional): the credential may be
	// used with or without user verification. It is the default of an
	// authenticator that does not know the extension.
	CredProtectOptional CredProtect = 1
	// CredProtectOptionalWithList (2, userVerificationOptionalWithCredentialIDList):
	// without verification the credential answers only to a request that NAMES
	// it, and is invisible to discovery.
	CredProtectOptionalWithList CredProtect = 2
	// CredProtectRequired (3, userVerificationRequired): the credential answers
	// to nothing without user verification, and an unverified request is told
	// there are NO credentials, whether or not the one it named exists. A caller
	// must therefore obtain verification BEFORE probing for a credential: a
	// probe that comes first gets "none" from the right key.
	CredProtectRequired CredProtect = 3
)

The policies, with the specification's numbers.

type Credential added in v0.3.0

type Credential struct {
	// Type is "public-key" for everything current.
	Type string
	// ID is the credential id the authenticator gave out.
	ID []byte
	// Transports, when known, say how the credential can be reached.
	Transports []string
}

Credential names one credential an authenticator holds.

type EnrollStep added in v0.10.0

type EnrollStep struct {
	// TemplateID names the enrollment under way; only enrollBegin returns it.
	TemplateID []byte
	// Status is how the last sample went.
	Status SampleStatus
	// Remaining is how many more good samples the key wants.
	Remaining int
}

EnrollStep is what the key reports after a sample.

type Enrollment added in v0.10.0

type Enrollment struct {
	ID   []byte
	Name string
}

Enrollment is one enrolled fingerprint.

type ExtensionOutputs added in v0.7.0

type ExtensionOutputs struct {
	// HMACSecret is true when a registration says the credential has the
	// hmac-secret extension. It is not the secret: that comes from an assertion.
	HMACSecret bool
	// CredProtect is the policy the authenticator applied, zero when it said
	// nothing. An authenticator that ignored a requested policy reports the
	// default here, which is how a caller finds out.
	CredProtect CredProtect
	// Raw holds every output, by identifier, undecoded.
	Raw map[string]cbor.RawMessage
	// contains filtered or unexported fields
}

ExtensionOutputs are the extension outputs an authenticator put in its authenticator data.

type Extensions added in v0.7.0

type Extensions struct {
	// HMACSecret asks the authenticator to create the credential with the
	// hmac-secret extension (CTAP 2.1, 12.5), so that [GetAssertionRequest.HMACSecret]
	// can derive secrets from it later.
	HMACSecret bool
	// CredProtect, when not zero, sets the credential protection policy.
	CredProtect CredProtect
	// Other carries extensions this package has no field for, by identifier. The
	// values are encoded as given; naming one of the fields above here as well is
	// an error rather than a silent choice.
	Other map[string]any
}

Extensions are the extension inputs of a registration (CTAP 2.1, 6.1.2, parameter 0x06). Which of them a caller asks for, and with what policy, is the caller's decision; this package encodes them and reads the outputs back.

type Flags added in v0.3.0

type Flags byte

Flags are the authenticator data's flag byte: what the authenticator did before it signed.

const (
	// FlagUP means a person was PRESENT: something touched the key. It says
	// nothing about who.
	FlagUP Flags = 1 << 0
	// FlagUV means the person was VERIFIED -- a PIN, a fingerprint on the key
	// itself. This is the bit that makes an assertion worth more than
	// possession.
	FlagUV Flags = 1 << 2
	// FlagBE means the credential may be backed up, and FlagBS that it
	// currently is. A backed-up credential is not confined to this one device,
	// which matters to anyone counting it as "something you have".
	FlagBE Flags = 1 << 3
	FlagBS Flags = 1 << 4
	// FlagAT means attested credential data follows, which a registration has
	// and an assertion does not.
	FlagAT Flags = 1 << 6
	// FlagED means extension data follows.
	FlagED Flags = 1 << 7
)

The flag bits, as the specification numbers them.

func (Flags) Has added in v0.3.0

func (f Flags) Has(want Flags) bool

Has reports whether every bit in want is set.

func (Flags) String added in v0.3.0

func (f Flags) String() string

String lists the flags that are set, in bit order.

type GetAssertionRequest added in v0.3.0

type GetAssertionRequest struct {
	RPID           string
	ClientDataHash []byte
	// Allow narrows the request to particular credentials. Leaving it empty
	// asks the authenticator to use a DISCOVERABLE credential, which it only
	// has if one was registered with the "rk" option.
	Allow   []Credential
	Options map[string]bool
	// Token, when valid, authorises the request. See
	// [MakeCredentialRequest.Token].
	Token Token
	// HMACSecret, when set, asks for the hmac-secret output (CTAP 2.1, 12.5).
	// Obtain the Token FIRST when the credential has credProtect level 3: an
	// unverified probe is answered "no credentials" by the right key.
	HMACSecret *HMACSecret
	// Extensions are further extension inputs, encoded as given. A key
	// "hmac-secret" here is an error: use [GetAssertionRequest.HMACSecret].
	Extensions map[string]any
}

GetAssertionRequest asks an authenticator to prove it holds a credential.

type HMACSecret added in v0.7.0

type HMACSecret struct {
	// Protocol is the PIN/UV auth protocol the salts travel under. Zero means the
	// request's token protocol when it has a token, else the highest one the
	// authenticator lists.
	Protocol PINProtocol
	// Salt1 is required, Salt2 optional; each is exactly 32 bytes.
	Salt1, Salt2 []byte
	// RequireUV makes the call fail, and return no secret, when the
	// authenticator did not report user verification.
	//
	// An authenticator derives a DIFFERENT secret for a verified request than for
	// an unverified one (CTAP 2.1, 12.5: CredRandomWithUV and
	// CredRandomWithoutUV), and nothing in the output says which. A caller that
	// derives a key from it and forgets to check [AuthData.Flags] gets a wrong
	// key without any error, so a caller that needs the verified secret should
	// set this.
	RequireUV bool
}

HMACSecret is the hmac-secret input of an assertion (CTAP 2.1, 12.5): one or two salts the authenticator turns into secrets bound to the credential.

type HMACSecretOutput added in v0.7.0

type HMACSecretOutput struct {
	First  []byte
	Second []byte // nil when no second salt was sent
}

HMACSecretOutput holds the secrets, HMAC-SHA-256(CredRandom, salt), 32 bytes each.

type Identity added in v0.11.0

type Identity struct {
	// Name is what the transport calls the key.
	Name string
	// AAGUID identifies the MODEL, not the individual key.
	AAGUID   [16]byte
	Versions []string
	// PINSet is true when a PIN is set; PINCapable when the key has one to set.
	PINSet, PINCapable bool
	// ForcePINChange is true when the PIN must be changed before use.
	ForcePINChange bool
	// FingerprintCapable is true for a key that declares bio enrollment;
	// FingerprintsEnrolled is true when at least one fingerprint is enrolled
	// (the bioEnroll option's value, CTAP 2.1 6.4).
	FingerprintCapable, FingerprintsEnrolled bool
}

Identity is what a key says about itself without being touched, to tell several apart on a screen.

func (Identity) String added in v0.11.0

func (i Identity) String() string

String renders the identity on one line.

type Info added in v0.2.0

type Info struct {
	// Versions are the protocols it speaks, such as "U2F_V2", "FIDO_2_0" and
	// "FIDO_2_1".
	Versions []string
	// Extensions it supports, such as "hmac-secret".
	Extensions []string
	// AAGUID identifies the MODEL of authenticator, not the individual one.
	AAGUID [16]byte
	// Options are the capabilities it declares, such as "rk" (it can store
	// credentials), "up" (it can test for a person's presence), "uv" (it can
	// verify who they are) and "clientPin".
	Options map[string]bool
	// MaxMsgSize is the largest message it will accept, or zero when it did
	// not say.
	MaxMsgSize uint
	// PINProtocols are the PIN protocol versions it supports.
	PINProtocols []uint
	// Transports it can be reached over, such as "usb" or "nfc".
	Transports []string
	// ForcePINChange is true when the PIN must be changed before it is used
	// again (key 0x0C).
	ForcePINChange bool
	// MinPINLength is the fewest code points a PIN may have (key 0x0D), or zero
	// when the authenticator did not say, which means 4.
	MinPINLength uint
}

Info is what an authenticator says about itself, from authenticatorGetInfo.

Only the fields with a caller are decoded. The rest of the reply is left alone rather than half-read: a struct field that is always the zero value because nothing fills it is worse than no field, since it reads as "this authenticator does not have one".

func (Info) BioMode added in v0.10.0

func (i Info) BioMode() BioMode

BioMode reads the options. The options are three-valued (6.4): false means "supported, nothing enrolled", so presence, not truth, decides.

func (Info) CredMgmtMode added in v0.12.0

func (i Info) CredMgmtMode() CredMgmtMode

CredMgmtMode reads the options by presence: a false "credMgmt" is "supported, nothing to manage", still the final command.

func (Info) Has added in v0.2.0

func (i Info) Has(option string) bool

Has reports whether the authenticator declares an option AND says it is true. An option a key does not mention is not the same as one it sets to false -- the first means "not applicable", the second "supported but off" -- and both answer no here, which is what a caller deciding whether to try something needs.

func (Info) String added in v0.2.0

func (i Info) String() string

String renders the authenticator the way a listing reads.

type InitReply

type InitReply struct {
	// Nonce is the nonce sent, echoed back. A reply whose nonce does not match
	// belongs to somebody else's INIT, which happens when two programs
	// initialise one key at the same time.
	Nonce [8]byte
	// Channel is the channel id to use from now on.
	Channel uint32
	Version Version
	Caps    Capabilities
}

InitReply is what CTAPHID_INIT answers.

func ParseInit

func ParseInit(data []byte) (InitReply, error)

ParseInit reads the reply to CmdInit.

It does NOT check the nonce: whether a mismatched nonce is somebody else's reply to ignore or a fault to report is the caller's decision, and this returns what arrived.

type Key

type Key struct {
	// contains filtered or unexported fields
}

Key is an authenticator with a negotiated channel.

func Open

func Open(ctx context.Context, t Transport) (*Key, error)

Open negotiates a channel on t and returns the key behind it.

The handshake is not optional and is done here rather than left to the caller: every later message carries the channel id, so a Key without one could not be used for anything, and returning one would be handing back a half-built object to be misused.

The Key takes ownership of t: Key.Close closes it, and so does a failed Open, so a caller never has to unwind a half-open device.

func (*Key) Bio added in v0.10.0

func (k *Key) Bio(info Info) (*Bio, error)

Bio returns the enrollment interface the key declares in info, or an error when it declares none.

func (*Key) CBOR added in v0.2.0

func (k *Key) CBOR(ctx context.Context, cmd byte, params []byte) ([]byte, error)

CBOR sends one CTAP2 command and returns the reply's body, with the status byte already checked.

params is the command's CBOR-encoded parameters, or nil for a command that takes none. The command byte is prepended here, because the CTAPHID payload of a CBOR message is the command followed by the parameters and getting that join wrong is the sort of thing each caller should not repeat.

func (*Key) Cancel added in v0.11.0

func (k *Key) Cancel() error

Cancel sends CTAPHID_CANCEL (CTAP 2.1 11.2.9.1.6): the key abandons whatever it is waiting for, answering the pending request with CTAP2_ERR_KEEPALIVE_CANCEL. It sends only; the answer, if anyone waits for one, arrives through the request that was pending.

func (*Key) Capabilities

func (k *Key) Capabilities() Capabilities

Capabilities is what the key said it can do.

func (*Key) ChangePIN deprecated added in v0.10.0

func (k *Key) ChangePIN(ctx context.Context, proto PINProtocol, curPIN, newPIN string, minLen uint) error

ChangePIN replaces the PIN: changePIN (clientPIN subcommand 0x04, CTAP 2.1 6.5.5.6). pinHashEnc proves the current PIN and newPinEnc carries the new one; pinUvAuthParam is the MAC of newPinEnc followed by pinHashEnc.

A wrong current PIN costs a retry, as in Key.PINToken: read Key.PINRetries first. When Info.ForcePINChange is set the authenticator refuses a new PIN equal to the current one.

Deprecated: a string cannot be wiped; use Key.ChangePINBytes. This form copies both PINs into slices, calls that one and wipes the copies.

func (*Key) ChangePINBytes added in v0.15.0

func (k *Key) ChangePINBytes(ctx context.Context, proto PINProtocol, curPIN, newPIN []byte, minLen uint) error

ChangePINBytes is Key.ChangePIN for PINs held as slices, so that the caller can wipe them. The requests are the same. Both are only read, and the copies made (the digest of curPIN, the padded block of newPIN) are wiped before the call returns; wiping curPIN and newPIN is the caller's.

func (*Key) Channel

func (k *Key) Channel() uint32

Channel is the negotiated channel id.

func (*Key) Close

func (k *Key) Close() error

Close releases the transport.

func (*Key) CredMgmt added in v0.12.0

func (k *Key) CredMgmt(info Info) (*CredMgmt, error)

CredMgmt returns the interface the key declares in info, or an error when it declares none.

func (*Key) GetAssertion added in v0.3.0

func (k *Key) GetAssertion(ctx context.Context, r GetAssertionRequest) (*Assertion, error)

GetAssertion asks the authenticator to sign, proving it holds the credential.

func (*Key) GetAssertions added in v0.8.0

func (k *Key) GetAssertions(ctx context.Context, r GetAssertionRequest, max int) ([]*Assertion, error)

GetAssertions asks for an assertion and then for every further one the authenticator announced (numberOfCredentials, CTAP 2.1 §6.2), with authenticatorGetNextAssertion (0x08, §6.3). This is how a request with an empty Allow list reaches every discoverable credential of the relying party, newest first, for ONE gesture: §6.3 collects no user presence of its own. The authenticator keeps the list for 30 seconds between commands.

max bounds the answer: an authenticator announcing more than max credentials is refused before any further command, because the count is the authenticator's word. An authenticator with a display may instead let the person pick one, and then announces none (§6.2.2, step 12).

§6.3 does not say whether a next assertion carries extension outputs. An hmac-secret output found in one is decrypted with the FIRST request's session, which is the only one there is; a next assertion WITHOUT one has a nil HMACSecret, not an error, so the caller sees what the authenticator actually does.

func (*Key) GetInfo added in v0.2.0

func (k *Key) GetInfo(ctx context.Context) (Info, error)

GetInfo asks the authenticator to describe itself.

A key that does not declare CapCBOR is not asked: it would answer CTAPHID_ERROR, and the caller would have to tell that refusal from a real fault.

func (*Key) Identity added in v0.11.0

func (k *Key) Identity(ctx context.Context) (Identity, error)

Identity reads the key's description with getInfo. It needs no touch and no PIN.

func (*Key) KeyAgreement added in v0.5.0

func (k *Key) KeyAgreement(ctx context.Context, proto PINProtocol) (*ecdh.PublicKey, error)

KeyAgreement asks the authenticator for a public key to agree with.

It is exported because it is the one half of the PIN dance that needs no PIN: a key with none set still answers, so this is how a caller checks that the whole chain -- CBOR out, COSE in, ECDH -- works before anybody is asked for a secret.

func (*Key) MakeCredential added in v0.3.0

func (k *Key) MakeCredential(ctx context.Context, r MakeCredentialRequest) (*Attestation, error)

MakeCredential registers a new credential.

The authenticator will ask for a person: a touch, and a PIN or a fingerprint when the request or the authenticator demands verification. It sends CTAPHID_KEEPALIVE the whole time it waits, which the transport skips, so the only bound on how long this takes is the context.

func (*Key) Name

func (k *Key) Name() string

Name is what the key calls itself.

func (*Key) NameTokens added in v0.12.0

func (k *Key) NameTokens(ctx context.Context, pin string, proto PINProtocol, info Info) (NameTokens, error)

NameTokens checks the PIN with a token (so a wrong PIN fails before anything is changed, costing the one retry a wrong PIN always costs) and returns what SetName and RemoveName need to ask for tokens as they go. The token used to check is discarded.

func (*Key) PINRetries added in v0.5.0

func (k *Key) PINRetries(ctx context.Context) (Retries, error)

PINRetries asks how many attempts are left.

It needs no PIN and no key agreement, which makes it the one clientPIN subcommand that can be asked of a key nobody has configured -- and the right thing to ask BEFORE prompting somebody, so a prompt is never the last one they get.

func (*Key) PINToken deprecated added in v0.5.0

func (k *Key) PINToken(ctx context.Context, pin string, proto PINProtocol, perms Permissions, rpID string) (Token, error)

PINToken exchanges a PIN for a token.

permissions is what the token will be allowed to authorise, and rpID narrows it further. Both are CTAP 2.1; an authenticator that does not list "pinUvAuthToken" in its options is asked the CTAP 2.0 way instead, where a token authorises everything and neither argument is sent.

The PIN never leaves in the clear: what is sent is the first sixteen bytes of its SHA-256, encrypted under a secret agreed for this exchange alone.

A wrong PIN COSTS a retry, and an authenticator that runs out locks until it is unplugged, then permanently. Key.PINRetries before prompting is not politeness.

Deprecated: a string is immutable, so the caller cannot wipe the PIN it holds and a copy stays in memory until the garbage collector reuses it. Use Key.PINTokenBytes. This form copies pin into a slice, calls that one and wipes the copy; the caller's string stays.

func (*Key) PINTokenBytes added in v0.15.0

func (k *Key) PINTokenBytes(ctx context.Context, pin []byte, proto PINProtocol, perms Permissions, rpID string) (Token, error)

PINTokenBytes is Key.PINToken for a PIN held as a slice, so that the caller can wipe it. It sends exactly the requests PINToken does, in the same order: the same single token is asked for.

pin is only read: its SHA-256 is taken in place, no string is made of it, no copy of it is kept, and the intermediate digest is wiped before the call returns. Wiping pin once the call has returned is the caller's:

defer clear(pin)

func (*Key) Ping

func (k *Key) Ping(ctx context.Context, data []byte) ([]byte, error)

Ping sends data and returns what came back, which a working channel returns unchanged. It is how to check a key is still there without asking it to do anything.

func (*Key) ReadName added in v0.12.0

func (k *Key) ReadName(ctx context.Context) (string, error)

ReadName reads the key's name with NO touch and NO PIN: getAssertion for NameRP with "up" false and no pinUvAuthParam. ErrNoName when there is none, ErrNameRefused when the key will not answer unverified, ErrNameAmbiguous when it holds several.

func (*Key) RemoveName added in v0.12.0

func (k *Key) RemoveName(ctx context.Context, tok NameTokens) error

RemoveName deletes every name credential. A key with none is not an error.

func (*Key) SelectPINProtocol added in v0.7.0

func (k *Key) SelectPINProtocol(ctx context.Context) (PINProtocol, error)

SelectPINProtocol picks the highest PIN/UV auth protocol the authenticator lists that this package implements.

func (*Key) SetName added in v0.12.0

func (k *Key) SetName(ctx context.Context, name string, tok NameTokens) error

SetName gives the key a name, replacing any it had.

The old name credentials are deleted FIRST (credential management, 6.8) and the new one made after, so the key never holds two: if making fails, the key has no name, which is harmless; two names would not be. A key that already has a name and cannot delete credentials is refused before anything changes. The credential is discoverable, credProtect level 1, with the name as user handle, name and display name.

func (*Key) SetPIN deprecated added in v0.10.0

func (k *Key) SetPIN(ctx context.Context, proto PINProtocol, newPIN string, minLen uint) error

SetPIN sets the first PIN of an authenticator that has none: setPIN (clientPIN subcommand 0x03, CTAP 2.1 6.5.5.5). newPinEnc is the PIN padded to 64 bytes and encrypted under the agreed secret, and pinUvAuthParam is the MAC of newPinEnc; there is no pinHashEnc.

minLen is the authenticator's Info.MinPINLength. An authenticator that already has a PIN answers CTAP2_ERR_PIN_AUTH_INVALID: use Key.ChangePIN.

Deprecated: a string cannot be wiped; use Key.SetPINBytes. This form copies newPIN into a slice, calls that one and wipes the copy.

func (*Key) SetPINBytes added in v0.15.0

func (k *Key) SetPINBytes(ctx context.Context, proto PINProtocol, newPIN []byte, minLen uint) error

SetPINBytes is Key.SetPIN for a PIN held as a slice, so that the caller can wipe it. The requests are the same. newPIN is only read: the one copy made (the 64-byte block that is encrypted) is wiped before the call returns, and wiping newPIN itself is the caller's.

func (*Key) String

func (k *Key) String() string

String renders the key the way a log reads.

func (*Key) UVRetries added in v0.7.0

func (k *Key) UVRetries(ctx context.Context) (int, error)

UVRetries asks how many built-in verification attempts remain (subcommand 0x07). It needs no verification.

func (*Key) UVToken added in v0.7.0

func (k *Key) UVToken(ctx context.Context, proto PINProtocol, perms Permissions, rpID string) (Token, error)

UVToken obtains a token by built-in user verification, such as a fingerprint sensor on the key: getPinUvAuthTokenUsingUvWithPermissions (CTAP 2.1, 6.5.5.7.3, subcommand 0x06).

The call blocks while the authenticator waits for the person, sending keepalives that the transport skips; the context is the only bound, so give it one. perms must name at least one permission, and rpID narrows them as in Key.PINToken. An authenticator without built-in UV, or one that does not list "pinUvAuthToken", answers with an error: read Info.Options ("uv", "pinUvAuthToken") first.

A refused verification costs a UV retry; Key.UVRetries says how many are left, and when they run out the authenticator asks for the PIN instead.

func (*Key) Version

func (k *Key) Version() Version

Version is the key's firmware and transport version.

func (*Key) Wink

func (k *Key) Wink(ctx context.Context) error

Wink makes the key blink, when it said it can.

It is the one thing here a PERSON can see, which is what makes it useful for more than diagnostics: asked to prove which key is which, or that the key is the one on the desk rather than one left in a hub across the room, a blink answers.

A key without CapWink is not asked, because a key that does not wink answers CTAPHID_ERROR and the caller would have to tell that refusal from a real fault.

func (*Key) YubiKeyInfo added in v0.16.0

func (k *Key) YubiKeyInfo(ctx context.Context) (YubiKeyInfo, error)

YubiKeyInfo reads the key's device information over CTAPHID, the way `ykman info` does. It only READS: nothing on the key changes.

The key must be a YubiKey (USB vendor id 0x1050): the command is a vendor one, and another vendor's key may give number CmdYubiKeyReadConfig a meaning of its own. A key of another make answers with an error at best.

Firmware before 4.1.0 cannot be asked (require_version, l.644) and is refused.

type MakeCredentialRequest added in v0.3.0

type MakeCredentialRequest struct {
	// ClientDataHash is SHA-256 of the client data the caller built. It is
	// hashed here by nobody: what goes into the client data is the caller's
	// business, and the authenticator signs the hash it is given.
	ClientDataHash []byte
	RP             RelyingParty
	User           User
	// Algorithms are COSE identifiers, most preferred first. Empty asks for
	// [AlgES256].
	Algorithms []int64
	// Exclude lists credentials that must NOT be registered again, which is how
	// a relying party stops one key holding two credentials for one account.
	Exclude []Credential
	// Options are the authenticator options for this request, such as "rk" for
	// a discoverable credential and "uv" to demand verification rather than
	// mere presence.
	Options map[string]bool
	// Token, when valid, authorises the request: it is what turns "somebody
	// touched the key" into "somebody who knows its PIN touched the key", and
	// it is the only way to get the verified bit set on an authenticator whose
	// verification IS a PIN.
	Token Token
	// Extensions are the extension inputs, such as hmac-secret and credProtect.
	Extensions Extensions
}

MakeCredentialRequest is a registration.

type ManagedCredential added in v0.12.0

type ManagedCredential struct {
	// ID is the credential id.
	ID []byte
	// User is the user entity stored with it.
	User User
}

ManagedCredential is a credential as credential management lists it.

type Message

type Message struct {
	Channel uint32
	Cmd     byte
	Data    []byte
}

Message is a CTAPHID message reassembled from its reports.

func (Message) IsError

func (m Message) IsError() bool

IsError reports whether the key refused, rather than answered.

func (Message) String

func (m Message) String() string

String renders the message the way a probe log reads.

type NameTokens added in v0.12.0

type NameTokens struct {
	// contains filtered or unexported fields
}

NameTokens authorises naming a key from one PIN.

⛔ It deliberately holds the PIN, not tokens. An authenticator keeps ONE pinUvAuthToken at a time: obtaining a new one replaces the last, so a token fetched for credential management is dead by the time makeCredential uses it (the authenticator answers CTAP2_ERR_PIN_AUTH_INVALID, 0x33, to the request's pinUvAuthParam even though the PIN was accepted). SetName therefore asks for each token at the moment it is used: credential management first (no relying party bound, 6.8), then makeCredential bound to NameRP. The zero value carries no verification.

type PINProtocol added in v0.5.0

type PINProtocol int

PINProtocol is a PIN/UV auth protocol version.

Two exist and they differ in more than a number: protocol one hashes the ECDH output once and truncates its HMAC to sixteen bytes, protocol two derives two separate keys through HKDF and truncates nothing. An authenticator says which it supports in Info.PINProtocols.

const (
	PINProtocolOne PINProtocol = 1
	PINProtocolTwo PINProtocol = 2
)

The protocols. Higher is better where an authenticator offers both: protocol two separates the encryption key from the authentication key and uses a fresh initialisation vector per message.

func (PINProtocol) String added in v0.5.0

func (p PINProtocol) String() string

String names the protocol.

type Permissions added in v0.5.0

type Permissions uint

Permissions are what a token is allowed to authorise. An authenticator that speaks CTAP 2.1 wants them; one that only speaks 2.0 has no notion of them and is asked the older way.

const (
	PermMakeCredential Permissions = 0x01
	PermGetAssertion   Permissions = 0x02
	// The others CTAP 2.1 (6.5.5.7) defines, named so a caller can ask for them.
	PermCredentialManagement Permissions = 0x04
	PermBioEnrollment        Permissions = 0x08
	PermLargeBlobWrite       Permissions = 0x10
	PermAuthenticatorConfig  Permissions = 0x20
)

The permissions this package can ask for.

type Reassembler

type Reassembler struct {
	// contains filtered or unexported fields
}

Reassembler puts a message back together from the reports a key sends.

It is a type rather than a function because the reports arrive one at a time, from a callback, and the caller needs to know after each one whether the message is complete.

func NewReassembler

func NewReassembler(channel uint32) *Reassembler

NewReassembler collects reports for one channel, refusing any other.

func (*Reassembler) Feed

func (r *Reassembler) Feed(report []byte) (msg Message, done bool, err error)

Feed takes one report. done is true when the message is whole, and the message is then returned and the reassembler is ready for the next one.

A report for another channel is an error rather than something to ignore: two programs talking to one key is a real situation, and silently dropping the other one's traffic would leave a caller waiting for a reply that was already discarded.

type RelyingParty added in v0.3.0

type RelyingParty struct {
	// ID is the domain the credential is scoped to. An authenticator hashes it
	// and never learns it.
	ID string
	// Name is for a person to read on the authenticator's own screen, when it
	// has one.
	Name string
}

RelyingParty is the site or program a credential belongs to.

type Retries added in v0.5.0

type Retries struct {
	// PIN is how many PIN attempts remain before the authenticator locks. It
	// falls on a wrong PIN and is restored by a correct one.
	PIN int
	// PowerCycle is true when the authenticator will accept no more PINs until
	// it is unplugged and plugged back in -- which is not the same as being
	// locked for good, and telling a person the difference matters.
	PowerCycle bool
}

Retries is what an authenticator says about how many attempts are left.

type SampleStatus added in v0.10.0

type SampleStatus uint

SampleStatus is lastEnrollSampleStatus (6.7).

const (
	SampleGood           SampleStatus = 0x00
	SampleTooHigh        SampleStatus = 0x01
	SampleTooLow         SampleStatus = 0x02
	SampleTooLeft        SampleStatus = 0x03
	SampleTooRight       SampleStatus = 0x04
	SampleTooFast        SampleStatus = 0x05
	SampleTooSlow        SampleStatus = 0x06
	SamplePoorQuality    SampleStatus = 0x07
	SampleTooSkewed      SampleStatus = 0x08
	SampleTooShort       SampleStatus = 0x09
	SampleMergeFailure   SampleStatus = 0x0A
	SampleAlreadyExists  SampleStatus = 0x0B
	SampleNoUserActivity SampleStatus = 0x0D
	SampleNoPresence     SampleStatus = 0x0E
)

The sample statuses of 6.7.

func (SampleStatus) String added in v0.10.0

func (s SampleStatus) String() string

String says what the status means to a person.

type SelectError added in v0.11.0

type SelectError struct {
	// Cause is the context's error when the wait ran out or was cancelled, nil
	// when every key failed on its own.
	Cause    error
	Failures []CandidateError
}

SelectError is what Select returns when no key was chosen. Every key's own failure is listed: none is swallowed, so "nothing was touched in time" can be told from "one key would not open".

func (*SelectError) Error added in v0.11.0

func (e *SelectError) Error() string

func (*SelectError) Unwrap added in v0.11.0

func (e *SelectError) Unwrap() []error

Unwrap exposes the cause and every key's error to errors.Is and errors.As.

type Selected added in v0.11.0

type Selected struct {
	// Index is its position in the list given to [Select].
	Index int
	Label string
	// Key is open and ready. The caller closes it; every other key was
	// cancelled and closed.
	Key  *Key
	Info Info
	// AlsoTouched lists the labels of OTHER keys that were touched in the same
	// instant, before they could be cancelled. When it is not empty the choice
	// is ambiguous, and a caller about to change something must not proceed on
	// it.
	AlsoTouched []string
	// Failures are the keys that could not be asked at all (unplugged while
	// waiting, would not open), reported alongside the winner.
	Failures []CandidateError
}

Selected is the key a person chose by touching it.

func Select added in v0.11.0

func Select(ctx context.Context, cands []Candidate) (*Selected, error)

Select asks every candidate for a touch at once and returns the first one touched. The others are sent CTAPHID_CANCEL and closed before Select returns.

Each key is opened and asked, in parallel, to wait for the person: authenticatorSelection (CTAP 2.1 6.9) when it speaks FIDO_2_1, and otherwise, as libfido2's touch.c does for 2.0 keys, a makeCredential whose pinUvAuthParam is empty. A key with neither (a 2.0 key with no PIN set up) cannot be selected without making a credential on it, so it is reported as an error rather than asked.

The wait is bounded by ctx: give it a timeout. A person who explicitly refuses on one key (CTAP2_ERR_OPERATION_DENIED) makes that key an error, as 6.9 says not to ask it again.

type SensorInfo added in v0.10.0

type SensorInfo struct {
	// Touch is true for a touch sensor, false for a swipe sensor.
	Touch bool
	// MaxSamples is the good samples an enrollment needs, at most.
	MaxSamples int
	// MaxNameLength is the longest friendly name in bytes, or zero when unsaid.
	MaxNameLength int
}

SensorInfo is getFingerprintSensorInfo.

type Status added in v0.2.0

type Status byte

Status is the byte a CTAP2 reply begins with. Zero is success.

const (
	StatusOperationDenied   Status = 0x27 // the person refused, or (YubiKey) did not touch in time
	StatusNoCredentials     Status = 0x2e
	StatusInvalidOption     Status = 0x2c // bio enrollment: no such enrollment, or none exist
	StatusUserActionTimeout Status = 0x2f
	StatusPINInvalid        Status = 0x31
	StatusPINBlocked        Status = 0x32
	StatusPINAuthInvalid    Status = 0x33 // the token or pinUvAuthParam was not accepted
	StatusPINAuthBlocked    Status = 0x34
)

Statuses a caller commonly acts on, named so that errors.As against a StatusError can be compared with a name instead of a number (CTAP 2.1 §8.2; the values are those of statusNames below).

const StatusOK Status = 0x00

StatusOK means the authenticator did what was asked.

func (Status) Error added in v0.2.0

func (s Status) Error() bool

Error reports whether the status is a refusal.

func (Status) String added in v0.2.0

func (s Status) String() string

String names the status, or gives its number when it has no name here.

type StatusError added in v0.9.0

type StatusError struct {
	Key    string // the transport's name for the key
	Status Status
}

StatusError is a CTAP2 command the authenticator refused. Use errors.As to read the Status; the message is the one this package always gave.

func (*StatusError) Error added in v0.9.0

func (e *StatusError) Error() string

type Token added in v0.5.0

type Token struct {
	// contains filtered or unexported fields
}

Token is a pinUvAuthToken: permission, for a while, to do the things it was asked for.

It is deliberately not a plain []byte. A token authenticates every later request, so it must be paired with the protocol it was obtained under -- authenticating with the wrong one produces sixteen bytes where thirty-two are expected, which an authenticator reports as a bad PIN rather than as a mismatched protocol.

func (Token) Protocol added in v0.5.0

func (t Token) Protocol() PINProtocol

Protocol is the protocol this token belongs to.

func (Token) Valid added in v0.5.0

func (t Token) Valid() bool

Valid reports whether the token holds anything.

type Transport

type Transport interface {
	// Send writes one report of exactly [ReportSize] bytes.
	Send(report []byte) error
	// Receive returns the next report.
	Receive(ctx context.Context) ([]byte, error)
	// Name is what the device calls itself, for error messages a person reads.
	Name() string
	// Close releases the device.
	Close() error
}

Transport carries CTAPHID reports to and from ONE authenticator.

It is deliberately this small. Everything above it -- framing, the handshake, keepalives, the commands -- is the same on every operating system, so an implementation has only to move 64 bytes at a time and say what the device is called.

Receive must return the NEXT report, blocking until one arrives, the context ends, or the device goes away. It must not drop reports between calls: a key answers a ping in under a millisecond, and an implementation that only listens while asked will miss it.

type User added in v0.3.0

type User struct {
	// ID is an opaque handle chosen by the relying party. It comes BACK in an
	// assertion, so it is how a caller knows who signed in -- and for that
	// reason it must not be an email address or anything else that identifies
	// a person to whoever holds the key.
	ID []byte
	// Name and DisplayName are shown to a person choosing between credentials.
	Name        string
	DisplayName string
}

User is who the credential is for, as the authenticator will remember them.

type Version

type Version struct {
	// CTAPHID is the transport protocol version, 2 on everything current.
	CTAPHID byte
	// Major, Minor and Build are the key's own firmware version.
	Major, Minor, Build byte
}

Version is what a key answered about itself.

func (Version) String

func (v Version) String() string

String renders the version the way the manufacturer writes it.

type YubiKeyCapability added in v0.16.0

type YubiKeyCapability uint32

YubiKeyCapability is a bit set of the applications a YubiKey carries (CAPABILITY in yubikit/management.py l.66-75).

const (
	YubiKeyOTP     YubiKeyCapability = 0x01
	YubiKeyU2F     YubiKeyCapability = 0x02
	YubiKeyOpenPGP YubiKeyCapability = 0x08
	YubiKeyPIV     YubiKeyCapability = 0x10
	YubiKeyOATH    YubiKeyCapability = 0x20
	YubiKeyHSMAuth YubiKeyCapability = 0x100
	YubiKeyFIDO2   YubiKeyCapability = 0x200
)

The application bits.

func (YubiKeyCapability) Applications added in v0.16.0

func (c YubiKeyCapability) Applications() []string

Applications returns the named applications in c in a fixed order, then one "Unknown(0x...)" entry for any bit this version does not name (the CCID bits 0x4 and 0x400 among them: yubikit/management.py l.126-134).

func (YubiKeyCapability) Has added in v0.16.0

Has reports whether every bit in want is set.

func (YubiKeyCapability) String added in v0.16.0

func (c YubiKeyCapability) String() string

String lists the applications, or "none".

func (YubiKeyCapability) UsesCCID added in v0.16.0

func (c YubiKeyCapability) UsesCCID() bool

UsesCCID reports whether c needs the smart-card (CCID) USB interface: the general CCID bit 0x4, management over CCID 0x400, or OATH, PIV, OpenPGP or YubiHSM Auth (CAPABILITY.usb_interfaces, yubikit/management.py l.130-135).

type YubiKeyFormFactor added in v0.16.0

type YubiKeyFormFactor uint8

YubiKeyFormFactor is the physical form of the key (FORM_FACTOR, yubikit/management.py l.150-178).

const (
	FormFactorUnknown      YubiKeyFormFactor = 0x00
	FormFactorUSBAKeychain YubiKeyFormFactor = 0x01
	FormFactorUSBANano     YubiKeyFormFactor = 0x02
	FormFactorUSBCKeychain YubiKeyFormFactor = 0x03
	FormFactorUSBCNano     YubiKeyFormFactor = 0x04
	FormFactorUSBCLightn   YubiKeyFormFactor = 0x05
	FormFactorUSBABio      YubiKeyFormFactor = 0x06
	FormFactorUSBCBio      YubiKeyFormFactor = 0x07
)

The form factors.

func (YubiKeyFormFactor) String added in v0.16.0

func (f YubiKeyFormFactor) String() string

String renders the form factor the way ykman does.

type YubiKeyInfo added in v0.16.0

type YubiKeyInfo struct {
	// Serial is the serial number; 0 when the key reports none (or hides it).
	Serial uint32
	// Version is the firmware version; for a pre-release it is the version the
	// key behaves as (l.391-395).
	Version YubiKeyVersion
	// VersionQualifier is the release channel and iteration.
	VersionQualifier YubiKeyVersionQualifier
	FormFactor       YubiKeyFormFactor
	// FIPS and SKY are the FIPS-series and Security Key-series flags carried in
	// the form-factor byte (0x80 and 0x40, l.347-348).
	FIPS, SKY bool

	// USBSupported and USBEnabled are the applications the key CAN carry over
	// USB, and those switched on now. NFC* are the same over NFC and are valid
	// only when HasNFC. On a YubiKey 4 USBEnabled is not reported (l.364-366)
	// and HasUSBEnabled is false.
	USBSupported, USBEnabled YubiKeyCapability
	HasUSBEnabled            bool
	NFCSupported, NFCEnabled YubiKeyCapability
	HasNFC                   bool

	// Locked is true when the configuration is protected by a lock code.
	Locked bool
	// AutoEjectTimeout, ChallengeResponseTimeout and DeviceFlags are the user
	// settings (l.353-355).
	AutoEjectTimeout         uint64
	ChallengeResponseTimeout uint64
	DeviceFlags              uint64
	NFCRestricted            bool
	// PartNumber is the part number; "" when absent or not UTF-8.
	PartNumber string
	// FIPSCapable and FIPSApproved are the applications that can be, and are,
	// in FIPS-approved mode (l.375-380).
	FIPSCapable, FIPSApproved YubiKeyCapability
	PINComplexity             bool
	// ResetBlocked is the applications whose reset is blocked.
	ResetBlocked YubiKeyCapability
	// FPSVersion and STMVersion are the fingerprint-sensor and STM firmware
	// versions of a Bio; nil when not reported or 0.0.0.
	FPSVersion, STMVersion *YubiKeyVersion
}

YubiKeyInfo is what `ykman info` reads from a key (DeviceInfo, yubikit/management.py l.295-313).

func ParseYubiKeyInfo added in v0.16.0

func ParseYubiKeyInfo(page []byte, defaultVersion YubiKeyVersion) (YubiKeyInfo, error)

ParseYubiKeyInfo parses ONE page of device information, the whole of it for every YubiKey 5.

func ParseYubiKeyPages added in v0.16.0

func ParseYubiKeyPages(pages [][]byte, defaultVersion YubiKeyVersion) (YubiKeyInfo, error)

ParseYubiKeyPages is ManagementSession._do_read_device_info (l.647-661) over pages already read: each is a length byte then TLVs, the length equal to the rest. It joins pages while the more-data flag (tag 0x10) is set, and refuses a last page that still asks for more.

type YubiKeyReleaseType added in v0.16.0

type YubiKeyReleaseType uint8

YubiKeyReleaseType is the release channel of a firmware (RELEASE_TYPE, yubikit/management.py l.197-205).

const (
	ReleaseAlpha YubiKeyReleaseType = 0
	ReleaseBeta  YubiKeyReleaseType = 1
	ReleaseFinal YubiKeyReleaseType = 2
)

The release types.

func (YubiKeyReleaseType) String added in v0.16.0

func (r YubiKeyReleaseType) String() string

String renders "alpha", "beta" or "final".

type YubiKeyVersion added in v0.16.0

type YubiKeyVersion struct{ Major, Minor, Patch uint8 }

YubiKeyVersion is a three-part firmware version.

func (YubiKeyVersion) IsZero added in v0.16.0

func (v YubiKeyVersion) IsZero() bool

IsZero reports 0.0.0, which the firmware uses for "not reported".

func (YubiKeyVersion) String added in v0.16.0

func (v YubiKeyVersion) String() string

String renders "5.8.0".

type YubiKeyVersionQualifier added in v0.16.0

type YubiKeyVersionQualifier struct {
	Version   YubiKeyVersion
	Type      YubiKeyReleaseType
	Iteration uint64
}

YubiKeyVersionQualifier is the fully qualified firmware version.

func (YubiKeyVersionQualifier) String added in v0.16.0

func (q YubiKeyVersionQualifier) String() string

String renders "5.8.0.final.0" (VersionQualifier.__str__, l.287-288).

Directories

Path Synopsis
cmd
fido module
Package mds reads the FIDO Metadata Service (MDS3) blob and tells what a FIDO authenticator is from its AAGUID.
Package mds reads the FIDO Metadata Service (MDS3) blob and tells what a FIDO authenticator is from its AAGUID.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址