webauthn

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 23 Imported by: 1 module, 0 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.

Documentation

Overview

Package webauthn implements the server (Relying Party) and browser WebAssembly client primitives of the W3C WebAuthn Level 3 specification.

Registration

Registering a new credential (passkey or security key) is a three-step ceremony between the server and the browser:

  1. Server: call NewAttestationOptions, set RelyingParty and User (and optionally ExcludeCredentials to avoid re-registering existing keys), persist Challenge in session storage, and JSON-marshal the options to send to the browser.
  2. Browser: pass the options to navigator.credentials.create() (converting base64url byte fields to ArrayBuffer/Uint8Array in JavaScript, or calling Create directly in a GOOS=js GOARCH=wasm client) and send the JSON response back to the server.
  3. Server: unmarshal AttestationResponse (which accepts both W3C Level 3 RegistrationResponseJSON and flat JSON), load the expected Challenge from session storage, call VerifyAttestation with VerifyAttestationOptions, and store the resulting VerifiedCredential (ID, COSEKey, SignCount, Transports, etc.).

Authentication

Authenticating with an existing credential follows a similar three-step ceremony:

  1. Server: call NewAssertionOptions, set RPID and AllowCredentials (or leave AllowCredentials empty for discoverable credentials), persist Challenge in session storage, and JSON-marshal the options to send to the browser.
  2. Browser: pass the options to navigator.credentials.get() (or call Get directly in a GOOS=js GOARCH=wasm client) and send the JSON response back to the server.
  3. Server: unmarshal AssertionResponse (which accepts both W3C Level 3 AuthenticationResponseJSON and flat JSON), look up the stored credential using resp.RawID (and resp.UserHandle for discoverable credentials), load the expected Challenge from session storage, call VerifyAssertion with VerifyAssertionOptions, and update the stored SignCount from VerifiedAssertion.

Wire Format

Binary fields use Bytes, which marshals to JSON as unpadded base64url strings per W3C WebAuthn Level 3 and unmarshals from either unpadded base64url strings or legacy JSON arrays of byte integers.

Browser WebAssembly Client

When built with GOOS=js GOARCH=wasm, the package additionally provides Create, Get, Hostname, and Origin wrapping the browser's navigator.credentials API. Binary inputs in Extensions maps must be passed as []byte or Bytes so they are converted to JavaScript Uint8Array values.

Low-Level Primitives and Testing

Lower-level building blocks are also exported for custom verification flows: ParseClientData, VerifyClientData, ParseAttestationObject, Attestation.VerifyAttestationStatement, ParseAuthenticatorData, ParseCOSEKey, MarshalCOSEKey, MarshalCOSEKeyWithAlg, VerifySignature, and RecoverPublicKey.

FakeAuthenticator (NewFakeAuthenticator) simulates an authenticator in unit tests and examples across all supported COSE algorithms and attestation formats ("none", "packed", and "fido-u2f").

Example (Authentication)
package main

import (
	"encoding/json"
	"fmt"
	"log"

	"github.com/c2FmZQ/webauthn"
)

