warp

package module
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2020 License: MIT Imports: 20 Imported by: 3

README

warp - WebAuthn Relying Party

Build Status GoDoc Go Report Card codecov CII Best Practices Release GitHub

warp is a WebAuthn Relying Party implementation which is intended to be 100% compliant with the W3C WebAuthn Level 1 standard while being HTTP implementation agnostic. It is completely standalone; simply provide your own HTTP server, backend storage and session storage.

Requires Go 1.13+

This library is still pre-v1, and API stability is not guaranteed. The library will adhere to SemVer and Go backward compatibility promises.

Update 2020-04-13 I am about ready to cut a 1.0 release, likely as soon as I finish the TPM attestation format. After running a couple of implementations, I'm fairly confident in the public API as it currently exists. I did look at achieving FIDO2 conformance, but this requires conforming to the FIDO2 Server spec which has some subtle and not-so-subtle changes/requirements on top of WebAuthn. I'll explore adding a FIDO2 compatibility layer in the future either as a part of this library or as a separate library.

Contents

Installation

  1. You must have Go 1.13+ installed.
  2. Use the go get command to bring the library into your workspace:
$ go get github.com/e3b0c442/warp
  1. Import into your code:
import "github.com/e3b0c442/warp"

Quick start

By design, warp is not batteries included. Your application must have the following to use warp:

  1. The ability to marshal and unmarshal JSON,
  2. A session or other backend store to store the challenge data,
  3. A config or other struct which implements the RelyingParty interface,
  4. A user store which implements the User interface, and
  5. A credential store which implements the Credential interface.
Starting registration

The user must be known. This example assumes the session store can infer the user from the request.

import (
    "encoding/json"
    "net/http"
    
    "github.com/e3b0c442/warp"
)

func StartRegistration(w http.ResponseWriter, r *http.Request) {
    //get the user data from a session cookie or similar
    session, err := SessionStore.Get(r)
    if err != nil {
        return http.Error(w, "Bad session data", http.StatusBadRequest)
    }

    //generate a challenge with the user data
    opts, err := warp.StartRegistration(relyingParty, session.User)
    if err != nil {
        return http.Error(w, "Unable to generate challenge", http.StatusInternalServerError)
    }
    //store the challenge for later verification
    session.Data["creation"] = opts
    http.SetCookie(w, session.Cookie)

    //send the challenge to the client
    json.NewEncoder(w).Encode(opts)
}
Finishing registration

The implementation is responsible for parsing an AttestationPublicKeyCredential from the request.

func FinishRegistration(w http.ResponseWriter, r *http.Request) {
    //get the user data and challenge from a session cookie or similar
    session, err := SessionStore.Get(r)
    if err != nil {
        return http.Error(w, "Bad session data", http.StatusBadRequest)
    }

    //get the stored challenge from the session store
    storedOpts, ok := session.Data["creation"]
    if !ok {
        return http.Error(w, "No creation data in session", http.StatusForbidden)
    }
    opts := storedOpts.(PublicKeyCredentialCreationOptions)
    
    //parse the credential sent from the client
    var cred AttestationPublicKeyCredential
    err := json.NewDecoder(r.Body).Decode(&cred)
    if err != nil {
        return http.Error(w, "Error parsing credential", http.StatusBadRequest)
    }

    //verify the credential against the stored challenge
    attestation, err := warp.FinishRegistration(relyingParty, CredentialStore.Find, &opts, &cred)
    if err != nil {
        return http.Error(w, "Credential verification failed", http.StatusUnauthorized)
    }

    //store the returned credential
    err := CredentialStore.Store(session.User, attestation)
    if err != nil {
        return http.Error(w, "Unable to store credential", http.StatusInternalServerError)
    }

    //return success to the client
    http.WriteHeader(http.StatusNoContent)
}
Starting authentication

The user is only required to be provided for second-factor auth, as long as the session can correlate the authentication start and finish calls.

func StartAuthentication(w http.ResponseWriter, r *http.Request) {
    //get or start the session data
    session, err := SessionStore.Get(r)
    if err != nil {
        session = SessionStore.Start(r)
    }

    opts, err := warp.StartAuthentication()
    if err != nil {
        return http.Error(w, "Unable to generate challenge", http.StatusInternalServerError)
    }

    //store the challenge for later verification
    session.Data["request"] = opts
    http.SetCookie(w, session.Cookie)

    //send the challenge to the client
    json.NewEncoder(w).Encode(opts)
}
Finishing authentication

If the user is already known, have the passed UserFinder ignore the ID and just return the known user; otherwise pass a mechanism to look up based on the user handle.

func FinishAuthentication(w http.ResponseWriter, r *http.Request) {
    //get or start the session data
    session, err := SessionStore.Get(r)
    if err != nil {
        return http.Error(w, "Bad session data", http.StatusBadRequest)
    }

    //get the stored challenge from the session store
    storedOpts, ok := session.Data["request"]
    if !ok {
        return http.Error(w, "No request data in session", http.StatusForbidden)
    }
    opts := storedOpts.(PublicKeyCredentialRequestOptions)
    
    //parse the credential sent from the client
    var cred AssertionPublicKeyCredential
    err := json.NewDecoder(r.Body).Decode(&cred)
    if err != nil {
        return http.Error(w, "Error parsing credential", http.StatusBadRequest)
    }

    //verify the credential
    authData, err := warp.FinishAuthentication(relyingParty, func(_ []byte) (warp.User, error) {
        return session.User, nil
    }, &opts, &cred)
    if err != nil {
        return http.Error(w, "Credential verification failed", http.StatusUnauthorized)
    }
    
    //update credential info such as signcount
    err := CredentialStore.Update(authData)
    if err != nil {
        //Implementation can decide whether this is a problem or not
    }

    //return success to the client
    http.WriteHeader(http.StatusNoContent)
}

