protocol

package
v0.0.0-...-ebaf9b7 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2022 License: BSD-3-Clause Imports: 28 Imported by: 51

Documentation

Overview

The protocol package contains data structures and validation functionality outlined in the Web Authnentication specification (https://www.w3.org/TR/webauthn). The data structures here attempt to conform as much as possible to their definitions, but some structs (like those that are used as part of validation steps) contain additional fields that help us unpack and validate the data we unmarshall. When implementing this library, most developers will primarily be using the API outlined in the webauthn package.

Index

Constants

View Source
const (
	Verified verifiedBootState = iota
	SelfSigned
	Unverified
	Failed
)
View Source
const (
	KM_ORIGIN_GENERATED = iota /* Generated in keymaster.  Should not exist outside the TEE. */
	KM_ORIGIN_DERIVED          /* Derived inside keymaster.  Likely exists off-device. */
	KM_ORIGIN_IMPORTED         /* Imported into keymaster.  Existed as cleartext in Android. */
	KM_ORIGIN_UNKNOWN          /* Keymaster did not record origin.  This value can only be seen on
	 * keys in a keymaster0 implementation.  The keymaster0 adapter uses
	 * this value to document the fact that it is unkown whether the key
	 * was generated inside or imported into keymaster. */
)
View Source
const (
	KM_PURPOSE_ENCRYPT    = iota /* Usable with RSA, EC and AES keys. */
	KM_PURPOSE_DECRYPT           /* Usable with RSA, EC and AES keys. */
	KM_PURPOSE_SIGN              /* Usable with RSA, EC and HMAC keys. */
	KM_PURPOSE_VERIFY            /* Usable with RSA, EC and HMAC keys. */
	KM_PURPOSE_DERIVE_KEY        /* Usable with EC keys. */
	KM_PURPOSE_WRAP              /* Usable with wrapped keys. */
)
View Source
const ChallengeLength = 32

ChallengeLength - Length of bytes to generate for a challenge

Variables

View Source
var (
	ErrBadRequest = &Error{
		Type:    "invalid_request",
		Details: "Error reading the requst data",
	}
	ErrChallengeMismatch = &Error{
		Type:    "challenge_mismatch",
		Details: "Stored challenge and received challenge do not match",
	}
	ErrParsingData = &Error{
		Type:    "parse_error",
		Details: "Error parsing the authenticator response",
	}
	ErrAuthData = &Error{
		Type:    "auth_data",
		Details: "Error verifying the authenticator data",
	}
	ErrVerification = &Error{
		Type:    "verification_error",
		Details: "Error validating the authenticator response",
	}
	ErrAttestation = &Error{
		Type:    "attesation_error",
		Details: "Error validating the attestation data provided",
	}
	ErrInvalidAttestation = &Error{
		Type:    "invalid_attestation",
		Details: "Invalid attestation data",
	}
	ErrAttestationFormat = &Error{
		Type:    "invalid_attestation",
		Details: "Invalid attestation format",
	}
	ErrAttestationCertificate = &Error{
		Type:    "invalid_certificate",
		Details: "Invalid attestation certificate",
	}
	ErrAssertionSignature = &Error{
		Type:    "invalid_signature",
		Details: "Assertion Signature against auth data and client hash is not valid",
	}
	ErrUnsupportedKey = &Error{
		Type:    "invalid_key_type",
		Details: "Unsupported Public Key Type",
	}
	ErrUnsupportedAlgorithm = &Error{
		Type:    "unsupported_key_algorithm",
		Details: "Unsupported public key algorithm",
	}
	ErrNotSpecImplemented = &Error{
		Type:    "spec_unimplemented",
		Details: "This field is not yet supported by the WebAuthn spec",
	}
	ErrNotImplemented = &Error{
		Type:    "not_implemented",
		Details: "This field is not yet supported by this library",
	}
)

Functions

func FullyQualifiedOrigin

func FullyQualifiedOrigin(u *url.URL) string

Returns the origin per the HTML spec: (scheme)://(host)[:(port)]

func RegisterAttestationFormat

func RegisterAttestationFormat(format string, handler attestationFormatValidationHandler)

Using one of the locally registered attestation formats, handle validating the attestation data provided by the authenticator (and in some cases its manufacturer)

func ResidentKeyRequired

func ResidentKeyRequired() *bool

ResidentKeyRequired - Require that the key be private key resident to the client device

func ResidentKeyUnrequired

func ResidentKeyUnrequired() *bool

ResidentKeyUnrequired - Do not require that the private key be resident to the client device.

Types

type AppleAnonymousAttestation

type AppleAnonymousAttestation struct {
	Nonce []byte `asn1:"tag:1,explicit"`
}

Apple has not yet publish schema for the extension(as of JULY 2021.)

type AttestationObject

type AttestationObject struct {
	// The authenticator data, including the newly created public key. See AuthenticatorData for more info
	AuthData AuthenticatorData
	// The byteform version of the authenticator data, used in part for signature validation
	RawAuthData []byte `json:"authData"`
	// The format of the Attestation data.
	Format string `json:"fmt"`
	// The attestation statement data sent back if attestation is requested.
	AttStatement map[string]interface{} `json:"attStmt,omitempty"`
}

From §6.4. Authenticators MUST also provide some form of attestation. The basic requirement is that the authenticator can produce, for each credential public key, an attestation statement verifiable by the WebAuthn Relying Party. Typically, this attestation statement contains a signature by an attestation private key over the attested credential public key and a challenge, as well as a certificate or similar data providing provenance information for the attestation public key, enabling the Relying Party to make a trust decision. However, if an attestation key pair is not available, then the authenticator MUST perform self attestation of the credential public key with the corresponding credential private key. All this information is returned by authenticators any time a new public key credential is generated, in the overall form of an attestation object. (https://www.w3.org/TR/webauthn/#attestation-object)

func (*AttestationObject) Verify

func (attestationObject *AttestationObject) Verify(relyingPartyID string, clientDataHash []byte, verificationRequired bool) error

Verify - Perform Steps 9 through 14 of registration verification, delegating Steps

type AttestedCredentialData

type AttestedCredentialData struct {
	AAGUID       []byte `json:"aaguid"`
	CredentialID []byte `json:"credential_id"`
	// The raw credential public key bytes received from the attestation data
	CredentialPublicKey []byte `json:"public_key"`
}

type AuthenticationExtensions

type AuthenticationExtensions map[string]interface{}

AuthenticationExtensions - referred to as AuthenticationExtensionsClientInputs in the spec document, this member contains additional parameters requesting additional processing by the client and authenticator. This is currently under development

type AuthenticationExtensionsClientOutputs

type AuthenticationExtensionsClientOutputs map[string]interface{}

type AuthenticatorAssertionResponse

type AuthenticatorAssertionResponse struct {
	AuthenticatorResponse
	AuthenticatorData URLEncodedBase64 `json:"authenticatorData"`
	Signature         URLEncodedBase64 `json:"signature"`
	UserHandle        URLEncodedBase64 `json:"userHandle,omitempty"`
}

The AuthenticatorAssertionResponse contains the raw authenticator assertion data and is parsed into ParsedAssertionResponse

type AuthenticatorAttachment

type AuthenticatorAttachment string

AuthenticatorAttachment https://www.w3.org/TR/webauthn/#dom-authenticatorselectioncriteria-authenticatorattachment

const (
	// Platform - A platform authenticator is attached using a client device-specific transport, called
	// platform attachment, and is usually not removable from the client device. A public key credential
	//  bound to a platform authenticator is called a platform credential.
	Platform AuthenticatorAttachment = "platform"
	// CrossPlatform A roaming authenticator is attached using cross-platform transports, called
	// cross-platform attachment. Authenticators of this class are removable from, and can "roam"
	// among, client devices. A public key credential bound to a roaming authenticator is called a
	// roaming credential.
	CrossPlatform AuthenticatorAttachment = "cross-platform"
)

type AuthenticatorAttestationResponse

type AuthenticatorAttestationResponse struct {
	// The byte slice of clientDataJSON, which becomes CollectedClientData
	AuthenticatorResponse
	// The byte slice version of AttestationObject
	// This attribute contains an attestation object, which is opaque to, and
	// cryptographically protected against tampering by, the client. The
	// attestation object contains both authenticator data and an attestation
	// statement. The former contains the AAGUID, a unique credential ID, and
	// the credential public key. The contents of the attestation statement are
	// determined by the attestation statement format used by the authenticator.
	// It also contains any additional information that the Relying Party's server
	// requires to validate the attestation statement, as well as to decode and
	// validate the authenticator data along with the JSON-serialized client data.
	AttestationObject URLEncodedBase64 `json:"attestationObject"`
}

The initial unpacked 'response' object received by the relying party. This contains the clientDataJSON object, which will be marshalled into CollectedClientData, and the 'attestationObject', which contains information about the authenticator, and the newly minted public key credential. The information in both objects are used to verify the authenticity of the ceremony and new credential

func (*AuthenticatorAttestationResponse) Parse

Parse the values returned in the authenticator response and perform attestation verification Step 8. This returns a fully decoded struct with the data put into a format that can be used to verify the user and credential that was created

type AuthenticatorData

type AuthenticatorData struct {
	RPIDHash []byte                 `json:"rpid"`
	Flags    AuthenticatorFlags     `json:"flags"`
	Counter  uint32                 `json:"sign_count"`
	AttData  AttestedCredentialData `json:"att_data"`
	ExtData  []byte                 `json:"ext_data"`
}

AuthenticatorData From §6.1 of the spec. The authenticator data structure encodes contextual bindings made by the authenticator. These bindings are controlled by the authenticator itself, and derive their trust from the WebAuthn Relying Party's assessment of the security properties of the authenticator. In one extreme case, the authenticator may be embedded in the client, and its bindings may be no more trustworthy than the client data. At the other extreme, the authenticator may be a discrete entity with high-security hardware and software, connected to the client over a secure channel. In both cases, the Relying Party receives the authenticator data in the same format, and uses its knowledge of the authenticator to make trust decisions.

The authenticator data, at least during attestation, contains the Public Key that the RP stores and will associate with the user attempting to register.

func (*AuthenticatorData) Unmarshal

func (a *AuthenticatorData) Unmarshal(rawAuthData []byte) error

Unmarshal will take the raw Authenticator Data and marshalls it into AuthenticatorData for further validation. The authenticator data has a compact but extensible encoding. This is desired since authenticators can be devices with limited capabilities and low power requirements, with much simpler software stacks than the client platform. The authenticator data structure is a byte array of 37 bytes or more, and is laid out in this table: https://www.w3.org/TR/webauthn/#table-authData

func (*AuthenticatorData) Verify

func (a *AuthenticatorData) Verify(rpIdHash, appIDHash []byte, userVerificationRequired bool) error

Verify on AuthenticatorData handles Steps 9 through 12 for Registration and Steps 11 through 14 for Assertion.

type AuthenticatorFlags

type AuthenticatorFlags byte

AuthenticatorFlags A byte of information returned during during ceremonies in the authenticatorData that contains bits that give us information about the whether the user was present and/or verified during authentication, and whether there is attestation or extension data present. Bit 0 is the least significant bit.

const (
	// FlagUserPresent Bit 00000001 in the byte sequence. Tells us if user is present
	FlagUserPresent AuthenticatorFlags = 1 << iota // Referred to as UP

	// FlagUserVerified Bit 00000100 in the byte sequence. Tells us if user is verified
	// by the authenticator using a biometric or PIN
	FlagUserVerified // Referred to as UV

	// FlagAttestedCredentialData Bit 01000000 in the byte sequence. Indicates whether
	// the authenticator added attested credential data.
	FlagAttestedCredentialData // Referred to as AT
	// FlagHasExtension Bit 10000000 in the byte sequence. Indicates if the authenticator data has extensions.
	FlagHasExtensions //  Referred to as ED
)

The bits that do not have flags are reserved for future use.

func (AuthenticatorFlags) HasAttestedCredentialData

func (flag AuthenticatorFlags) HasAttestedCredentialData() bool

HasAttestedCredentialData returns if the AT flag was set

func (AuthenticatorFlags) HasExtensions

func (flag AuthenticatorFlags) HasExtensions() bool

HasExtensions returns if the ED flag was set

func (AuthenticatorFlags) UserPresent

func (flag AuthenticatorFlags) UserPresent() bool

UserPresent returns if the UP flag was set

func (AuthenticatorFlags) UserVerified

func (flag AuthenticatorFlags) UserVerified() bool

UserVerified returns if the UV flag was set

type AuthenticatorResponse

type AuthenticatorResponse struct {
	// From the spec https://www.w3.org/TR/webauthn/#dom-authenticatorresponse-clientdatajson
	// This attribute contains a JSON serialization of the client data passed to the authenticator
	// by the client in its call to either create() or get().
	ClientDataJSON URLEncodedBase64 `json:"clientDataJSON"`
}

Authenticators respond to Relying Party requests by returning an object derived from the AuthenticatorResponse interface. See §5.2. Authenticator Responses https://www.w3.org/TR/webauthn/#iface-authenticatorresponse

type AuthenticatorSelection

type AuthenticatorSelection struct {
	// AuthenticatorAttachment If this member is present, eligible authenticators are filtered to only
	// authenticators attached with the specified AuthenticatorAttachment enum
	AuthenticatorAttachment AuthenticatorAttachment `json:"authenticatorAttachment,omitempty"`
	// RequireResidentKey this member describes the Relying Party's requirements regarding resident
	// credentials. If the parameter is set to true, the authenticator MUST create a client-side-resident
	// public key credential source when creating a public key credential.
	RequireResidentKey *bool `json:"requireResidentKey,omitempty"`
	// ResidentKey this member describes the Relying Party's requirements regarding resident
	// credentials per Webauthn Level 2.
	ResidentKey ResidentKeyRequirement `json:"residentKey,omitempty"`
	// UserVerification This member describes the Relying Party's requirements regarding user verification for
	// the create() operation. Eligible authenticators are filtered to only those capable of satisfying this
	// requirement.
	UserVerification UserVerificationRequirement `json:"userVerification,omitempty"`
}

WebAuthn Relying Parties may use the AuthenticatorSelectionCriteria dictionary to specify their requirements regarding authenticator attributes. See §5.4.4. Authenticator Selection Criteria https://www.w3.org/TR/webauthn/#authenticatorSelection

type AuthenticatorTransport

type AuthenticatorTransport string

Authenticators may implement various transports for communicating with clients. This enumeration defines hints as to how clients might communicate with a particular authenticator in order to obtain an assertion for a specific credential. Note that these hints represent the WebAuthn Relying Party's best belief as to how an authenticator may be reached. A Relying Party may obtain a list of transports hints from some attestation statement formats or via some out-of-band mechanism; it is outside the scope of this specification to define that mechanism. See §5.10.4. Authenticator Transport https://www.w3.org/TR/webauthn/#transport

const (
	// USB The authenticator should transport information over USB
	USB AuthenticatorTransport = "usb"
	// NFC The authenticator should transport information over Near Field Communication Protocol
	NFC AuthenticatorTransport = "nfc"
	// BLE The authenticator should transport information over Bluetooth
	BLE AuthenticatorTransport = "ble"
	// Internal the client should use an internal source like a TPM or SE
	Internal AuthenticatorTransport = "internal"
)

type CeremonyType

type CeremonyType string
const (
	CreateCeremony CeremonyType = "webauthn.create"
	AssertCeremony CeremonyType = "webauthn.get"
)

type Challenge

type Challenge URLEncodedBase64

Challenge that should be signed and returned by the authenticator

func CreateChallenge

func CreateChallenge() (Challenge, error)

Create a new challenge to be sent to the authenticator. The spec recommends using at least 16 bytes with 100 bits of entropy. We use 32 bytes.

func (Challenge) String

func (c Challenge) String() string

type CollectedClientData

type CollectedClientData struct {
	// Type the string "webauthn.create" when creating new credentials,
	// and "webauthn.get" when getting an assertion from an existing credential. The
	// purpose of this member is to prevent certain types of signature confusion attacks
	//(where an attacker substitutes one legitimate signature for another).
	Type         CeremonyType  `json:"type"`
	Challenge    string        `json:"challenge"`
	Origin       string        `json:"origin"`
	TokenBinding *TokenBinding `json:"tokenBinding,omitempty"`
	// Chromium (Chrome) returns a hint sometimes about how to handle clientDataJSON in a safe manner
	Hint string `json:"new_keys_may_be_added_here,omitempty"`
}

CollectedClientData represents the contextual bindings of both the WebAuthn Relying Party and the client. It is a key-value mapping whose keys are strings. Values can be any type that has a valid encoding in JSON. Its structure is defined by the following Web IDL. https://www.w3.org/TR/webauthn/#sec-client-data

func (*CollectedClientData) Verify

func (c *CollectedClientData) Verify(storedChallenge string, ceremony CeremonyType, relyingPartyOrigin string) error

Handles steps 3 through 6 of verfying the registering client data of a new credential and steps 7 through 10 of verifying an authentication assertion See https://www.w3.org/TR/webauthn/#registering-a-new-credential and https://www.w3.org/TR/webauthn/#verifying-assertion

type ConveyancePreference

type ConveyancePreference string

WebAuthn Relying Parties may use AttestationConveyancePreference to specify their preference regarding attestation conveyance during credential generation. See §5.4.6. https://www.w3.org/TR/webauthn/#attestation-convey

const (
	// The default value. This value indicates that the Relying Party is not interested in authenticator attestation. For example,
	// in order to potentially avoid having to obtain user consent to relay identifying information to the Relying Party, or to
	// save a roundtrip to an Attestation CA.
	PreferNoAttestation ConveyancePreference = "none"
	// This value indicates that the Relying Party prefers an attestation conveyance yielding verifiable attestation
	// statements, but allows the client to decide how to obtain such attestation statements. The client MAY replace
	// the authenticator-generated attestation statements with attestation statements generated by an Anonymization
	// CA, in order to protect the user’s privacy, or to assist Relying Parties with attestation verification in a
	// heterogeneous ecosystem.
	PreferIndirectAttestation ConveyancePreference = "indirect"
	// This value indicates that the Relying Party wants to receive the attestation statement as generated by the authenticator.
	PreferDirectAttestation ConveyancePreference = "direct"
)

type Credential

type Credential struct {
	// ID is The credential’s identifier. The requirements for the
	// identifier are distinct for each type of credential. It might
	// represent a username for username/password tuples, for example.
	ID string `json:"id"`
	// Type is the value of the object’s interface object's [[type]] slot,
	// which specifies the credential type represented by this object.
	// This should be type "public-key" for Webauthn credentials.
	Type string `json:"type"`
}

The basic credential type that is inherited by WebAuthn's PublicKeyCredential type https://w3c.github.io/webappsec-credential-management/#credential

type CredentialAssertion

type CredentialAssertion struct {
	Response PublicKeyCredentialRequestOptions `json:"publicKey"`
}

type CredentialAssertionResponse

type CredentialAssertionResponse struct {
	PublicKeyCredential
	AssertionResponse AuthenticatorAssertionResponse `json:"response"`
}

The raw response returned to us from an authenticator when we request a credential for login/assertion.

type CredentialCreation

type CredentialCreation struct {
	Response PublicKeyCredentialCreationOptions `json:"publicKey"`
}

type CredentialCreationResponse

type CredentialCreationResponse struct {
	PublicKeyCredential
	AttestationResponse AuthenticatorAttestationResponse `json:"response"`
}

type CredentialDescriptor

type CredentialDescriptor struct {
	// The valid credential types.
	Type CredentialType `json:"type"`
	// CredentialID The ID of a credential to allow/disallow
	CredentialID []byte `json:"id"`
	// The authenticator transports that can be used
	Transport []AuthenticatorTransport `json:"transports,omitempty"`
}

This dictionary contains the attributes that are specified by a caller when referring to a public key credential as an input parameter to the create() or get() methods. It mirrors the fields of the PublicKeyCredential object returned by the latter methods. See §5.10.3. Credential Descriptor https://www.w3.org/TR/webauthn/#credential-dictionary

type CredentialEntity

type CredentialEntity struct {
	// A human-palatable name for the entity. Its function depends on what the PublicKeyCredentialEntity represents:
	//
	// When inherited by PublicKeyCredentialRpEntity it is a human-palatable identifier for the Relying Party,
	// intended only for display. For example, "ACME Corporation", "Wonderful Widgets, Inc." or "ОАО Примертех".
	//
	// When inherited by PublicKeyCredentialUserEntity, it is a human-palatable identifier for a user account. It is
	// intended only for display, i.e., aiding the user in determining the difference between user accounts with similar
	// displayNames. For example, "alexm", "alex.p.mueller@example.com" or "+14255551234".
	Name string `json:"name"`
	// A serialized URL which resolves to an image associated with the entity. For example,
	// this could be a user’s avatar or a Relying Party's logo. This URL MUST be an a priori
	// authenticated URL. Authenticators MUST accept and store a 128-byte minimum length for
	// an icon member’s value. Authenticators MAY ignore an icon member’s value if its length
	// is greater than 128 bytes. The URL’s scheme MAY be "data" to avoid fetches of the URL,
	// at the cost of needing more storage.
	Icon string `json:"icon,omitempty"`
}

From §5.4.1 (https://www.w3.org/TR/webauthn/#dictionary-pkcredentialentity). PublicKeyCredentialEntity describes a user account, or a WebAuthn Relying Party, with which a public key credential is associated.

type CredentialParameter

type CredentialParameter struct {
	Type      CredentialType                       `json:"type"`
	Algorithm webauthncose.COSEAlgorithmIdentifier `json:"alg"`
}

CredentialParameter is the credential type and algorithm that the relying party wants the authenticator to create

type CredentialType

type CredentialType string

This enumeration defines the valid credential types. It is an extension point; values can be added to it in the future, as more credential types are defined. The values of this enumeration are used for versioning the Authentication Assertion and attestation structures according to the type of the authenticator. See §5.10.3. Credential Descriptor https://www.w3.org/TR/webauthn/#credentialType

const (
	// PublicKeyCredentialType - Currently one credential type is defined, namely "public-key".
	PublicKeyCredentialType CredentialType = "public-key"
)

type Error

type Error struct {
	// Short name for the type of error that has occurred
	Type string `json:"type"`
	// Additional details about the error
	Details string `json:"error"`
	// Information to help debug the error
	DevInfo string `json:"debug"`
}

func (*Error) Error

func (err *Error) Error() string

func (*Error) WithDetails

func (passedError *Error) WithDetails(details string) *Error

func (*Error) WithInfo

func (passedError *Error) WithInfo(info string) *Error

type Extensions

type Extensions interface{}

type KM_KEY_ORIGIN

type KM_KEY_ORIGIN int

*

  • The origin of a key (or pair), i.e. where it was generated. Note that KM_TAG_ORIGIN can be found
  • in either the hardware-enforced or software-enforced list for a key, indicating whether the key
  • is hardware or software-based. Specifically, a key with KM_ORIGIN_GENERATED in the
  • hardware-enforced list is guaranteed never to have existed outide the secure hardware.

type KM_PURPOSE

type KM_PURPOSE int

*

  • Possible purposes of a key (or pair).

type ParsedAssertionResponse

type ParsedAssertionResponse struct {
	CollectedClientData CollectedClientData
	AuthenticatorData   AuthenticatorData
	Signature           []byte
	UserHandle          []byte
}

Parsed form of AuthenticatorAssertionResponse

type ParsedAttestationResponse

type ParsedAttestationResponse struct {
	CollectedClientData CollectedClientData
	AttestationObject   AttestationObject
}

The parsed out version of AuthenticatorAttestationResponse.

type ParsedCredential

type ParsedCredential struct {
	ID   string `cbor:"id"`
	Type string `cbor:"type"`
}

The PublicKeyCredential interface inherits from Credential, and contains

the attributes that are returned to the caller when a new credential

is created, or a new assertion is requested.

type ParsedCredentialAssertionData

type ParsedCredentialAssertionData struct {
	ParsedPublicKeyCredential
	Response ParsedAssertionResponse
	Raw      CredentialAssertionResponse
}

The parsed CredentialAssertionResponse that has been marshalled into a format that allows us to verify the client and authenticator data inside the response

func ParseCredentialRequestResponse

func ParseCredentialRequestResponse(response *http.Request) (*ParsedCredentialAssertionData, error)

Parse the credential request response into a format that is either required by the specification or makes the assertion verification steps easier to complete. This takes an http.Request that contains the assertion response data in a raw, mostly base64 encoded format, and parses the data into manageable structures

func ParseCredentialRequestResponseBody

func ParseCredentialRequestResponseBody(body io.Reader) (*ParsedCredentialAssertionData, error)

Parse the credential request response into a format that is either required by the specification or makes the assertion verification steps easier to complete. This takes an io.Reader that contains the assertion response data in a raw, mostly base64 encoded format, and parses the data into manageable structures

func (*ParsedCredentialAssertionData) Verify

func (p *ParsedCredentialAssertionData) Verify(storedChallenge string, relyingPartyID, relyingPartyOrigin, appID string, verifyUser bool, credentialBytes []byte) error

Follow the remaining steps outlined in §7.2 Verifying an authentication assertion (https://www.w3.org/TR/webauthn/#verifying-assertion) and return an error if there is a failure during each step.

type ParsedCredentialCreationData

type ParsedCredentialCreationData struct {
	ParsedPublicKeyCredential
	Response ParsedAttestationResponse
	Raw      CredentialCreationResponse
}

func ParseCredentialCreationResponse

func ParseCredentialCreationResponse(response *http.Request) (*ParsedCredentialCreationData, error)

func ParseCredentialCreationResponseBody

func ParseCredentialCreationResponseBody(body io.Reader) (*ParsedCredentialCreationData, error)

func (*ParsedCredentialCreationData) Verify

func (pcc *ParsedCredentialCreationData) Verify(storedChallenge string, verifyUser bool, relyingPartyID, relyingPartyOrigin string) error

Verifies the Client and Attestation data as laid out by §7.1. Registering a new credential https://www.w3.org/TR/webauthn/#registering-a-new-credential

type ParsedPublicKeyCredential

type ParsedPublicKeyCredential struct {
	ParsedCredential
	RawID                  []byte                                `json:"rawId"`
	ClientExtensionResults AuthenticationExtensionsClientOutputs `json:"clientExtensionResults,omitempty"`
}

func (ParsedPublicKeyCredential) GetAppID

func (ppkc ParsedPublicKeyCredential) GetAppID(authExt AuthenticationExtensions, credentialAttestationType string) (appID string, err error)

GetAppID takes a AuthenticationExtensions object or nil. It then performs the following checks in order:

1. Check that the Session Data's AuthenticationExtensions has been provided and return a blank appid if it hasn't been. 2. Check that the AuthenticationExtensionsClientOutputs contains the extensions output and return a blank appid if it doesn't. 3. Check that the Credential AttestationType is `fido-u2f` and return a blank appid if it isn't. 4. Check that the AuthenticationExtensionsClientOutputs contains the appid key and return a blank appid if it doesn't. 5. Check that the AuthenticationExtensionsClientOutputs appid is a bool and return an error if it isn't. 6. Check that the appid output is true and return a blank appid if it isn't. 7. Check that the Session Data has an appid extension defined and return an error if it doesn't. 8. Check that the appid extension in Session Data is a string and return an error if it isn't. 9. Return the appid extension value from the Session Data.

type PublicKeyCredential

type PublicKeyCredential struct {
	Credential
	RawID                  URLEncodedBase64                      `json:"rawId"`
	ClientExtensionResults AuthenticationExtensionsClientOutputs `json:"clientExtensionResults,omitempty"`
}

type PublicKeyCredentialCreationOptions

type PublicKeyCredentialCreationOptions struct {
	Challenge              Challenge                `json:"challenge"`
	RelyingParty           RelyingPartyEntity       `json:"rp"`
	User                   UserEntity               `json:"user"`
	Parameters             []CredentialParameter    `json:"pubKeyCredParams,omitempty"`
	AuthenticatorSelection AuthenticatorSelection   `json:"authenticatorSelection,omitempty"`
	Timeout                int                      `json:"timeout,omitempty"`
	CredentialExcludeList  []CredentialDescriptor   `json:"excludeCredentials,omitempty"`
	Extensions             AuthenticationExtensions `json:"extensions,omitempty"`
	Attestation            ConveyancePreference     `json:"attestation,omitempty"`
}

In order to create a Credential via create(), the caller specifies a few parameters in a CredentialCreationOptions object. See §5.4. Options for Credential Creation https://www.w3.org/TR/webauthn/#dictionary-makecredentialoptions

type PublicKeyCredentialRequestOptions

type PublicKeyCredentialRequestOptions struct {
	Challenge          Challenge                   `json:"challenge"`
	Timeout            int                         `json:"timeout,omitempty"`
	RelyingPartyID     string                      `json:"rpId,omitempty"`
	AllowedCredentials []CredentialDescriptor      `json:"allowCredentials,omitempty"`
	UserVerification   UserVerificationRequirement `json:"userVerification,omitempty"` // Default is "preferred"
	Extensions         AuthenticationExtensions    `json:"extensions,omitempty"`
}

The PublicKeyCredentialRequestOptions dictionary supplies get() with the data it needs to generate an assertion. Its challenge member MUST be present, while its other members are OPTIONAL. See §5.5. Options for Assertion Generation https://www.w3.org/TR/webauthn/#assertion-options

func (*PublicKeyCredentialRequestOptions) GetAllowedCredentialIDs

func (a *PublicKeyCredentialRequestOptions) GetAllowedCredentialIDs() [][]byte

type RelyingPartyEntity

type RelyingPartyEntity struct {
	CredentialEntity
	// A unique identifier for the Relying Party entity, which sets the RP ID.
	ID string `json:"id"`
}

From §5.4.2 (https://www.w3.org/TR/webauthn/#sctn-rp-credential-params). The PublicKeyCredentialRpEntity is used to supply additional Relying Party attributes when creating a new credential.

type ResidentKeyRequirement

type ResidentKeyRequirement string

ResidentKeyRequirement https://www.w3.org/TR/webauthn/#dom-authenticatorselectioncriteria-residentkey

const (
	// ResidentKeyRequirementDiscouraged indicates to the client we do not want a discoverable credential. This is the default.
	ResidentKeyRequirementDiscouraged ResidentKeyRequirement = "discouraged"

	// ResidentKeyRequirementPreferred indicates to the client we would prefer a discoverable credential.
	ResidentKeyRequirementPreferred ResidentKeyRequirement = "preferred"

	// ResidentKeyRequirementRequired indicates to the client we require a discoverable credential and that it should
	// fail if the credential does not support this feature.
	ResidentKeyRequirementRequired ResidentKeyRequirement = "required"
)

type SafetyNetResponse

type SafetyNetResponse struct {
	Nonce                      string        `json:"nonce"`
	TimestampMs                int64         `json:"timestampMs"`
	ApkPackageName             string        `json:"apkPackageName"`
	ApkDigestSha256            string        `json:"apkDigestSha256"`
	CtsProfileMatch            bool          `json:"ctsProfileMatch"`
	ApkCertificateDigestSha256 []interface{} `json:"apkCertificateDigestSha256"`
	BasicIntegrity             bool          `json:"basicIntegrity"`
}

type ServerResponse

type ServerResponse struct {
	Status  ServerResponseStatus `json:"status"`
	Message string               `json:"errorMessage"`
}

type ServerResponseStatus

type ServerResponseStatus string
const (
	StatusOk     ServerResponseStatus = "ok"
	StatusFailed ServerResponseStatus = "failed"
)

type TokenBinding

type TokenBinding struct {
	Status TokenBindingStatus `json:"status"`
	ID     string             `json:"id,omitempty"`
}

type TokenBindingStatus

type TokenBindingStatus string
const (
	// Indicates token binding was used when communicating with the
	// Relying Party. In this case, the id member MUST be present.
	Present TokenBindingStatus = "present"
	// Indicates token binding was used when communicating with the
	// negotiated when communicating with the Relying Party.
	Supported TokenBindingStatus = "supported"
	// Indicates token binding not supported
	// when communicating with the Relying Party.
	NotSupported TokenBindingStatus = "not-supported"
)

type URLEncodedBase64

type URLEncodedBase64 []byte

URLEncodedBase64 represents a byte slice holding URL-encoded base64 data. When fields of this type are unmarshaled from JSON, the data is base64 decoded into a byte slice.

func (URLEncodedBase64) MarshalJSON

func (data URLEncodedBase64) MarshalJSON() ([]byte, error)

MarshalJSON base64 encodes a non URL-encoded value, storing the result in the provided byte slice.

func (*URLEncodedBase64) UnmarshalJSON

func (dest *URLEncodedBase64) UnmarshalJSON(data []byte) error

UnmarshalJSON base64 decodes a URL-encoded value, storing the result in the provided byte slice.

type UserEntity

type UserEntity struct {
	CredentialEntity
	// A human-palatable name for the user account, intended only for display.
	// For example, "Alex P. Müller" or "田中 倫". The Relying Party SHOULD let
	// the user choose this, and SHOULD NOT restrict the choice more than necessary.
	DisplayName string `json:"displayName,omitempty"`
	// ID is the user handle of the user account entity. 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](https://www.w3.org/TR/webauthn/#biblio-rfc8266).
	ID []byte `json:"id"`
}

From §5.4.3 (https://www.w3.org/TR/webauthn/#sctn-user-credential-params). The PublicKeyCredentialUserEntity is used to supply additional user account attributes when creating a new credential.

type UserVerificationRequirement

type UserVerificationRequirement string

A WebAuthn Relying Party may require user verification for some of its operations but not for others, and may use this type to express its needs. See §5.10.6. User Verification Requirement Enumeration https://www.w3.org/TR/webauthn/#userVerificationRequirement

const (
	// VerificationRequired User verification is required to create/release a credential
	VerificationRequired UserVerificationRequirement = "required"
	// VerificationPreferred User verification is preferred to create/release a credential
	VerificationPreferred UserVerificationRequirement = "preferred" // This is the default
	// VerificationDiscouraged The authenticator should not verify the user for the credential
	VerificationDiscouraged UserVerificationRequirement = "discouraged"
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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