func main() {
	// Placeholder storage for short-lived challenges (e.g. server session store)
	// and previously registered credentials (e.g. user database).
	type storedCredential struct {
		ID         webauthn.Bytes
		UserHandle webauthn.Bytes
		COSEKey    webauthn.Bytes
		SignCount  uint32
		Transports []string
	}
	pendingChallenges := make(map[string][]byte)
	userCredentials := make(map[string]map[string]*storedCredential)

	// Setup: populate storage with an existing registered key for "alice".
	auth, err := webauthn.NewFakeAuthenticator()
	if err != nil {
		log.Fatal(err)
	}
	auth.SetOrigin("https://example.com")
	regOpts, err := webauthn.NewAttestationOptions()
	if err != nil {
		log.Fatal(err)
	}
	regOpts.RelyingParty = webauthn.RelyingPartyEntity{Name: "Example Corp", ID: "example.com"}
	regOpts.User = webauthn.UserEntity{ID: webauthn.Bytes("alice-uid"), Name: "alice@example.com", DisplayName: "Alice"}
	regCD, regAtt, err := auth.Create(regOpts)
	if err != nil {
		log.Fatal(err)
	}
	regCred, err := webauthn.VerifyAttestation(&webauthn.AttestationResponse{
		ClientDataJSON:    regCD,
		AttestationObject: regAtt,
	}, webauthn.VerifyAttestationOptions{
		Challenge: regOpts.Challenge,
		Origin:    "https://example.com",
		RPID:      "example.com",
	})
	if err != nil {
		log.Fatal(err)
	}
	userCredentials["alice"] = map[string]*storedCredential{
		regCred.ID.String(): {
			ID:         regCred.ID,
			UserHandle: regOpts.User.ID,
			COSEKey:    regCred.COSEKey,
			SignCount:  regCred.SignCount,
		},
	}

	// Placeholder for server <-> browser communication (e.g. HTTP/JSON).
	// In production, the server sends optionsJSON to the browser, the browser
	// calls navigator.credentials.get() (or webauthn.Get in Go WASM), and
	// sends the AuthenticationResponseJSON back to the server.
	browserGet := func(optionsJSON []byte) (responseJSON []byte, err error) {
		var opts webauthn.AssertionOptions
		if err := json.Unmarshal(optionsJSON, &opts); err != nil {
			return nil, err
		}
		id, clientDataJSON, authData, sig, userHandle, err := auth.Get(&opts)
		if err != nil {
			return nil, err
		}
		return json.Marshal(map[string]any{
			"id":    webauthn.Bytes(id).String(),
			"rawId": webauthn.Bytes(id),
			"type":  "public-key",
			"response": map[string]any{
				"clientDataJSON":    webauthn.Bytes(clientDataJSON),
				"authenticatorData": webauthn.Bytes(authData),
				"signature":         webauthn.Bytes(sig),
				"userHandle":        webauthn.Bytes(userHandle),
			},
		})
	}

	// Step 1 (Server): Build AssertionOptions from stored credentials and save the challenge.
	opts, err := webauthn.NewAssertionOptions()
	if err != nil {
		log.Fatal(err)
	}
	opts.RPID = "example.com"
	for _, cred := range userCredentials["alice"] {
		opts.AllowCredentials = append(opts.AllowCredentials, webauthn.CredentialID{
			Type:       "public-key",
			ID:         cred.ID,
			Transports: cred.Transports,
		})
	}
	pendingChallenges["session-2"] = opts.Challenge

	optionsJSON, err := json.Marshal(opts)
	if err != nil {
		log.Fatal(err)
	}

	// Step 2 (Browser): Send optionsJSON to the browser and receive responseJSON.
	responseJSON, err := browserGet(optionsJSON)
	if err != nil {
		log.Fatal(err)
	}

	// Step 3 (Server): Load the challenge and credential, verify the assertion,
	// and update SignCount in storage.
	challenge := pendingChallenges["session-2"]
	delete(pendingChallenges, "session-2")

	var resp webauthn.AssertionResponse
	if err := json.Unmarshal(responseJSON, &resp); err != nil {
		log.Fatal(err)
	}
	stored := userCredentials["alice"][resp.RawID.String()]
	if stored == nil {
		log.Fatal("unknown credential")
	}
	res, err := webauthn.VerifyAssertion(&resp, webauthn.VerifyAssertionOptions{
		Challenge:               challenge,
		Origin:                  "https://example.com",
		RPID:                    "example.com",
		COSEKey:                 stored.COSEKey,
		CredentialID:            stored.ID,
		UserHandle:              stored.UserHandle,
		PrevSignCount:           stored.SignCount,
		RequireUserVerification: true,
	})
	if err != nil {
		log.Fatal(err)
	}
	stored.SignCount = res.SignCount

	fmt.Printf("authenticated: userVerified=%v signCount=%d\n", res.UserVerified, stored.SignCount)
}
Output:
authenticated: userVerified=true signCount=1
Example (Registration)
package main

import (
	"encoding/json"
	"fmt"
	"log"

	"github.com/c2FmZQ/webauthn"
)

