forked from duo-labs/webauthn
/
login.go
268 lines (218 loc) · 10.4 KB
/
login.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package webauthn
import (
"bytes"
"encoding/base64"
"net/http"
"github.com/duo-labs/webauthn/protocol"
)
// BEGIN REGISTRATION
// These objects help us creat the CredentialCreationOptions
// that will be passed to the authenticator via the user client
// LoginOption is used to provide parameters that modify the default Credential Assertion Payload that is sent to the user.
type LoginOption func(*protocol.PublicKeyCredentialRequestOptions)
// Creates the 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
// (https://www.w3.org/TR/webauthn/#assertion-options). 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 retreived.
func (webauthn *WebAuthn) BeginLogin(user User, opts ...LoginOption) (*protocol.CredentialAssertion, *SessionData, error) {
challenge, err := protocol.CreateChallenge()
if err != nil {
return nil, nil, err
}
credentials := user.WebAuthnCredentials()
if len(credentials) == 0 { // If the user does not have any credentials, we cannot do login
return nil, nil, protocol.ErrBadRequest.WithDetails("Found no credentials for user")
}
var allowedCredentials = make([]protocol.CredentialDescriptor, len(credentials))
for i, credential := range credentials {
var credentialDescriptor protocol.CredentialDescriptor
credentialDescriptor.CredentialID = credential.ID
credentialDescriptor.Type = protocol.PublicKeyCredentialType
allowedCredentials[i] = credentialDescriptor
}
requestOptions := protocol.PublicKeyCredentialRequestOptions{
Challenge: challenge,
Timeout: webauthn.Config.Timeout,
RelyingPartyID: webauthn.Config.RPID,
UserVerification: webauthn.Config.AuthenticatorSelection.UserVerification,
AllowedCredentials: allowedCredentials,
}
for _, setter := range opts {
setter(&requestOptions)
}
newSessionData := SessionData{
Challenge: base64.RawURLEncoding.EncodeToString(challenge),
UserID: user.WebAuthnID(),
AllowedCredentialIDs: requestOptions.GetAllowedCredentialIDs(),
UserVerification: requestOptions.UserVerification,
}
response := protocol.CredentialAssertion{requestOptions}
return &response, &newSessionData, nil
}
//Same as BeginLogin() (standard WebAuthn implemenation), but takes an extra 'data' input and
// uses that as the challenge instead of generating a random byte sequence. Allows for arbitrary
// data to be signed by the HSK without modifying any of the CTAP2 (client to authenticator) code.
func (webauthn *WebAuthn) BeginCast(user User, data string, opts ...LoginOption) (*protocol.CredentialAssertion, *SessionData, error) {
rand, err := protocol.CreateChallenge()
if err != nil {
return nil, nil, err
}
//combine the ballot data and random challenge with a null-byte separator
challenge := append([]byte(data), append([]byte{0}, rand...)...)
//Everything past here is just a copy of BeginLogin()
credentials := user.WebAuthnCredentials()
if len(credentials) == 0 { // If the user does not have any credentials, we cannot do login
return nil, nil, protocol.ErrBadRequest.WithDetails("Found no credentials for user")
}
var allowedCredentials = make([]protocol.CredentialDescriptor, len(credentials))
for i, credential := range credentials {
var credentialDescriptor protocol.CredentialDescriptor
credentialDescriptor.CredentialID = credential.ID
credentialDescriptor.Type = protocol.PublicKeyCredentialType
allowedCredentials[i] = credentialDescriptor
}
requestOptions := protocol.PublicKeyCredentialRequestOptions{
Challenge: challenge,
Timeout: webauthn.Config.Timeout,
RelyingPartyID: webauthn.Config.RPID,
UserVerification: webauthn.Config.AuthenticatorSelection.UserVerification,
AllowedCredentials: allowedCredentials,
}
for _, setter := range opts {
setter(&requestOptions)
}
newSessionData := SessionData{
Challenge: base64.RawURLEncoding.EncodeToString(challenge),
UserID: user.WebAuthnID(),
AllowedCredentialIDs: requestOptions.GetAllowedCredentialIDs(),
UserVerification: requestOptions.UserVerification,
}
response := protocol.CredentialAssertion{requestOptions}
return &response, &newSessionData, nil
}
//Same as FinishLogin() (standard WebAuthn implemenation), but also returns the challenge (ballot data)
// and parsed HSK repsonse structure so that a verifiable ballot structure can be constructed with it.
func (webauthn *WebAuthn) FinishCast(user User, session SessionData, response *http.Request) (*Credential, string, *protocol.ParsedCredentialAssertionData, error) {
parsedResponse, err := protocol.ParseCredentialRequestResponse(response)
if err != nil {
return nil, "", nil, err
}
//veriData := session.Challenge
veriData, err := base64.RawURLEncoding.DecodeString(session.Challenge)
if err != nil {
return nil, "", nil, err
}
veriData = bytes.Split(veriData, []byte{0})[0] //separate the data from the random challenge
cred, err := webauthn.ValidateLogin(user, session, parsedResponse)
return cred, string(veriData), parsedResponse, err
}
//Just calls BeginCast() because the first part of the Verify process is exactly the same on the backend.
// Only difference is the source of 'data' and how the result is handled, which are both taken care of by
// the caller.
func (webauthn *WebAuthn) BeginVerify(user User, data string, opts ...LoginOption) (*protocol.CredentialAssertion, *SessionData, error) {
return webauthn.BeginCast(user, data, opts...)
}
//Just calls FinishCast() because the second part of the Verify process is exactly the same on the backend.
// Only difference is how the result is handled, which is taken care of by the caller.
func (webauthn *WebAuthn) FinishVerify(user User, session SessionData, response *http.Request) (*Credential, string, *protocol.ParsedCredentialAssertionData, error) {
return webauthn.FinishCast(user, session, response)
}
// Updates the allowed credential list with Credential Descripiptors, discussed in §5.10.3
// (https://www.w3.org/TR/webauthn/#dictdef-publickeycredentialdescriptor) with user-supplied values
func WithAllowedCredentials(allowList []protocol.CredentialDescriptor) LoginOption {
return func(cco *protocol.PublicKeyCredentialRequestOptions) {
cco.AllowedCredentials = allowList
}
}
// Request a user verification preference
func WithUserVerification(userVerification protocol.UserVerificationRequirement) LoginOption {
return func(cco *protocol.PublicKeyCredentialRequestOptions) {
cco.UserVerification = userVerification
}
}
// Request additional extensions for assertion
func WithAssertionExtensions(extensions protocol.AuthenticationExtensions) LoginOption {
return func(cco *protocol.PublicKeyCredentialRequestOptions) {
cco.Extensions = extensions
}
}
// Take the response from the client and validate it against the user credentials and stored session data
func (webauthn *WebAuthn) FinishLogin(user User, session SessionData, response *http.Request) (*Credential, error) {
parsedResponse, err := protocol.ParseCredentialRequestResponse(response)
if err != nil {
return nil, err
}
return webauthn.ValidateLogin(user, session, parsedResponse)
}
// ValidateLogin takes a parsed response and validates it against the user credentials and session data
func (webauthn *WebAuthn) ValidateLogin(user User, session SessionData, parsedResponse *protocol.ParsedCredentialAssertionData) (*Credential, error) {
if !bytes.Equal(user.WebAuthnID(), session.UserID) {
return nil, protocol.ErrBadRequest.WithDetails("ID mismatch for User and Session")
}
// Step 1. If the allowCredentials option was given when this authentication ceremony was initiated,
// verify that credential.id identifies one of the public key credentials that were listed in
// allowCredentials.
// NON-NORMATIVE Prior Step: Verify that the allowCredentials for the sesssion are owned by the user provided
userCredentials := user.WebAuthnCredentials()
var credentialFound bool
if len(session.AllowedCredentialIDs) > 0 {
var credentialsOwned bool
for _, userCredential := range userCredentials {
for _, allowedCredentialID := range session.AllowedCredentialIDs {
if bytes.Equal(userCredential.ID, allowedCredentialID) {
credentialsOwned = true
break
}
credentialsOwned = false
}
}
if !credentialsOwned {
return nil, protocol.ErrBadRequest.WithDetails("User does not own all credentials from the allowedCredentialList")
}
for _, allowedCredentialID := range session.AllowedCredentialIDs {
if bytes.Equal(parsedResponse.RawID, allowedCredentialID) {
credentialFound = true
break
}
}
if !credentialFound {
return nil, protocol.ErrBadRequest.WithDetails("User does not own the credential returned")
}
}
// Step 2. If credential.response.userHandle is present, verify that the user identified by this value is
// the owner of the public key credential identified by credential.id.
// This is in part handled by our Step 1
userHandle := parsedResponse.Response.UserHandle
if userHandle != nil && len(userHandle) > 0 {
if !bytes.Equal(userHandle, user.WebAuthnID()) {
return nil, protocol.ErrBadRequest.WithDetails("userHandle and User ID do not match")
}
}
// Step 3. Using credential’s id attribute (or the corresponding rawId, if base64url encoding is inappropriate
// for your use case), look up the corresponding credential public key.
var loginCredential Credential
for _, cred := range userCredentials {
if bytes.Equal(cred.ID, parsedResponse.RawID) {
loginCredential = cred
credentialFound = true
break
}
credentialFound = false
}
if !credentialFound {
return nil, protocol.ErrBadRequest.WithDetails("Unable to find the credential for the returned credential ID")
}
shouldVerifyUser := session.UserVerification == protocol.VerificationRequired
rpID := webauthn.Config.RPID
rpOrigin := webauthn.Config.RPOrigin
// Handle steps 4 through 16
validError := parsedResponse.Verify(session.Challenge, rpID, rpOrigin, shouldVerifyUser, loginCredential.PublicKey)
if validError != nil {
return nil, validError
}
// Handle step 17
loginCredential.Authenticator.UpdateCounter(parsedResponse.Response.AuthenticatorData.Counter)
return &loginCredential, nil
}