Design goals

warp was built with the following goals in mind:

  • 100% compliance with the WebAuthn Level 1 specification
  • HTTP implementation agnostic. This library makes no assumptions about the structure or operation of your web application. Use your implementation's canonical method to parse the WebAuthn JSON.
  • No assumptions about application data models. Implement and use the required interfaces wherever is appropriate in your implementation
  • Minimal dependencies outside of the standard library, with those used chosen carefully to keep the dependency tree clean. At the time of this writing, the following external dependencies are used:
  • Simple package structure - just one package to import
  • Structure and member naming parity with the WebAuthn spec, so that you can follow along and understand

Specification coverage

  • Key algorithms:
    • Supported: ES256, ES384, ES512, EdDSA, RS1, RS256, RS384, RS512, PS256, PS384, PS512
    • To be implemented: None planned
  • Attestation formats
    • Supported: packed, fido-u2f, none
    • To be implemented: tpm, android-key, android-safetynet
  • Defined extensions
    • Supported: appid, txAuthSimple, txAuthGeneric
    • To be implemented: authnSel, exts, uvi, loc, uvm, biometricPerfBounds

High level API

WebAuthn relying parties have two responsibilities: managing the registration ceremony, and managing the authentication ceremony. In order to support these ceremonies, interfaces are defined such that the methods will return the required data.

Interfaces
RelyingParty
type RelyingParty interface {
	EntityID() string
	EntityName() string
	EntityIcon() string
	Origin() string
}

RelyingParty contains all of the non-user-specific data required to be stored or configured by the relying party for use during the registration or authentication ceremonies.

  • EntityID() string: Returns the Relying Party ID, which scopes the credential. Credentials can only be used for authentication with the same entity (identified by RP ID) it was registered with. The RP ID must be equal to or a registrable domain suffix of the origin.
  • EntityName() string: A human-palatable name for the Relying Party.
  • EntityIcon() string: A URL which resolves an image associated with the Relying Party. May be the empty string.
  • Origin() string: The fully qualified origin of the Relying Party.
User
type User interface {
	EntityName() string
	EntityIcon() string
	EntityID() []byte
	EntityDisplayName() string
	Credentials() map[string]Credential
}

User contains all of the user-specific information which needs to be stored and provided during the registration and authentication ceremonies.

  • EntityName() string: A human-palatable name for a user account, such as a username or email address
  • EntityIcon() string: A URL which resolves to an image associated with the user. May be the empty string.
  • EntityID() string: The user handle for the account. This should be an opaque byte sequence with a maximum of 64 bytes which does not contain any other identifying information about the user.
  • EntityDisplayName() string: A human-palatable name for a user account, such as a user's full name, intended for display.
  • Credentials() map[string]Credential returns a map of objects which implement the Credential interface. The map is keyed by the base64url-encoded form of the credential ID.
Credential
type Credential interface {
	Owner() User
	CredentialID() []byte
	CredentialPublicKey() []byte
	CredentialSignCount() uint
}

Credential contains the credential-specific information which needs to be stored and provided during the authentication ceremony to verify an authentication assertion.

  • Owner() User: Returns the object implementing the User interface to which this credential belongs.
  • CredentialID() []byte: The raw credential ID.
  • CredentialPublicKey() []byte: The credential public key as returned from FinishRegistration. The key is encoded in the COSE key format, and may vary in size depending on the key algorithm.
  • CredentialSignCount() uint: The stored signature counter. If the credential returns a signature counter that is less than this value, it is evidence of tampering or a duplicated credential, and the authentication ceremony will fail. If you do not wish to verify this, return 0 from this method.
Helper functions
UserFinder
type UserFinder func([]byte) (User, error)

UserFinder defines a function which takes a user handle as an argument and returns an object conforming to the User interface. If the user does not exist in the system, return nil and an appropriate error.

CredentialFinder
type CredentialFinder func([]byte) (Credential, error)

CredentialFinder defines a function which takes a raw credential ID and returns an object conforming to the Credential interface. If the credential does not exist in the system, return nil and an appropriate error.

RegistrationValidator
type RegistrationValidator func(opts *PublicKeyCredentialCreationOptions, cred *AttestationPublicKeyCredential) error

RegistrationValidator defines a function which takes the credential creation options and returned attestation credential, and performs any additional validation desired. Pointers to the two structs are passed so they can be modified if needed. RegistrationValidators are run before any other validations in FinishRegistration

AuthenticationValidator
type AuthenticationValidator func(opts *PublicKeyCredentialRequestOptions, cred *AssertionPublicKeyCredential) error

AuthenticationValidator defines a function which takes the credential request options and returned assertion credential, and performs any additional validation desired. Pointers to the two structs are passed so they can be modified if needed. AuthenticationValidators are run before any other validations in FinishAuthentication.