func main() {
	// Placeholder storage for short-lived challenges (e.g. server session store)
	// and registered credentials (e.g. user database).
	type storedCredential struct {
		ID         webauthn.Bytes
		UserHandle webauthn.Bytes
		COSEKey    webauthn.Bytes
		SignCount  uint32
		Transports []string
	}
	pendingChallenges := make(map[string][]byte)
	userCredentials := make(map[string]map[string]*storedCredential)

	// Placeholder for server <-> browser communication (e.g. HTTP/JSON).
	// In production, the server sends optionsJSON to the browser, the browser
	// calls navigator.credentials.create() (or webauthn.Create in Go WASM),
	// and sends the RegistrationResponseJSON back to the server.
	// FakeAuthenticator simulates the browser and authenticator here.
	auth, err := webauthn.NewFakeAuthenticator()
	if err != nil {
		log.Fatal(err)
	}
	auth.SetOrigin("https://example.com")
	browserCreate := func(optionsJSON []byte) (responseJSON []byte, err error) {
		var opts webauthn.AttestationOptions
		if err := json.Unmarshal(optionsJSON, &opts); err != nil {
			return nil, err
		}
		clientDataJSON, attestationObject, err := auth.Create(&opts)
		if err != nil {
			return nil, err
		}
		att, err := webauthn.ParseAttestationObject(attestationObject)
		if err != nil {
			return nil, err
		}
		credID := att.AuthData.AttestedCredentials.ID
		return json.Marshal(map[string]any{
			"id":    credID.String(),
			"rawId": credID,
			"type":  "public-key",
			"response": map[string]any{
				"clientDataJSON":    webauthn.Bytes(clientDataJSON),
				"attestationObject": webauthn.Bytes(attestationObject),
				"transports":        []string{"internal"},
			},
		})
	}

	// Step 1 (Server): Build AttestationOptions and store the challenge.
	opts, err := webauthn.NewAttestationOptions()
	if err != nil {
		log.Fatal(err)
	}
	opts.RelyingParty = webauthn.RelyingPartyEntity{
		Name: "Example Corp",
		ID:   "example.com",
	}
	opts.User = webauthn.UserEntity{
		ID:          webauthn.Bytes("alice-uid"),
		Name:        "alice@example.com",
		DisplayName: "Alice",
	}
	// Exclude any credentials already registered for this user.
	for _, existing := range userCredentials["alice"] {
		opts.ExcludeCredentials = append(opts.ExcludeCredentials, webauthn.CredentialID{
			Type:       "public-key",
			ID:         existing.ID,
			Transports: existing.Transports,
		})
	}
	pendingChallenges["session-1"] = opts.Challenge

	optionsJSON, err := json.Marshal(opts)
	if err != nil {
		log.Fatal(err)
	}

	// Step 2 (Browser): Send optionsJSON to the browser and receive responseJSON.
	responseJSON, err := browserCreate(optionsJSON)
	if err != nil {
		log.Fatal(err)
	}

	// Step 3 (Server): Load the challenge, verify the attestation, and save the credential.
	challenge := pendingChallenges["session-1"]
	delete(pendingChallenges, "session-1")

	var resp webauthn.AttestationResponse
	if err := json.Unmarshal(responseJSON, &resp); err != nil {
		log.Fatal(err)
	}
	cred, err := webauthn.VerifyAttestation(&resp, webauthn.VerifyAttestationOptions{
		Challenge:               challenge,
		Origin:                  "https://example.com",
		RPID:                    "example.com",
		RequireUserVerification: true,
	})
	if err != nil {
		log.Fatal(err)
	}
	if userCredentials["alice"] == nil {
		userCredentials["alice"] = make(map[string]*storedCredential)
	}
	userCredentials["alice"][cred.ID.String()] = &storedCredential{
		ID:         cred.ID,
		UserHandle: opts.User.ID,
		COSEKey:    cred.COSEKey,
		SignCount:  cred.SignCount,
		Transports: cred.Transports,
	}

	fmt.Printf("registered: userVerified=%v hasKey=%v\n", cred.UserVerified, len(cred.COSEKey) > 0)
}
Output:
registered: userVerified=true hasKey=true

Index

Examples

Constants

View Source
const (
	// COSE algorithm identifiers.
	// https://www.iana.org/assignments/cose/cose.xhtml#algorithms
	// https://w3c.github.io/webauthn/#sctn-alg-identifier
	AlgES256 = -7   // ECDSA w/ SHA-256 on P-256
	AlgEdDSA = -8   // EdDSA on Ed25519
	AlgES384 = -35  // ECDSA w/ SHA-384 on P-384
	AlgES512 = -36  // ECDSA w/ SHA-512 on P-521
	AlgPS256 = -37  // RSASSA-PSS w/ SHA-256
	AlgPS384 = -38  // RSASSA-PSS w/ SHA-384
	AlgPS512 = -39  // RSASSA-PSS w/ SHA-512
	AlgRS256 = -257 // RSASSA-PKCS1-v1_5 w/ SHA-256
	AlgRS384 = -258 // RSASSA-PKCS1-v1_5 w/ SHA-384
	AlgRS512 = -259 // RSASSA-PKCS1-v1_5 w/ SHA-512
)
View Source
const (
	// Authenticator data flags.
	// https://w3c.github.io/webauthn/#sctn-authenticator-data
	FlagUserPresent            byte = 1 << 0 // 0x01 UP
	FlagUserVerified           byte = 1 << 2 // 0x04 UV
	FlagBackupEligible         byte = 1 << 3 // 0x08 BE
	FlagBackupState            byte = 1 << 4 // 0x10 BS
	FlagAttestedCredentialData byte = 1 << 6 // 0x40 AT
	FlagExtensionData          byte = 1 << 7 // 0x80 ED
)

Variables

View Source
var ErrTooShort = errors.New("too short")

ErrTooShort indicates that the message is too short and cannot be decoded.

Functions

func ParseAuthenticatorData

func ParseAuthenticatorData(raw []byte, ad *AuthenticatorData) error

ParseAuthenticatorData parses raw authenticatorData bytes into ad and validates structural and flag invariants per W3C WebAuthn Level 3 §6.1.

func ParseCOSEKey

func ParseCOSEKey(coseKey []byte) (crypto.PublicKey, int, error)

