webauthn

package
v0.11.2 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2024 License: BSD-3-Clause Imports: 11 Imported by: 205

Documentation

Overview

Package webauthn contains the API functionality of the library. After creating and configuring a webauthn object, users can call the object to create and validate web authentication credentials.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SelectAuthenticator

func SelectAuthenticator(att string, rrk *bool, uv string) protocol.AuthenticatorSelection

SelectAuthenticator allow for easy marshaling of authenticator options that are provided to the user.

Types

type Authenticator

type Authenticator struct {
	// The AAGUID of the authenticator. An AAGUID is defined as an array containing the globally unique
	// identifier of the authenticator model being sought.
	AAGUID []byte `json:"AAGUID"`

	// SignCount -Upon a new login operation, the Relying Party compares the stored signature counter value
	// with the new signCount value returned in the assertion’s authenticator data. If this new
	// signCount value is less than or equal to the stored value, a cloned authenticator may
	// exist, or the authenticator may be malfunctioning.
	SignCount uint32 `json:"signCount"`

	// CloneWarning - This is a signal that the authenticator may be cloned, i.e. at least two copies of the
	// credential private key may exist and are being used in parallel. Relying Parties should incorporate
	// this information into their risk scoring. Whether the Relying Party updates the stored signature
	// counter value in this case, or not, or fails the authentication ceremony or not, is Relying Party-specific.
	CloneWarning bool `json:"cloneWarning"`

	// Attachment is the authenticatorAttachment value returned by the request.
	Attachment protocol.AuthenticatorAttachment `json:"attachment"`
}

func (*Authenticator) UpdateCounter

func (a *Authenticator) UpdateCounter(authDataCount uint32)

UpdateCounter updates the authenticator and either sets the clone warning value or the sign count.

Step 17 of §7.2. about verifying attestation. If the signature counter value authData.signCount is nonzero or the value stored in conjunction with credential’s id attribute is nonzero, then run the following sub-step:

If the signature counter value authData.signCount is

→ Greater than the signature counter value stored in conjunction with credential’s id attribute.
Update the stored signature counter value, associated with credential’s id attribute, to be the value of
authData.signCount.

→ Less than or equal to the signature counter value stored in conjunction with credential’s id attribute.
This is a signal that the authenticator may be cloned, see CloneWarning above for more information.

type Config

type Config struct {
	// RPID configures the Relying Party Server ID. This should generally be the origin without a scheme and port.
	RPID string

	// RPDisplayName configures the display name for the Relying Party Server. This can be any string.
	RPDisplayName string

	// RPOrigins configures the list of Relying Party Server Origins that are permitted. These should be fully
	// qualified origins.
	RPOrigins []string

	// RPTopOrigins configures the list of Relying Party Server Top Origins that are permitted. These should be fully
	// qualified origins.
	RPTopOrigins []string

	// RPTopOriginVerificationMode determines the verification mode for the Top Origin value. By default the
	// TopOriginIgnoreVerificationMode is used however this is going to change at such a time as WebAuthn Level 3
	// becomes recommended, implementers should explicitly set this value if they want stability.
	RPTopOriginVerificationMode protocol.TopOriginVerificationMode

	// AttestationPreference sets the default attestation conveyance preferences.
	AttestationPreference protocol.ConveyancePreference

	// AuthenticatorSelection sets the default authenticator selection options.
	AuthenticatorSelection protocol.AuthenticatorSelection

	// Debug enables various debug options.
	Debug bool

	// EncodeUserIDAsString ensures the user.id value during registrations is encoded as a raw UTF8 string. This is
	// useful when you only use printable ASCII characters for the random user.id but the browser library does not
	// decode the URL Safe Base64 data.
	EncodeUserIDAsString bool

	// Timeouts configures various timeouts.
	Timeouts TimeoutsConfig

	// MDS is a metadata.Provider and enables various metadata validations if configured.
	MDS metadata.Provider
	// contains filtered or unexported fields
}