Registration:

Registration flow

StartRegistration
func StartRegistration(rp RelyingParty, user User, opts ...Option) (*PublicKeyCredentialCreationOptions, error)

StartRegistration begins the registration ceremony by generating a cryptographic challenge and sending it to the client along with information about the user and Relying Party in the form of a PublicKeyCredentialCreationOptions object.

The returned object or its data must be stored in the server-side session cache such that it can be reconstructed to pass to the FinishRegistration function.

Parameters:
  • rp: any value which implements the RelyingParty interface.optional if the default port for the scheme is being used.
  • user: any value which implements the User interface.
  • opts: zero or more Option functions to adjust the PublicKeyCredentialCreationOptions as needed. These do not need to be set, and likely shouldn't unless you know what you are doing. The following function generators are included:
    • Timeout(uint): Sets the client timeout
    • ExcludeCredentials([]PublicKeyCredentialDescriptors): Provides a list of credentials to exclude
    • AuthenticatorSelection(AuthenticatorSelectionCriteria): Sets the criteria for choosing an authenticator
    • Attestation(AttestationConveyancePreference): Sets the preferred attestation conveyance
    • Extensions(...Extension) takes zero or more Extension which can be used to set WebAuthn client extension inputs
Return values:
  • A pointer to a PublicKeyCredentialCreationOptions struct. This value must be marshaled to JSON and returned to the client. It must also be stored in a server-side session cache in order to verify the client's subsequent response. Returns nil on error.
  • An error if there was a problem generating the options struct, or nil on success.
FinishRegistration
func FinishRegistration(rp RelyingParty, credFinder CredentialFinder, opts *PublicKeyCredentialCreationOptions, cred *AttestationPublicKeyCredential, vals ...RegistrationValidator) (*AttestationObject, error)

FinishRegistration completes the registration ceremony, by verifying the public key credential sent by the client against the stored creation options. If the verification is successful, a credential ID and public key are returned which must be stored. It is the responsibility of the implementor to store these and associate with the calling user.

Parameters:
  • rp: An object which implements the RelyingParty interface
  • credFinder: A function conforming to CredentialFinder which is used to check if a credential ID already exists in the system
  • opts: A pointer to the stored PublicKeyCredentialCreationOptions which was previously sent to the client
  • cred: The parsed AttestationPublicKeyCredential that was sent from the client in response to the server challenge
  • vals: Additional custom validations to be performed in addition to those required by the specification
Return values:
  • An *AttestationObject which contains all of the information that may need to be stored to authenticate using the credential
  • An error identifying the cause of the registration failure, or nil on success.
Authentication

Authentication flow

StartAuthentication
func StartAuthentication(opts ...Option) (*PublicKeyCredentialRequestOptions, error)

StartAuthentication starts the authentication ceremony by generating a cryptographic challenge and sending it to the client along with options in the form of a PublicKeyCredentialRequestOptions object.

Parameters:
  • opts: zero or more Option functions to adjust the PublicKeyCredentialRequestOptions as needed. These do not need to be set, and likely shouldn't unless you know what you are doing. The following function generators are included:
    • Timeout(uint): Sets the client timeout
    • RelyingPartyID(string): Adds the explicit relying party ID to the object
    • AllowCredentials([]PublicKeyCredentialDescriptor): Restrict allowed credentials
    • UserVerification(UserVerificationRequirement): Require user verification (PIN, biometric, etc)
Return values:
  • A pointer to a PublicKeyCredentialRequestOptions struct. This value must be marshaled to JSON and returned to the client. It must also be stored in a server-side session cache in order to verify the client's subsequent response. Returns nil on error.
  • An error if there was a problem generating the options struct, or nil on success.
FinishAuthentication
func FinishAuthentication(rp RelyingParty, userFinder UserFinder, opts *PublicKeyCredentialRequestOptions, cred *AssertionPublicKeyCredential, vals ...AuthenticationValidator) (*AuthenticatorData, error)

FinishAuthentication completes the authentication ceremony by verifying the signed challenge and credential data with the stored public key for the credential. If the verification is successful, it returns a new signature counter value to be stored, and a nil error. Otherwise, 0 and an error describing the failure are returned. It is the responsibility of the caller to store the updated signature counter if they are choosing to verify this.

Parameters:
  • rp: An object implementing the RelyingParty interface.
  • userFinder: A function conforming to the UserFinder type which accepts a user handle as an argument and returns an object implementing the User interface. If the caller is not implementing the passwordless/single factor flow, the function can ignore the user handle and just return the already-known User.
  • opts: A pointer to the stored PublicKeyCredentialRequestOptions which was previously sent to the client.
  • cred: The parsed AssertionPublicKeyCredential that was sent from the client in response to the server challenge.
  • vals: Additional custom validations to be performed in addition to those required by the specification
Return values:
  • An *AuthenticatorData which contains information about the credential used to authenticate; may be used to update stored credential data such as sign count.
  • An error if there was a problem verifying the user, or nil on success

Contributing

Please read CONTRIBUTING.md for instructions on contributing to the project.

Contributors

Thanks to the following who have made contributions to the software or its documentation.

@virtualandy

Security vulnerabilities

Given the impact of the authentication flow on the overall security of a project, security vulnerabilities will be taken extremely seriously.