ParseCOSEKey parses and validates a CBOR-encoded COSE_Key (RFC 9052 / RFC 9053 / RFC 8230 / RFC 8812) and returns the corresponding crypto.PublicKey and COSE algorithm identifier.

func RecoverPublicKey

func RecoverPublicKey(authData1, clientDataJSON1, sig1Bytes, authData2, clientDataJSON2, sig2Bytes []byte) (*ecdsa.PublicKey, error)

RecoverPublicKey recovers the ECDSA P-256 public key from two WebAuthn assertions using different challenges. Two assertions are required to uniquely identify the public key among the mathematically possible ECDSA recovery candidates.

func VerifySignature

func VerifySignature(coseKey, authData, clientDataJSON, signature []byte) error

VerifySignature verifies a WebAuthn assertion or attestation signature over authData || SHA-256(clientDataJSON) using the given CBOR-encoded COSE_Key.

Types

type AssertionOptions

type AssertionOptions struct {
	// The cryptographic challenge (32 random bytes).
	Challenge Bytes `json:"challenge"`
	// Timeout in milliseconds.
	Timeout int `json:"timeout,omitempty"`
	// Optional Relying Party ID.
	RPID string `json:"rpId,omitempty"`
	// A list of credentials already registered for this user.
	AllowCredentials []CredentialID `json:"allowCredentials,omitempty"`
	// UserVerification: "required", "preferred", or "discouraged".
	UserVerification string `json:"userVerification,omitempty"`
	// Optional hints ("security-key", "client-device", "hybrid").
	Hints []string `json:"hints,omitempty"`
	// Extensions. With the WASM client (Create and Get), binary inputs must
	// be []byte or Bytes values; they are passed to the browser as Uint8Array.
	Extensions map[string]any `json:"extensions,omitempty"`
}

AssertionOptions encapsulates the options to navigator.credentials.get() (PublicKeyCredentialRequestOptions).

func NewAssertionOptions

func NewAssertionOptions() (*AssertionOptions, error)

NewAssertionOptions returns a new AssertionOptions with Challenge, Timeout, UserVerification, and an empty AllowCredentials slice populated.

type AssertionResponse

type AssertionResponse struct {
	// ID is the base64url-encoded credential ID.
	ID string `json:"id,omitempty"`
	// RawID is the raw binary credential ID.
	RawID Bytes `json:"rawId,omitempty"`
	// Type is the credential type ("public-key").
	Type string `json:"type,omitempty"`
	// AuthenticatorAttachment reports how the authenticator is attached
	// ("platform" or "cross-platform").
	AuthenticatorAttachment string `json:"authenticatorAttachment,omitempty"`
	// ClientDataJSON is the serialized JSON client data passed to the authenticator.
	ClientDataJSON Bytes `json:"clientDataJSON"`
	// AuthenticatorData is the raw authenticator data returned by the authenticator.
	AuthenticatorData Bytes `json:"authenticatorData"`
	// Signature is the raw signature over authData || SHA-256(clientDataJSON).
	Signature Bytes `json:"signature"`
	// UserHandle is the user handle returned for discoverable credentials, if any.
	UserHandle Bytes `json:"userHandle,omitempty"`
}

AssertionResponse represents an authentication assertion response from navigator.credentials.get(). Its JSON unmarshaler accepts both the W3C WebAuthn Level 3 AuthenticationResponseJSON structure (with a nested "response" object) and a flat JSON object structure.

func (*AssertionResponse) UnmarshalJSON

func (r *AssertionResponse) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshals an AssertionResponse from either a W3C Level 3 AuthenticationResponseJSON object or a flat JSON object.

type Attestation

type Attestation struct {
	// Format is the attestation statement format identifier (e.g. "none", "packed", "fido-u2f").
	Format string `cbor:"fmt"`
	// AttStmt is the raw CBOR-encoded attestation statement.
	AttStmt cbor.RawMessage `cbor:"attStmt"`
	// RawAuthData is the raw authenticatorData bytes.
	RawAuthData Bytes `cbor:"authData"`

	// AuthData is the parsed authenticatorData.
	AuthData AuthenticatorData `cbor:"-"`
}

Attestation represents a parsed WebAuthn attestationObject. https://w3c.github.io/webauthn/#sctn-attestation

func ParseAttestationObject

func ParseAttestationObject(attestationObject []byte) (*Attestation, error)

ParseAttestationObject parses a CBOR-encoded attestationObject and its embedded authenticatorData. It does not verify the attestation statement signature unless VerifyAttestationStatement is called on the returned Attestation.

func (*Attestation) VerifyAttestationStatement

func (att *Attestation) VerifyAttestationStatement(clientDataJSON []byte) error

VerifyAttestationStatement optionally verifies the attestation statement signature for "none", "packed" (both x5c and self-attestation), and "fido-u2f" formats per W3C WebAuthn Level 3 §8.