Config represents the WebAuthn configuration.

func (*Config) GetMetaDataProvider added in v0.11.0

func (c *Config) GetMetaDataProvider() metadata.Provider

func (*Config) GetOrigins added in v0.11.0

func (c *Config) GetOrigins() []string

func (*Config) GetRPID added in v0.11.0

func (c *Config) GetRPID() string

func (*Config) GetTopOriginVerificationMode added in v0.11.0

func (c *Config) GetTopOriginVerificationMode() protocol.TopOriginVerificationMode

func (*Config) GetTopOrigins added in v0.11.0

func (c *Config) GetTopOrigins() []string

type ConfigProvider added in v0.11.0

type ConfigProvider interface {
	GetRPID() string
	GetOrigins() []string
	GetTopOrigins() []string
	GetTopOriginVerificationMode() protocol.TopOriginVerificationMode
	GetMetaDataProvider() metadata.Provider
}

type Credential

type Credential struct {
	// The Credential ID of the public key credential source. Described by the Credential Record 'id' field.
	ID []byte `json:"id"`

	// The credential public key of the public key credential source. Described by the Credential Record 'publicKey field.
	PublicKey []byte `json:"publicKey"`

	// The attestation format used (if any) by the authenticator when creating the credential.
	AttestationType string `json:"attestationType"`

	// The transport types the authenticator supports.
	Transport []protocol.AuthenticatorTransport `json:"transport"`

	// The commonly stored flags.
	Flags CredentialFlags `json:"flags"`

	// The Authenticator information for a given certificate.
	Authenticator Authenticator `json:"authenticator"`

	// The attestation values that can be used to validate this credential via the MDS3 at a later date.
	Attestation CredentialAttestation `json:"attestation"`
}

Credential contains all needed information about a WebAuthn credential for storage. This struct is effectively the Credential Record as described in the specification.