If you discover a security vulnerability, please send an email to security@e3b0c442.io instead of opening an issue. Security vulnerabilities will be resolved within 14 days whenever feasible and the reporter and issue details will be acknowledged in the changelog once the code resolving the issue is released.

License

Copyright (c) 2020 Nick Meyer and contributors.

This project is released under the MIT license

Documentation

Overview

Package warp is a WebAuthn Relying Party implementation for Go that is not attached to net/http. Bring your own everything, parse the standards-compliant JSON, and pass into the appropriate functions. For full documentation visit https://github.com/e3b0c442/warp

Index

Constants

View Source
const (
	ExtensionAppID               = "appid"
	ExtensionTxAuthSimple        = "txAuthSimple"
	ExtensionTxAuthGeneric       = "txAuthGeneric"
	ExtensionAuthnSel            = "authnSel"
	ExtensionExts                = "exts"
	ExtensionUVI                 = "uvi"
	ExtensionLoc                 = "loc"
	ExtensionUVM                 = "uvm"
	ExtensionBiometricPerfBounds = "biometricPerfBounds"
)

Identifiers for defined extensions

View Source
const (
	StatusSupported = "supported"
	StatusPresent   = "present"
)

enum values for the TokenBindingStatus type

Variables

View Source
var (
	ErrDecodeAttestedCredentialData = Error{/* contains filtered or unexported fields */}
	ErrDecodeAuthenticatorData      = Error{/* contains filtered or unexported fields */}
	ErrDecodeCOSEKey                = Error{/* contains filtered or unexported fields */}
	ErrECDAANotSupported            = Error{/* contains filtered or unexported fields */}
	ErrEncodeAttestedCredentialData = Error{/* contains filtered or unexported fields */}
	ErrEncodeAuthenticatorData      = Error{/* contains filtered or unexported fields */}
	ErrGenerateChallenge            = Error{/* contains filtered or unexported fields */}
	ErrMarshalAttestationObject     = Error{/* contains filtered or unexported fields */}
	ErrOption                       = Error{/* contains filtered or unexported fields */}
	ErrNotImplemented               = Error{/* contains filtered or unexported fields */}
	ErrUnmarshalAttestationObject   = Error{/* contains filtered or unexported fields */}
	ErrVerifyAttestation            = Error{/* contains filtered or unexported fields */}
	ErrVerifyAuthentication         = Error{/* contains filtered or unexported fields */}
	ErrVerifyClientExtensionOutput  = Error{/* contains filtered or unexported fields */}
	ErrVerifyRegistration           = Error{/* contains filtered or unexported fields */}
	ErrVerifySignature              = Error{/* contains filtered or unexported fields */}
)

Categorical top-level errors

AuthenticationExtensionValidators is a map to all extension validators for extensions allowed during the authentication ceremony

View Source
var ChallengeLength = 32

ChallengeLength represents the size of the generated challenge. Must be greater than 16.

View Source
var RegistrationExtensionValidators map[string]RegistrationValidator = map[string]RegistrationValidator{}

RegistrationExtensionValidators is a map to all extension validators for extensions allowed during the registration ceremony

Functions

func DecodePublicKey

func DecodePublicKey(coseKey *COSEKey) (crypto.PublicKey, error)

DecodePublicKey parses a crypto.PublicKey from a COSEKey

func VerifyFIDOU2FAttestationStatement added in v0.3.0

func VerifyFIDOU2FAttestationStatement(attStmt []byte, rawAuthData []byte, clientDataHash [32]byte) error

VerifyFIDOU2FAttestationStatement verifies that an attestation statement of type "fido-u2f" is valid

func VerifyNoneAttestationStatement

func VerifyNoneAttestationStatement(attStmt []byte, _ []byte, _ [32]byte) error

VerifyNoneAttestationStatement verifies that at attestation statement of type "none" is valid

func VerifyPackedAttestationStatement added in v0.4.0

func VerifyPackedAttestationStatement(attStmt []byte, rawAuthData []byte, clientDataHash [32]byte) error

VerifyPackedAttestationStatement verifies that an attestation statement of type "packed" is valid

func VerifySignature

func VerifySignature(rawKey cbor.RawMessage, message, sig []byte) error

VerifySignature verifies a signature using a provided COSEKey, message, and signature

Types

type AssertionPublicKeyCredential

type AssertionPublicKeyCredential struct {
	PublicKeyCredential
	Response AuthenticatorAssertionResponse `json:"response"`
}

AssertionPublicKeyCredential is the PublicKeyCredential returned from a call to navigator.credentials.get(), with an AuthenticatorAssertionResponse

type AttestationConveyancePreference

type AttestationConveyancePreference string

AttestationConveyancePreference may be used by relying parties to specify their preference regarding attestation conveyance during credential generation.

const (
	ConveyanceNone     AttestationConveyancePreference = "none"
	ConveyanceIndirect AttestationConveyancePreference = "indirect"
	ConveyanceDirect   AttestationConveyancePreference = "direct"
)

enum values for AttestationConveyancePreference type

type AttestationObject

type AttestationObject struct {
	AuthData AuthenticatorData
	Fmt      AttestationStatementFormat
	AttStmt  cbor.RawMessage
}

AttestationObject contains both authenticator data and an attestation statement.