type AttestationOptions

type AttestationOptions struct {
	// The cryptographic challenge (32 random bytes).
	Challenge Bytes `json:"challenge"`
	// The name and optional ID of the relying party.
	RelyingParty RelyingPartyEntity `json:"rp"`
	// The user information.
	User UserEntity `json:"user"`
	// The acceptable public key parameters.
	PubKeyCredParams []PubKeyCredParam `json:"pubKeyCredParams,omitempty"`
	// Timeout in milliseconds.
	Timeout int `json:"timeout,omitempty"`
	// A list of credentials already registered for this user.
	ExcludeCredentials []CredentialID `json:"excludeCredentials,omitempty"`
	// The type of attestation conveyance preference ("none", "indirect", "direct", "enterprise").
	Attestation string `json:"attestation,omitempty"`
	// Optional list of preferred attestation statement formats.
	AttestationFormats []string `json:"attestationFormats,omitempty"`
	// Authenticator selection parameters.
	AuthenticatorSelection AuthenticatorSelection `json:"authenticatorSelection"`
	// Optional hints ("security-key", "client-device", "hybrid").
	Hints []string `json:"hints,omitempty"`
	// Extensions. With the WASM client (Create and Get), binary inputs must
	// be []byte or Bytes values; they are passed to the browser as Uint8Array.
	Extensions map[string]any `json:"extensions,omitempty"`
}

AttestationOptions encapsulates the options to navigator.credentials.create() (PublicKeyCredentialCreationOptions).

func NewAttestationOptions

func NewAttestationOptions() (*AttestationOptions, error)

NewAttestationOptions returns a new AttestationOptions with Challenge, PubKeyCredParams, Timeout, Attestation, and AuthenticatorSelection populated with passkey-friendly defaults.

type AttestationResponse

type AttestationResponse struct {
	// ID is the base64url-encoded credential ID.
	ID string `json:"id,omitempty"`
	// RawID is the raw binary credential ID.
	RawID Bytes `json:"rawId,omitempty"`
	// Type is the credential type ("public-key").
	Type string `json:"type,omitempty"`
	// AuthenticatorAttachment reports how the authenticator is attached
	// ("platform" or "cross-platform").
	AuthenticatorAttachment string `json:"authenticatorAttachment,omitempty"`
	// ClientDataJSON is the serialized JSON client data passed to the authenticator.
	ClientDataJSON Bytes `json:"clientDataJSON"`
	// AttestationObject is the CBOR-encoded attestation object returned by the authenticator.
	AttestationObject Bytes `json:"attestationObject"`
	// Transports lists the authenticator transports (e.g. "internal", "usb", "nfc", "ble", "hybrid").
	Transports []string `json:"transports,omitempty"`
}

AttestationResponse represents a credential registration response from navigator.credentials.create(). Its JSON unmarshaler accepts both the W3C WebAuthn Level 3 RegistrationResponseJSON structure (with a nested "response" object) and a flat JSON object structure.

func (*AttestationResponse) UnmarshalJSON

func (r *AttestationResponse) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshals an AttestationResponse from either a W3C Level 3 RegistrationResponseJSON object or a flat JSON object.

type AttestedCredentials

type AttestedCredentials struct {
	// AAGUID is the 16-byte Authenticator Attestation GUID.
	AAGUID Bytes `json:"AAGUID"`
	// ID is the raw credential ID.
	ID Bytes `json:"credentialId"`
	// COSEKey is the CBOR-encoded COSE_Key public key.
	COSEKey Bytes `json:"credentialPublicKey"`
}

AttestedCredentials holds the attested credential data from an AuthenticatorData structure. https://w3c.github.io/webauthn/#sctn-attested-credential-data

func (AttestedCredentials) PublicKey

func (c AttestedCredentials) PublicKey() (crypto.PublicKey, error)

PublicKey parses and validates the COSE_Key in c.COSEKey and returns the corresponding standard library crypto.PublicKey (*ecdsa.PublicKey, ed25519.PublicKey, or *rsa.PublicKey).

type AuthenticatorData

type AuthenticatorData struct {
	// Flags is the raw 1-byte authenticator data flags bitfield.
	Flags byte `json:"flags"`
	// RPIDHash is the 32-byte SHA-256 hash of the Relying Party ID.
	RPIDHash Bytes `json:"rpIdHash"`
	// UserPresence reports whether the User Present (UP) flag is set.
	UserPresence bool `json:"up"`
	// BackupEligible reports whether the Backup Eligibility (BE) flag is set.
	BackupEligible bool `json:"be"`
	// BackupState reports whether the Backup State (BS) flag is set.
	BackupState bool `json:"bs"`
	// UserVerification reports whether the User Verified (UV) flag is set.
	UserVerification bool `json:"uv"`
	// AttestedCredentialData reports whether the AT flag is set.
	AttestedCredentialData bool `json:"at"`
	// ExtensionData reports whether the ED flag is set.
	ExtensionData bool `json:"ed"`
	// SignCount is the 32-bit signature counter.
	SignCount uint32 `json:"signCount"`
	// AttestedCredentials holds the attested credential data when AT is set.
	AttestedCredentials *AttestedCredentials `json:"attestedCredentialData,omitempty"`
	// Extensions holds the raw CBOR-encoded extension outputs when ED is set.
	Extensions Bytes `json:"extensions,omitempty"`
}