See: §4. Terminology: Credential Record (https://www.w3.org/TR/webauthn-3/#credential-record)

func NewCredential added in v0.11.0

func NewCredential(clientDataHash []byte, c *protocol.ParsedCredentialCreationData) (credential *Credential, err error)

NewCredential will return a credential pointer on successful validation of a registration response.

func (Credential) Descriptor added in v0.2.0

func (c Credential) Descriptor() (descriptor protocol.CredentialDescriptor)

Descriptor converts a Credential into a protocol.CredentialDescriptor.

func (Credential) Verify added in v0.11.0

func (c Credential) Verify(mds metadata.Provider) (err error)

Verify this credentials against the metadata.Provider given.

type CredentialAttestation added in v0.11.0

type CredentialAttestation struct {
	ClientDataJSON     []byte `json:"clientDataJSON"`
	ClientDataHash     []byte `json:"clientDataHash"`
	AuthenticatorData  []byte `json:"authenticatorData"`
	PublicKeyAlgorithm int64  `json:"publicKeyAlgorithm"`
	Object             []byte `json:"object"`
}

type CredentialFlags added in v0.7.2

type CredentialFlags struct {
	// Flag UP indicates the users presence.
	UserPresent bool `json:"userPresent"`

	// Flag UV indicates the user performed verification.
	UserVerified bool `json:"userVerified"`

	// Flag BE indicates the credential is able to be backed up and/or sync'd between devices. This should NEVER change.
	BackupEligible bool `json:"backupEligible"`

	// Flag BS indicates the credential has been backed up and/or sync'd. This value can change but it's recommended
	// that RP's keep track of this value.
	BackupState bool `json:"backupState"`
}

type DiscoverableUserHandler added in v0.2.0

type DiscoverableUserHandler func(rawID, userHandle []byte) (user User, err error)

DiscoverableUserHandler returns a *User given the provided userHandle.

type LoginOption

LoginOption is used to provide parameters that modify the default Credential Assertion Payload that is sent to the user.

func WithAllowedCredentials

func WithAllowedCredentials(allowList []protocol.CredentialDescriptor) LoginOption

WithAllowedCredentials adjusts the allowed credential list with Credential Descriptors, discussed in the included specification sections with user-supplied values.

Specification: §5.10.3. Credential Descriptor (https://www.w3.org/TR/webauthn/#dictdef-publickeycredentialdescriptor)

Specification: §5.4.4. Authenticator Selection Criteria (https://www.w3.org/TR/webauthn/#dom-authenticatorselectioncriteria-userverification)

func WithAppIdExtension added in v0.2.0

func WithAppIdExtension(appid string) LoginOption

WithAppIdExtension automatically includes the specified appid if the AllowedCredentials contains a credential with the type `fido-u2f`.

func WithAssertionExtensions

func WithAssertionExtensions(extensions protocol.AuthenticationExtensions) LoginOption

WithAssertionExtensions adjusts the requested extensions.

func WithAssertionPublicKeyCredentialHints added in v0.11.0

func WithAssertionPublicKeyCredentialHints(hints []protocol.PublicKeyCredentialHints) LoginOption

WithAssertionPublicKeyCredentialHints adjusts the non-default hints for credential types to select during login.

WebAuthn Level 3.

func WithLoginRelyingPartyID added in v0.11.0

func WithLoginRelyingPartyID(id string) LoginOption

WithLoginRelyingPartyID sets the Relying Party ID for this particular login.

func WithUserVerification

func WithUserVerification(userVerification protocol.UserVerificationRequirement) LoginOption

WithUserVerification adjusts the user verification preference.

Specification: §5.4.4. Authenticator Selection Criteria (https://www.w3.org/TR/webauthn/#dom-authenticatorselectioncriteria-userverification)

type RegistrationOption

type RegistrationOption func(*protocol.PublicKeyCredentialCreationOptions)

RegistrationOption describes a function which modifies the registration *protocol.PublicKeyCredentialCreationOptions values.

func WithAppIdExcludeExtension added in v0.2.0

func WithAppIdExcludeExtension(appid string) RegistrationOption

WithAppIdExcludeExtension automatically includes the specified appid if the CredentialExcludeList contains a credential with the type `fido-u2f`.

func WithAttestationFormats added in v0.11.0

func WithAttestationFormats(formats []protocol.AttestationFormat) RegistrationOption

WithAttestationFormats adjusts the non-default formats for credential types to select during registration.

WebAuthn Level 3.

func WithAuthenticatorSelection

func WithAuthenticatorSelection(authenticatorSelection protocol.AuthenticatorSelection) RegistrationOption

WithAuthenticatorSelection adjusts the non-default parameters regarding the authenticator to select during registration.

func WithConveyancePreference

func WithConveyancePreference(preference protocol.ConveyancePreference) RegistrationOption

WithConveyancePreference adjusts the non-default parameters regarding whether the authenticator should attest to the credential.

func WithCredentialParameters added in v0.3.4

func WithCredentialParameters(credentialParams []protocol.CredentialParameter) RegistrationOption

WithCredentialParameters adjusts the credential parameters in the registration options.

func WithExclusions

func WithExclusions(excludeList []protocol.CredentialDescriptor) RegistrationOption

WithExclusions adjusts the non-default parameters regarding credentials to exclude from registration.

func WithExtensions

func WithExtensions(extension protocol.AuthenticationExtensions) RegistrationOption

WithExtensions adjusts the extension parameter in the registration options.

func WithPublicKeyCredentialHints added in v0.11.0

func WithPublicKeyCredentialHints(hints []protocol.PublicKeyCredentialHints) RegistrationOption

WithPublicKeyCredentialHints adjusts the non-default hints for credential types to select during registration.

WebAuthn Level 3.

func WithRegistrationRelyingPartyID added in v0.11.0

func WithRegistrationRelyingPartyID(id string) RegistrationOption

WithRegistrationRelyingPartyID sets the relying party id for the registration.

func WithRegistrationRelyingPartyName added in v0.11.0

func WithRegistrationRelyingPartyName(name string) RegistrationOption

WithRegistrationRelyingPartyName sets the relying party name for the registration.

func WithResidentKeyRequirement added in v0.2.0

func WithResidentKeyRequirement(requirement protocol.ResidentKeyRequirement) RegistrationOption

WithResidentKeyRequirement sets both the resident key and require resident key protocol options.

type SessionData

type SessionData struct {
	Challenge            string    `json:"challenge"`
	RelyingPartyID       string    `json:"rpId"`
	UserID               []byte    `json:"user_id"`
	AllowedCredentialIDs [][]byte  `json:"allowed_credentials,omitempty"`
	Expires              time.Time `json:"expires"`

	UserVerification protocol.UserVerificationRequirement `json:"userVerification"`
	Extensions       protocol.AuthenticationExtensions    `json:"extensions,omitempty"`
}

SessionData is the data that should be stored by the Relying Party for the duration of the web authentication ceremony.

type TimeoutConfig added in v0.8.0

type TimeoutConfig struct {
	// Enforce the timeouts at the Relying Party / Server. This means if enabled and the user takes too long that even
	// if the browser does not enforce the timeout the Relying Party / Server will.
	Enforce bool

	// Timeout is the timeout for logins/registrations when the UserVerificationRequirement is set to anything other
	// than discouraged.
	Timeout time.Duration

	// TimeoutUVD is the timeout for logins/registrations when the UserVerificationRequirement is set to discouraged.
	TimeoutUVD time.Duration
}

TimeoutConfig represents the WebAuthn timeouts configuration for either registration or login..

type TimeoutsConfig added in v0.8.0

type TimeoutsConfig struct {
	Login        TimeoutConfig
	Registration TimeoutConfig
}

TimeoutsConfig represents the WebAuthn timeouts configuration.

type User

type User interface {
	// WebAuthnID provides the user handle of the user account. A user handle is an opaque byte sequence with a maximum
	// size of 64 bytes, and is not meant to be displayed to the user.
	//
	// To ensure secure operation, authentication and authorization decisions MUST be made on the basis of this id
	// member, not the displayName nor name members. See Section 6.1 of [RFC8266].
	//
	// It's recommended this value is completely random and uses the entire 64 bytes.
	//
	// Specification: §5.4.3. User Account Parameters for Credential Generation (https://w3c.github.io/webauthn/#dom-publickeycredentialuserentity-id)
	WebAuthnID() []byte

	// WebAuthnName provides the name attribute of the user account during registration and is a human-palatable name for the user
	// account, intended only for display. For example, "Alex Müller" or "田中倫". The Relying Party SHOULD let the user
	// choose this, and SHOULD NOT restrict the choice more than necessary.
	//
	// Specification: §5.4.3. User Account Parameters for Credential Generation (https://w3c.github.io/webauthn/#dictdef-publickeycredentialuserentity)
	WebAuthnName() string

	// WebAuthnDisplayName provides the name attribute of the user account during registration and is a human-palatable
	// name for the user account, intended only for display. For example, "Alex Müller" or "田中倫". The Relying Party
	// SHOULD let the user choose this, and SHOULD NOT restrict the choice more than necessary.
	//
	// Specification: §5.4.3. User Account Parameters for Credential Generation (https://www.w3.org/TR/webauthn/#dom-publickeycredentialuserentity-displayname)
	WebAuthnDisplayName() string

	// WebAuthnCredentials provides the list of Credential objects owned by the user.
	WebAuthnCredentials() []Credential
}

User is an interface with the Relying Party's User entry and provides the fields and methods needed for WebAuthn registration operations.

type WebAuthn

type WebAuthn struct {
	Config *Config
}

WebAuthn is the primary interface of this package and contains the request handlers that should be called.

func New

func New(config *Config) (*WebAuthn, error)

New creates a new WebAuthn object given the proper Config.

func (*WebAuthn) BeginDiscoverableLogin added in v0.2.0

func (webauthn *WebAuthn) BeginDiscoverableLogin(opts ...LoginOption) (*protocol.CredentialAssertion, *SessionData, error)

BeginDiscoverableLogin begins a client-side discoverable login, previously known as Resident Key logins.

func (*WebAuthn) BeginLogin

func (webauthn *WebAuthn) BeginLogin(user User, opts ...LoginOption) (*protocol.CredentialAssertion, *SessionData, error)

BeginLogin creates the *protocol.CredentialAssertion data payload that should be sent to the user agent for beginning the login/assertion process. The format of this data can be seen in §5.5 of the WebAuthn specification. These default values can be amended by providing additional LoginOption parameters. This function also returns sessionData, that must be stored by the RP in a secure manner and then provided to the FinishLogin function. This data helps us verify the ownership of the credential being retrieved.

Specification: §5.5. Options for Assertion Generation (https://www.w3.org/TR/webauthn/#dictionary-assertion-options)

func (*WebAuthn) BeginRegistration

func (webauthn *WebAuthn) BeginRegistration(user User, opts ...RegistrationOption) (creation *protocol.CredentialCreation, session *SessionData, err error)

BeginRegistration generates a new set of registration data to be sent to the client and authenticator.

func (*WebAuthn) CreateCredential

func (webauthn *WebAuthn) CreateCredential(user User, session SessionData, parsedResponse *protocol.ParsedCredentialCreationData) (credential *Credential, err error)

CreateCredential verifies a parsed response against the user's credentials and session data.

func (*WebAuthn) FinishDiscoverableLogin added in v0.9.0

func (webauthn *WebAuthn) FinishDiscoverableLogin(handler DiscoverableUserHandler, session SessionData, response *http.Request) (*Credential, error)

FinishDiscoverableLogin takes the response from the client and validate it against the handler and stored session data. The handler helps to find out which user must be used to validate the response. This is a function defined in your business code that will retrieve the user from your persistent data.

func (*WebAuthn) FinishLogin

func (webauthn *WebAuthn) FinishLogin(user User, session SessionData, response *http.Request) (*Credential, error)

FinishLogin takes the response from the client and validate it against the user credentials and stored session data.

func (*WebAuthn) FinishRegistration

func (webauthn *WebAuthn) FinishRegistration(user User, session SessionData, response *http.Request) (*Credential, error)

FinishRegistration takes the response from the authenticator and client and verify the credential against the user's credentials and session data.

func (*WebAuthn) ValidateDiscoverableLogin added in v0.2.0

func (webauthn *WebAuthn) ValidateDiscoverableLogin(handler DiscoverableUserHandler, session SessionData, parsedResponse *protocol.ParsedCredentialAssertionData) (credential *Credential, err error)

ValidateDiscoverableLogin is an overloaded version of ValidateLogin that allows for discoverable credentials.

Note: this is just a backwards compatibility layer over ValidatePasskeyLogin which returns more information.

func (*WebAuthn) ValidateLogin

func (webauthn *WebAuthn) ValidateLogin(user User, session SessionData, parsedResponse *protocol.ParsedCredentialAssertionData) (*Credential, error)

ValidateLogin takes a parsed response and validates it against the user credentials and session data.

func (*WebAuthn) ValidatePasskeyLogin added in v0.11.0

func (webauthn *WebAuthn) ValidatePasskeyLogin(handler DiscoverableUserHandler, session SessionData, parsedResponse *protocol.ParsedCredentialAssertionData) (user User, credential *Credential, err error)

ValidatePasskeyLogin is an overloaded version of ValidateLogin that allows for passkey credentials.

Jump to

Keyboard shortcuts

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