func FinishRegistration

FinishRegistration completes the registration ceremony by validating the provided public key credential, and returns the attestation object containing all authenticator data that should be stored.

func (*AttestationObject) MarshalBinary added in v0.2.0

func (ao *AttestationObject) MarshalBinary() (data []byte, err error)

MarshalBinary implements the BinaryMarshaler interface, and returns the raw CBOR encoding of AttestationObject

func (*AttestationObject) UnmarshalBinary added in v0.2.0

func (ao *AttestationObject) UnmarshalBinary(data []byte) error

UnmarshalBinary implements the BinaryUnmarshaler interface, and populates an AttestationObject with the provided raw CBOR

type AttestationPublicKeyCredential

type AttestationPublicKeyCredential struct {
	PublicKeyCredential
	Response AuthenticatorAttestationResponse `json:"response"`
}

AttestationPublicKeyCredential is the PublicKeyCredential returned from a call to navigator.credentials.create(), with an AuthenticatorAttestationResponse

type AttestationStatementFormat

type AttestationStatementFormat string

AttestationStatementFormat is the identifier for an attestation statement format.

const (
	AttestationFormatPacked           AttestationStatementFormat = "packed"
	AttestationFormatTPM              AttestationStatementFormat = "tpm"
	AttestationFormatAndroidKey       AttestationStatementFormat = "android-key"
	AttestationFormatAndroidSafetyNet AttestationStatementFormat = "android-safetynet"
	AttestationFormatFidoU2F          AttestationStatementFormat = "fido-u2f"
	AttestationFormatNone             AttestationStatementFormat = "none"
)

enum values for AttestationStatementFormat

func SupportedAttestationStatementFormats

func SupportedAttestationStatementFormats() []AttestationStatementFormat

SupportedAttestationStatementFormats returns the list of attestation formats currently supported by the library

func (AttestationStatementFormat) Valid

func (asf AttestationStatementFormat) Valid() error

Valid determines if the Attestation Format Identifier is a valid value

type AttestedCredentialData

type AttestedCredentialData struct {
	AAGUID              [16]byte
	CredentialID        []byte
	CredentialPublicKey cbor.RawMessage
}

AttestedCredentialData is a variable-length byte array added to the authenticator data when generating an attestation object for a given credential. §6.4.1

func (*AttestedCredentialData) Decode

func (acd *AttestedCredentialData) Decode(data io.Reader) error

Decode decodes the attested credential data from a stream

func (*AttestedCredentialData) Encode added in v0.2.0

func (acd *AttestedCredentialData) Encode(w io.Writer) error

Encode encodes the attested credential data to a stream

type AuthenticationExtensionsClientInputs

type AuthenticationExtensionsClientInputs map[string]interface{}

AuthenticationExtensionsClientInputs contains the client extension input values for zero or more extensions. §5.7

func BuildExtensions

func BuildExtensions(exts ...Extension) AuthenticationExtensionsClientInputs

BuildExtensions builds the extension map to be added to the options object

type AuthenticationExtensionsClientOutputs

type AuthenticationExtensionsClientOutputs map[string]interface{}

AuthenticationExtensionsClientOutputs containing the client extension output values for zero or more WebAuthn extensions. §5.8

type AuthenticationValidator added in v0.5.0

type AuthenticationValidator func(opts *PublicKeyCredentialRequestOptions, cred *AssertionPublicKeyCredential) error

AuthenticationValidator is a function that can do additional custom validations against the AssertionPublicKeyCredential return by the client and the PublicKeyCredentialRequestOptions sent to the client. Returning a non-nil error ends the authentication ceremony unsuccessfully.

func ValidateAppID added in v0.5.0

func ValidateAppID() AuthenticationValidator

ValidateAppID validates the appid extension and updates the credential request options with the valid AppID as needed

func ValidateTxAuthGeneric added in v0.6.0

func ValidateTxAuthGeneric() AuthenticationValidator

ValidateTxAuthGeneric validates the txAuthGeneric extension

func ValidateTxAuthSimple added in v0.6.0

func ValidateTxAuthSimple() AuthenticationValidator

ValidateTxAuthSimple validates the txAuthSimple extension

type AuthenticatorAssertionResponse

type AuthenticatorAssertionResponse struct {
	AuthenticatorResponse
	AuthenticatorData []byte `json:"authenticatorData"`
	Signature         []byte `json:"signature"`
	UserHandle        []byte `json:"userHandle"`
}

AuthenticatorAssertionResponse represents an authenticator's response to a client’s request for generation of a new authentication assertion given the WebAuthn Relying Party's challenge and OPTIONAL list of credentials it is aware of.

type AuthenticatorAttachment

type AuthenticatorAttachment string

AuthenticatorAttachment describes authenticators' attachment modalities.

const (
	AttachmentPlatform      AuthenticatorAttachment = "platform"
	AttachmentCrossPlatform AuthenticatorAttachment = "cross-platform"
)

enum values for AuthenticatorAttachment type

type AuthenticatorAttestationResponse

type AuthenticatorAttestationResponse struct {
	AuthenticatorResponse
	AttestationObject []byte `json:"attestationObject"`
}

AuthenticatorAttestationResponse represents the authenticator's response to a client’s request for the creation of a new public key credential.

type AuthenticatorData