AuthenticatorData is the authenticator data provided during attestation and assertion ceremonies. https://w3c.github.io/webauthn/#sctn-authenticator-data

type AuthenticatorSelection

type AuthenticatorSelection struct {
	// AuthenticatorAttachment: "platform" or "cross-platform".
	AuthenticatorAttachment string `json:"authenticatorAttachment,omitempty"`
	// UserVerification: "required", "preferred", or "discouraged".
	UserVerification string `json:"userVerification,omitempty"`
	// ResidentKey: "required", "preferred", or "discouraged".
	ResidentKey string `json:"residentKey,omitempty"`
	// RequireResidentKey is the WebAuthn Level 1 boolean field. It should
	// be true iff ResidentKey is "required".
	RequireResidentKey bool `json:"requireResidentKey,omitempty"`
}

AuthenticatorSelection specifies requirements regarding authenticator attributes during credential creation.

type Bytes

type Bytes []byte

Bytes is a byte slice that marshals to JSON as an unpadded base64url string per W3C WebAuthn Level 3, and unmarshals from either an unpadded base64url string or a JSON array of byte integers ([1, 2, 3]) for backward compatibility.

func MarshalCOSEKey

func MarshalCOSEKey(pub crypto.PublicKey) (Bytes, error)

MarshalCOSEKey encodes a crypto.PublicKey (*ecdsa.PublicKey, ed25519.PublicKey, or *rsa.PublicKey) as a CBOR COSE_Key structure using its default COSE algorithm (AlgES256/AlgES384/AlgES512 for ECDSA, AlgEdDSA for Ed25519, and AlgRS256 for RSA). To specify an explicit RSA algorithm (such as AlgPS256 or AlgRS384), use MarshalCOSEKeyWithAlg.

func MarshalCOSEKeyWithAlg

func MarshalCOSEKeyWithAlg(pub crypto.PublicKey, alg int) (Bytes, error)

MarshalCOSEKeyWithAlg encodes a crypto.PublicKey as a CBOR COSE_Key structure with the specified COSE algorithm identifier (if alg is 0, the default algorithm for the key type is used).

func ParseBytes

func ParseBytes(s string) (Bytes, error)

ParseBytes decodes an unpadded base64url string into Bytes.

func (Bytes) MarshalJSON

func (b Bytes) MarshalJSON() ([]byte, error)

MarshalJSON marshals b as an unpadded base64url JSON string (or null if nil).

func (Bytes) String

func (b Bytes) String() string

String returns the unpadded base64url representation of b.

func (*Bytes) UnmarshalJSON

func (b *Bytes) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshals b from either an unpadded base64url JSON string or a JSON array of integers in [0, 255].

type ClientData

type ClientData struct {
	// Type is "webauthn.create" or "webauthn.get".
	Type string `json:"type"`
	// Challenge is the unpadded base64url-encoded challenge.
	Challenge string `json:"challenge"`
	// Origin is the serialized origin of the caller.
	Origin string `json:"origin"`
	// CrossOrigin reports whether the ceremony occurred in a cross-origin iframe.
	CrossOrigin bool `json:"crossOrigin,omitempty"`
	// TopOrigin is the top-level origin when CrossOrigin is true.
	TopOrigin string `json:"topOrigin,omitempty"`
	// TokenBinding is the optional TLS token binding state.
	TokenBinding *TokenBinding `json:"tokenBinding,omitempty"`
}

ClientData is a decoded CollectedClientData (clientDataJSON) object. https://w3c.github.io/webauthn/#dictdef-collectedclientdata

func ParseClientData

func ParseClientData(js []byte) (*ClientData, error)

ParseClientData parses a clientDataJSON blob and validates structural invariants on optional fields (crossOrigin/topOrigin and tokenBinding).

func VerifyClientData

func VerifyClientData(js []byte, wantType string, wantChallenge []byte, wantOrigin string) (*ClientData, error)

VerifyClientData checks that a clientDataJSON blob belongs to the ceremony requested by the caller: it validates the type ("webauthn.create" or "webauthn.get"), rejects cross-origin ceremonies, verifies that the base64url-encoded challenge strictly decodes to wantChallenge, and (when wantOrigin is non-empty) checks that Origin matches wantOrigin.

