webauthn

package
v0.10.2 Latest Latest
Warning

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

Go to latest
Published: Mar 13, 2024 License: BSD-3-Clause Imports: 7 Imported by: 143

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

	// 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

	// RPIcon sets the icon URL for the Relying Party Server.
	//
	// Deprecated: this option has been removed from newer specifications due to security considerations.
	RPIcon string

	// RPOrigin configures the permitted Relying Party Server Origin.
	//
	// Deprecated: Use RPOrigins instead.
	RPOrigin string

	// Timeout configures the default timeout in milliseconds.
	//
	// Deprecated: Use Timeouts instead.
	Timeout int
	// contains filtered or unexported fields
}

Config represents the WebAuthn configuration.

type Credential

type Credential struct {
	// A probabilistically-unique byte sequence identifying a public key credential source and its authentication assertions.
	ID []byte `json:"id"`

	// The public key portion of a Relying Party-specific credential key pair, generated by an authenticator and returned to
	// a Relying Party at registration time (see also public key credential). The private key portion of the credential key
	// pair is known as the credential private key. Note that in the case of self attestation, the credential key pair is also
	// used as the attestation key pair, see self attestation for details.
	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"`
}

Credential contains all needed information about a WebAuthn credential for storage.

func MakeNewCredential

func MakeNewCredential(c *protocol.ParsedCredentialCreationData) (*Credential, error)

MakeNewCredential 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.

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 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 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 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"`
	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

	// WebAuthnIcon is a deprecated option.
	// Deprecated: this has been removed from the specification recommendation. Suggest a blank string.
	WebAuthnIcon() string
}

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, 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, error)

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

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.

Jump to

Keyboard shortcuts

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