type AuthenticatorData struct {
	RPIDHash               [32]byte
	UP                     bool
	UV                     bool
	AT                     bool
	ED                     bool
	SignCount              uint32
	AttestedCredentialData AttestedCredentialData
	Extensions             map[string]interface{}
}

AuthenticatorData encodes contextual bindings made by the authenticator.

func FinishAuthentication

FinishAuthentication completes the authentication ceremony by validating the provided credential assertion against the stored public key.

func (*AuthenticatorData) Decode

func (ad *AuthenticatorData) Decode(data io.Reader) error

Decode decodes the ad hoc AuthenticatorData structure

func (*AuthenticatorData) Encode added in v0.2.0

func (ad *AuthenticatorData) Encode(w io.Writer) error

Encode encodes the AuthenticatorData structure into the raw binary authData

func (*AuthenticatorData) MarshalBinary added in v0.2.0

func (ad *AuthenticatorData) MarshalBinary() (data []byte, err error)

MarshalBinary implements the BinaryMarshaler interface, and returns the raw binary authData

func (*AuthenticatorData) UnmarshalBinary added in v0.2.0

func (ad *AuthenticatorData) UnmarshalBinary(data []byte) error

UnmarshalBinary implements the BinaryUnmarshaler interface, and populates an AuthenticatorData with the provided raw authData

type AuthenticatorResponse

type AuthenticatorResponse struct {
	ClientDataJSON []byte `json:"clientDataJSON"`
}

AuthenticatorResponse is the is the basic authenticator response

type AuthenticatorSelectionCriteria

type AuthenticatorSelectionCriteria struct {
	AuthenticatorAttachment AuthenticatorAttachment     `json:"authenticatorAttachment,omitempty"`
	RequireResidentKey      bool                        `json:"requireResidentKey,omitempty"`
	UserVerification        UserVerificationRequirement `json:"userVerification,omitempty"`
}

AuthenticatorSelectionCriteria may be used to specify their requirements regarding authenticator attributes.

type AuthenticatorTransport

type AuthenticatorTransport string

AuthenticatorTransport defines hints as to how clients might communicate with a particular authenticator in order to obtain an assertion for a specific credential.

const (
	TransportUSB      AuthenticatorTransport = "usb"
	TransportNFC      AuthenticatorTransport = "nfc"
	TransportBLE      AuthenticatorTransport = "ble"
	TransportInternal AuthenticatorTransport = "internal"
)

enum values for AuthenticatorTransport type

type CMCredential

type CMCredential struct {
	ID   string `json:"id"`
	Type string `json:"type"`
}

CMCredential is the basic Credential Management Credential type that is inherited by PublicKeyCredential

type COSEAlgorithmIdentifier

type COSEAlgorithmIdentifier int

COSEAlgorithmIdentifier is a number identifying a cryptographic algorithm

const (
	AlgorithmRS1   COSEAlgorithmIdentifier = -65535
	AlgorithmRS512 COSEAlgorithmIdentifier = -259
	AlgorithmRS384 COSEAlgorithmIdentifier = -258
	AlgorithmRS256 COSEAlgorithmIdentifier = -257
	AlgorithmPS512 COSEAlgorithmIdentifier = -39
	AlgorithmPS384 COSEAlgorithmIdentifier = -38
	AlgorithmPS256 COSEAlgorithmIdentifier = -37
	AlgorithmES512 COSEAlgorithmIdentifier = -36
	AlgorithmES384 COSEAlgorithmIdentifier = -35
	AlgorithmEdDSA COSEAlgorithmIdentifier = -8
	AlgorithmES256 COSEAlgorithmIdentifier = -7
)

enum values for COSEAlgorithmIdentifier type

func SupportedKeyAlgorithms

func SupportedKeyAlgorithms() []COSEAlgorithmIdentifier

SupportedKeyAlgorithms returns the list of key algorithms currently supported by the library

type COSEEllipticCurve

type COSEEllipticCurve int

COSEEllipticCurve is a number identifying an elliptic curve

const (
	CurveP256 COSEEllipticCurve = 1
	CurveP384 COSEEllipticCurve = 2
	CurveP521 COSEEllipticCurve = 3
)

enum values for COSEEllipticCurve type

type COSEKey

type COSEKey struct {
	Kty       int             `cbor:"1,keyasint,omitempty"`
	Kid       []byte          `cbor:"2,keyasint,omitempty"`
	Alg       int             `cbor:"3,keyasint,omitempty"`
	KeyOpts   int             `cbor:"4,keyasint,omitempty"`
	IV        []byte          `cbor:"5,keyasint,omitempty"`
	CrvOrNOrK cbor.RawMessage `cbor:"-1,keyasint,omitempty"` // K for symmetric keys, Crv for elliptic curve keys, N for RSA modulus
	XOrE      cbor.RawMessage `cbor:"-2,keyasint,omitempty"` // X for curve x-coordinate, E for RSA public exponent
	Y         cbor.RawMessage `cbor:"-3,keyasint,omitempty"` // Y for curve y-cooridate
	D         []byte          `cbor:"-4,keyasint,omitempty"`
}

COSEKey represents a key decoded from COSE format.

type COSEKeyType

type COSEKeyType int

COSEKeyType is a number identifying a key type