type CredentialID

type CredentialID struct {
	// The type of credential. Always "public-key".
	Type string `json:"type"`
	// The credential ID.
	ID Bytes `json:"id"`
	// The available transports for this credential.
	Transports []string `json:"transports,omitempty"`
}

CredentialID is a public key credential descriptor.

type FakeAuthenticator

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

FakeAuthenticator mimics the behavior of a WebAuthn authenticator for testing.

func NewFakeAuthenticator

func NewFakeAuthenticator() (*FakeAuthenticator, error)

NewFakeAuthenticator returns a new FakeAuthenticator for testing.

func (*FakeAuthenticator) Create

func (a *FakeAuthenticator) Create(options *AttestationOptions) (clientDataJSON, attestationObject []byte, err error)

Create mimics the behavior of the WebAuthn navigator.credentials.create() call.

The attestation statement format is selected with options.Attestation and options.AttestationFormats. To get a "packed" or "fido-u2f" attestation, set Attestation to "direct" and AttestationFormats to the desired format. See also SetSelfAttestation.

func (*FakeAuthenticator) Get

func (a *FakeAuthenticator) Get(options *AssertionOptions) (id, clientDataJSON, authData, signature, userHandle []byte, err error)

Get mimics the behavior of the WebAuthn navigator.credentials.get() call.

func (*FakeAuthenticator) ResetSignCount

func (a *FakeAuthenticator) ResetSignCount()

ResetSignCount resets the signature counter of all the keys, like a cloned authenticator would.

func (*FakeAuthenticator) RotateKeys

func (a *FakeAuthenticator) RotateKeys() error

RotateKeys replaces all private keys in the fake authenticator so subsequent signatures will fail verification against the previously attested public keys.

func (*FakeAuthenticator) SetOrigin

func (a *FakeAuthenticator) SetOrigin(orig string)

SetOrigin sets the origin reported in clientDataJSON by the fake authenticator.

func (*FakeAuthenticator) SetSelfAttestation

func (a *FakeAuthenticator) SetSelfAttestation(self bool)

SetSelfAttestation selects the kind of "packed" attestation statement that the fake authenticator produces: self attestation (signed with the credential private key) when self is true, or basic attestation with an x5c attestation certificate when it is false (the default).

type PubKeyCredParam

type PubKeyCredParam struct {
	// The type of credential. Always "public-key".
	Type string `json:"type"`
	// The COSE algorithm identifier (e.g. -7 for ES256, -8 for EdDSA, -257 for RS256).
	Alg int `json:"alg"`
}

PubKeyCredParam specifies a credential type and COSE algorithm identifier.

type RelyingPartyEntity

type RelyingPartyEntity struct {
	// Name is a human-palatable name for the Relying Party (e.g. "Example Corp").
	Name string `json:"name"`
	// ID is the Relying Party Identifier (e.g. "example.com"). If omitted, the
	// browser defaults it to the effective domain of the current origin.
	ID string `json:"id,omitempty"`
}

RelyingPartyEntity describes the Relying Party in AttestationOptions.

type TokenBinding

type TokenBinding struct {
	// Status is "present" or "supported".
	Status string `json:"status"`
	// ID is the base64url-encoded token binding ID when Status is "present".
	ID string `json:"id,omitempty"`
}

TokenBinding represents the tokenBinding member of CollectedClientData. https://w3c.github.io/webauthn/#dom-collectedclientdata-tokenbinding

type UserEntity

type UserEntity struct {
	// ID is an opaque, user-specific byte sequence (1-64 bytes).
	ID Bytes `json:"id"`
	// Name is a human-palatable identifier for the user account (e.g. "alice@example.com").
	Name string `json:"name"`
	// DisplayName is a human-palatable name for the user account (e.g. "Alice").
	DisplayName string `json:"displayName"`
}

UserEntity describes the user account in AttestationOptions.

type VerifiedAssertion

type VerifiedAssertion struct {
	// CredentialID is the raw ID of the credential that produced the assertion.
	CredentialID Bytes
	// UserHandle is the user handle returned by the authenticator, if any.
	UserHandle Bytes
	// SignCount is the updated signature counter to persist for replay/clone detection.
	SignCount uint32
	// BackupEligible reports whether the credential is multi-device (BE flag).
	BackupEligible bool
	// BackupState reports whether the credential is currently backed up (BS flag).
	BackupState bool
	// UserVerified reports whether the user was verified during authentication (UV flag).
	UserVerified bool
	// AuthData is the parsed authenticatorData.
	AuthData AuthenticatorData
	// ClientData is the parsed clientDataJSON.
	ClientData *ClientData
}

VerifiedAssertion contains the validated assertion details resulting from a successful authentication ceremony (VerifyAssertion).

func VerifyAssertion