const (
	KeyTypeOKP COSEKeyType = 1
	KeyTypeEC2 COSEKeyType = 2
	KeyTypeRSA COSEKeyType = 3
)

enum values for COSEKeyType type

type CollectedClientData

type CollectedClientData struct {
	Type         string        `json:"type"`
	Challenge    string        `json:"challenge"`
	Origin       string        `json:"origin"`
	TokenBinding *TokenBinding `json:"tokenBinding,omitempty"`
}

CollectedClientData represents the contextual bindings of both the WebAuthn Relying Party and the client.

type Credential

type Credential interface {
	Owner() User
	CredentialSignCount() uint
	CredentialID() []byte
	CredentialPublicKey() []byte
}

Credential defines functions which return data required about the stored credentials

type CredentialCreationOptions

type CredentialCreationOptions struct {
	PublicKey PublicKeyCredentialCreationOptions `json:"publicKey"`
}

CredentialCreationOptions specifies the parameters to create a credential

type CredentialFinder

type CredentialFinder func([]byte) (Credential, error)

CredentialFinder defines a function which takes a credential ID as a parameter and returns an object which implements the Credential interface and an error

type CredentialRequestOptions

type CredentialRequestOptions struct {
	PublicKey PublicKeyCredentialRequestOptions `json:"publicKey"`
}

CredentialRequestOptions specifies the parameters to retrieve a credential

type Error

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

Error represents an error in a WebAuthn relying party operation

func NewError

func NewError(fmStr string, els ...interface{}) Error

NewError returns a new Error with a custom message

func (Error) Error

func (e Error) Error() string

Error implements the error interface

func (Error) Is

func (e Error) Is(target error) bool

Is establishes equality for error types

func (Error) Unwrap

func (e Error) Unwrap() error

Unwrap allows for error unwrapping

func (Error) Wrap

func (e Error) Wrap(err error) Error

Wrap returns a new error which contains the provided error wrapped with this error

type Extension

Extension defines an extension to a creation options or request options object

func UseAppID

func UseAppID(appID string) Extension

UseAppID adds the appid extension to the extensions object

func UseTxAuthGeneric added in v0.6.0

func UseTxAuthGeneric(contentType string, content []byte) Extension

UseTxAuthGeneric adds the txAuthGeneric extension to the extensions object

func UseTxAuthSimple added in v0.6.0

func UseTxAuthSimple(txAuthSimple string) Extension

UseTxAuthSimple adds the txAuthSimple extension to the extensions object

type FIDOU2FAttestationStatement added in v0.3.0

type FIDOU2FAttestationStatement struct {
	X5C [][]byte `cbor:"x5c"`
	Sig []byte   `cbor:"sig"`
}

FIDOU2FAttestationStatement represents a decoded attestation statement of type "fido-u2f"

type Option

type Option func(interface{}) error

Option is a function that can be passed as a parameter to StartRegistration or StartAuthentication functions which adjusts the final options object. Options must typecheck for a pointer to PublicKeyCredentialCreationOptions or PublicKeyCredentialRequestOptions

func AllowCredentials

func AllowCredentials(creds []PublicKeyCredentialDescriptor) Option

AllowCredentials returns an option that adds a list of allowed credentials to the credential request object

func Attestation

func Attestation(pref AttestationConveyancePreference) Option

Attestation returns an option that adds an attestation conveyance preference to the creation options object

func AuthenticatorSelection

func AuthenticatorSelection(criteria AuthenticatorSelectionCriteria) Option

AuthenticatorSelection returns an option that adds authenticator selection criteria to the creation options object

func ExcludeCredentials

func ExcludeCredentials(creds []PublicKeyCredentialDescriptor) Option

ExcludeCredentials returns an option that adds a list of credentials to exclude to the creation options object

func Extensions

func Extensions(exts ...Extension) Option

Extensions returns an option that adds one or more extensions to the creation options object or request options object

func RelyingPartyID

func RelyingPartyID(rpID string) Option

RelyingPartyID returns an option that specifies the Relying Party ID in the credential request object

func Timeout

func Timeout(timeout uint) Option

Timeout returns an option that adds a custom timeout to the credential creation options or credential request options object

func UserVerification

func UserVerification(req UserVerificationRequirement) Option

UserVerification returns an option that adds the relying party argument for user verification to the credential request object

type PackedAttestationStatement added in v0.4.0

type PackedAttestationStatement struct {
	Alg        COSEAlgorithmIdentifier `cbor:"alg"`
	Sig        []byte                  `cbor:"sig"`
	X5C        [][]byte                `cbor:"x5c"`
	ECDAAKeyID []byte                  `cbor:"ecdaaKeyId"`
}

PackedAttestationStatement represents a decoded attestation statement of type "packed"

type PublicKeyCredential

type PublicKeyCredential struct {
	CMCredential
	RawID      []byte                                `json:"rawId"`
	Extensions AuthenticationExtensionsClientOutputs `json:"extensions,omitempty"`
}

PublicKeyCredential 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 PublicKeyCredentialCreationOptions

type PublicKeyCredentialCreationOptions struct {
	RP                     PublicKeyCredentialRPEntity          `json:"rp"`
	User                   PublicKeyCredentialUserEntity        `json:"user"`
	Challenge              []byte                               `json:"challenge"`
	PubKeyCredParams       []PublicKeyCredentialParameters      `json:"pubKeyCredParams"`
	Timeout                uint                                 `json:"timeout,omitempty"`
	ExcludeCredentials     []PublicKeyCredentialDescriptor      `json:"excludeCredentials,omitempty"`
	AuthenticatorSelection *AuthenticatorSelectionCriteria      `json:"authenticatorSelection,omitempty"`
	Attestation            AttestationConveyancePreference      `json:"attestation,omitempty"`
	Extensions             AuthenticationExtensionsClientInputs `json:"extensions,omitempty"`
}

PublicKeyCredentialCreationOptions represent options for credential creation

func StartRegistration

func StartRegistration(
	rp RelyingParty,
	user User,
	opts ...Option,
) (
	*PublicKeyCredentialCreationOptions,
	error,
)

StartRegistration starts the registration ceremony by creating a credential creation options object to be sent to the client.

type PublicKeyCredentialDescriptor

type PublicKeyCredentialDescriptor struct {
	Type       PublicKeyCredentialType  `json:"type"`
	ID         []byte                   `json:"id"`
	Transports []AuthenticatorTransport `json:"transports,omitempty"`
}

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

type PublicKeyCredentialEntity

type PublicKeyCredentialEntity struct {
	Name string `json:"name"`
	Icon string `json:"icon,omitempty"`
}

PublicKeyCredentialEntity describes a user account, or a WebAuthn Relying Party, which a public key credential is associated with or scoped to, respectively.

type PublicKeyCredentialParameters

type PublicKeyCredentialParameters struct {
	Type PublicKeyCredentialType `json:"type"`
	Alg  COSEAlgorithmIdentifier `json:"alg"`
}

PublicKeyCredentialParameters is used to supply additional parameters when creating a new credential.

func SupportedPublicKeyCredentialParameters

func SupportedPublicKeyCredentialParameters() []PublicKeyCredentialParameters

SupportedPublicKeyCredentialParameters enumerates the credential types and algorithms currently supported by this library.

type PublicKeyCredentialRPEntity

type PublicKeyCredentialRPEntity struct {
	PublicKeyCredentialEntity
	ID string `json:"id,omitempty"`
}

PublicKeyCredentialRPEntity is used to supply additional Relying Party attributes when creating a new credential.

type PublicKeyCredentialRequestOptions

type PublicKeyCredentialRequestOptions struct {
	Challenge        []byte                               `json:"challenge"`
	Timeout          uint                                 `json:"timeout,omitempty"`
	RPID             string                               `json:"rpId,omitempty"`
	AllowCredentials []PublicKeyCredentialDescriptor      `json:"allowCredentials,omitempty"`
	UserVerification UserVerificationRequirement          `json:"userVerification,omitempty"`
	Extensions       AuthenticationExtensionsClientInputs `json:"extensions,omitempty"`
}

PublicKeyCredentialRequestOptions supplies get() with the data it needs to generate an assertion.

func StartAuthentication

func StartAuthentication(
	opts ...Option,
) (
	*PublicKeyCredentialRequestOptions,
	error,
)

StartAuthentication starts the authentication ceremony by creating a credential request options object to be sent to the client

type PublicKeyCredentialType

type PublicKeyCredentialType string

PublicKeyCredentialType defines the valid credential types.

const (
	PublicKey PublicKeyCredentialType = "public-key"
)

enum values for PublicKeyCredentialType type

type PublicKeyCredentialUserEntity

type PublicKeyCredentialUserEntity struct {
	PublicKeyCredentialEntity
	ID          []byte `json:"id"`
	DisplayName string `json:"displayName"`
}

PublicKeyCredentialUserEntity is used to supply additional user account attributes when creating a new credential.

type RegistrationValidator added in v0.5.0

type RegistrationValidator func(opts *PublicKeyCredentialCreationOptions, cred *AttestationPublicKeyCredential) error

RegistrationValidator is a function that can do additional custom validations against the AttestationPublicKeyCredential returned by the client and the PublicKeyCredentialCreationOptions sent to the client. Returning a non-nil error ends the registration ceremony unsuccessfully.

type RelyingParty

type RelyingParty interface {
	EntityID() string
	EntityName() string
	EntityIcon() string
	Origin() string
}

RelyingParty defines functions which return data required about the Relying Party in order to perform WebAuthn transactions.

type TokenBinding

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

TokenBinding contains information about the state of the Token Binding protocol used when communicating with the Relying Party.

type TokenBindingStatus

type TokenBindingStatus string

TokenBindingStatus represents a token binding status value.

type User

type User interface {
	EntityName() string
	EntityIcon() string
	EntityID() []byte
	EntityDisplayName() string
	Credentials() map[string]Credential
}

User defines functions which return data required about the authenticating user in order to perform WebAuthn transactions.

type UserFinder

type UserFinder func([]byte) (User, error)

UserFinder defines a function which takes a user handle as a parameter and returns an object which implements the User interface and an error

type UserVerificationRequirement

type UserVerificationRequirement string

UserVerificationRequirement describes relying party user verification requirements

const (
	VerificationRequired    UserVerificationRequirement = "required"
	VerificationPreferred   UserVerificationRequirement = "preferred"
	VerificationDiscouraged UserVerificationRequirement = "discouraged"
)

enum values for UserVerificationRequirement type

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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