func VerifyAssertion(resp *AssertionResponse, opts VerifyAssertionOptions) (*VerifiedAssertion, error)

VerifyAssertion performs server-side verification of an authentication assertion response per W3C WebAuthn Level 3 §7.2.

type VerifiedCredential

type VerifiedCredential struct {
	// ID is the raw credential ID to store for future assertions.
	ID Bytes
	// PublicKey is the parsed standard library public key (*ecdsa.PublicKey,
	// ed25519.PublicKey, or *rsa.PublicKey).
	PublicKey crypto.PublicKey
	// COSEKey is the CBOR-encoded COSE_Key to store for future assertions.
	COSEKey Bytes
	// Algorithm is the COSE algorithm identifier (e.g. AlgES256, AlgEdDSA, AlgRS256).
	Algorithm int
	// AAGUID is the 16-byte Authenticator Attestation GUID.
	AAGUID Bytes
	// RPIDHash is the SHA-256 hash of the Relying Party ID.
	RPIDHash Bytes
	// SignCount is the initial signature counter reported by the authenticator.
	SignCount uint32
	// BackupEligible reports whether the credential is multi-device (BE flag).
	BackupEligible bool
	// BackupState reports whether the credential is currently backed up (BS flag).
	BackupState bool
	// UserVerified reports whether the user was verified during registration (UV flag).
	UserVerified bool
	// Transports lists the authenticator transports reported by the browser.
	Transports []string
	// Attestation is the parsed attestationObject.
	Attestation *Attestation
	// ClientData is the parsed clientDataJSON.
	ClientData *ClientData
}

VerifiedCredential contains the validated credential information resulting from a successful registration ceremony (VerifyAttestation).

func VerifyAttestation

func VerifyAttestation(resp *AttestationResponse, opts VerifyAttestationOptions) (*VerifiedCredential, error)

VerifyAttestation performs server-side verification of a registration response per W3C WebAuthn Level 3 §7.1.

type VerifyAssertionOptions

type VerifyAssertionOptions struct {
	// Challenge is the expected raw challenge bytes sent in AssertionOptions.
	Challenge []byte
	// Origin is the expected clientData.origin (e.g. "https://example.com").
	Origin string
	// AllowedOrigins is an optional list of acceptable origins (used if Origin is empty).
	AllowedOrigins []string
	// RPID is the Relying Party Identifier (e.g. "example.com").
	RPID string
	// COSEKey is the stored CBOR-encoded COSE_Key for the credential.
	COSEKey []byte
	// CredentialID, if non-empty, must match the credential ID in the response.
	CredentialID []byte
	// UserHandle, if non-empty, must match a non-empty userHandle in the response.
	UserHandle []byte
	// RequireUserVerification requires the UV flag to be set in authenticatorData.
	RequireUserVerification bool
	// PrevSignCount is the previously recorded signature counter for this credential.
	PrevSignCount uint32
	// IgnoreSignCount disables the signature counter progression check.
	IgnoreSignCount bool
}

VerifyAssertionOptions configures server-side verification of an authentication assertion response per W3C WebAuthn Level 3 §7.2.

type VerifyAttestationOptions

type VerifyAttestationOptions struct {
	// Challenge is the expected raw challenge bytes sent in AttestationOptions.
	Challenge []byte
	// Origin is the expected clientData.origin (e.g. "https://example.com").
	Origin string
	// AllowedOrigins is an optional list of acceptable origins (used if Origin is empty).
	AllowedOrigins []string
	// RPID is the Relying Party Identifier (e.g. "example.com").
	RPID string
	// RequireUserVerification requires the UV flag to be set in authenticatorData.
	RequireUserVerification bool
	// VerifyAttestationStatement requires the attestation statement signature
	// ("none", "packed", "fido-u2f") to be verified.
	VerifyAttestationStatement bool
	// AllowedAlgorithms is an optional list of acceptable COSE algorithm
	// identifiers. If empty, all supported algorithms are allowed.
	AllowedAlgorithms []int
}

VerifyAttestationOptions configures server-side verification of a credential registration response per W3C WebAuthn Level 3 §7.1.

Directories

Path Synopsis
Package ssh implements OpenSSH FIDO2/WebAuthn ECDSA P-256 security keys (sk-ecdsa-sha2-nistp256@openssh.com) and browser WebAuthn SSH signatures (webauthn-sk-ecdsa-sha2-nistp256@openssh.com) per OpenSSH PROTOCOL.u2f.
Package ssh implements OpenSSH FIDO2/WebAuthn ECDSA P-256 security keys (sk-ecdsa-sha2-nistp256@openssh.com) and browser WebAuthn SSH signatures (webauthn-sk-ecdsa-sha2-nistp256@openssh.com) per OpenSSH PROTOCOL.u2f.

Jump to

Keyboard shortcuts

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