-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
u2f_register.go
276 lines (248 loc) · 8.84 KB
/
u2f_register.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
269
270
271
272
273
274
275
276
// Copyright 2021 Gravitational, Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package webauthncli
import (
"bytes"
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/sha256"
"crypto/x509"
"encoding/asn1"
"encoding/base64"
"encoding/binary"
"encoding/json"
"fmt"
"github.com/duo-labs/webauthn/protocol"
"github.com/duo-labs/webauthn/protocol/webauthncose"
"github.com/flynn/u2f/u2ftoken"
"github.com/fxamacker/cbor/v2"
"github.com/gravitational/trace"
log "github.com/sirupsen/logrus"
"github.com/gravitational/teleport/api/client/proto"
wanlib "github.com/gravitational/teleport/lib/auth/webauthn"
)
// U2FRegister implements Register for U2F/CTAP1 devices.
// The implementation is backed exclusively by Go code, making it useful in
// scenarios where libfido2 is unavailable.
func U2FRegister(ctx context.Context, origin string, cc *wanlib.CredentialCreation) (*proto.MFARegisterResponse, error) {
// Preliminary checks, more below.
switch {
case origin == "":
return nil, trace.BadParameter("origin required")
case cc == nil:
return nil, trace.BadParameter("credential creation required")
case cc.Response.RelyingParty.ID == "":
return nil, trace.BadParameter("credential creation missing relying party ID")
}
// U2F/CTAP1 is limited to ES256, check if it's allowed.
ok := false
for _, params := range cc.Response.Parameters {
if params.Type == protocol.PublicKeyCredentialType && params.Algorithm == webauthncose.AlgES256 {
ok = true
break
}
}
if !ok {
return nil, trace.BadParameter("ES256 not allowed by credential parameters")
}
// Can we fulfill the authenticator selection?
if aa := cc.Response.AuthenticatorSelection.AuthenticatorAttachment; aa == protocol.Platform {
return nil, trace.BadParameter("platform attachment required by authenticator selection")
}
if rrk := cc.Response.AuthenticatorSelection.RequireResidentKey; rrk != nil && *rrk {
return nil, trace.BadParameter("resident key required by authenticator selection")
}
if uv := cc.Response.AuthenticatorSelection.UserVerification; uv == protocol.VerificationRequired {
return nil, trace.BadParameter("user verification required by authenticator selection")
}
// Prepare challenge data for the device.
ccdJSON, err := json.Marshal(&CollectedClientData{
Type: string(protocol.CreateCeremony),
Challenge: base64.RawURLEncoding.EncodeToString(cc.Response.Challenge),
Origin: origin,
})
if err != nil {
return nil, trace.Wrap(err)
}
ccdHash := sha256.Sum256(ccdJSON)
rpIDHash := sha256.Sum256([]byte(cc.Response.RelyingParty.ID))
var appIDHash []byte
if value, ok := cc.Response.Extensions[wanlib.AppIDExtension]; ok {
appID := fmt.Sprint(value)
h := sha256.Sum256([]byte(appID))
appIDHash = h[:]
}
// Register!
var rawResp []byte
if err := RunOnU2FDevices(ctx, func(t Token) error {
// Is the authenticator in the credential exclude list?
for _, cred := range cc.Response.CredentialExcludeList {
for _, app := range [][]byte{rpIDHash[:], appIDHash} {
if len(app) == 0 {
continue
}
// Check if the device is already registered by calling
// CheckAuthenticate.
// If the method succeeds then the device knows about the
// {key handle, app} pair, which means it is already registered.
// CheckAuthenticate doesn't require user interaction.
if err := t.CheckAuthenticate(u2ftoken.AuthenticateRequest{
Challenge: ccdHash[:],
Application: app,
KeyHandle: cred.CredentialID,
}); err == nil {
log.Warnf(
"WebAuthn: Authenticator already registered under credential ID %q",
base64.RawURLEncoding.EncodeToString(cred.CredentialID))
return ErrAlreadyRegistered // Remove authenticator from list
}
}
}
var err error
rawResp, err = t.Register(u2ftoken.RegisterRequest{
Challenge: ccdHash[:],
Application: rpIDHash[:],
})
return err
}); err != nil {
return nil, trace.Wrap(err)
}
// Parse U2F response and convert to Webauthn - after that we are done.
resp, err := parseU2FRegistrationResponse(rawResp)
if err != nil {
return nil, trace.Wrap(err)
}
ccr, err := credentialResponseFromU2F(ccdJSON, rpIDHash[:], resp)
if err != nil {
return nil, trace.Wrap(err)
}
return &proto.MFARegisterResponse{
Response: &proto.MFARegisterResponse_Webauthn{
Webauthn: wanlib.CredentialCreationResponseToProto(ccr),
},
}, nil
}
type u2fRegistrationResponse struct {
PubKey *ecdsa.PublicKey
KeyHandle, AttestationCert, Signature []byte
}
func parseU2FRegistrationResponse(resp []byte) (*u2fRegistrationResponse, error) {
// Reference:
// https://fidoalliance.org/specs/fido-u2f-v1.2-ps-20170411/fido-u2f-raw-message-formats-v1.2-ps-20170411.html#registration-response-message-success
// minRespLen is based on:
// 1 byte reserved +
// 65 pubKey +
// 1 key handle length +
// N key handle (at least 1) +
// N attestation cert (at least 1, need to parse to find out) +
// N signature (at least 1, spec says 71-73 bytes, YMMV)
const pubKeyLen = 65
const minRespLen = 1 + pubKeyLen + 4
if len(resp) < minRespLen {
return nil, trace.BadParameter("U2F response too small, got %v bytes, expected at least %v", len(resp), minRespLen)
}
// Reads until the key handle length are guaranteed by the size checking
// above.
buf := resp
if buf[0] != 0x05 {
return nil, trace.BadParameter("invalid reserved byte: %v", buf[0])
}
buf = buf[1:]
// public key
x, y := elliptic.Unmarshal(elliptic.P256(), buf[:pubKeyLen])
if x == nil {
return nil, trace.BadParameter("failed to parse public key")
}
buf = buf[pubKeyLen:]
pubKey := &ecdsa.PublicKey{
Curve: elliptic.P256(),
X: x,
Y: y,
}
// key handle
l := int(buf[0])
buf = buf[1:]
// Size checking resumed from now on.
if len(buf) < l {
return nil, trace.BadParameter("key handle length is %v, but only %v bytes are left", l, len(buf))
}
keyHandle := buf[:l]
buf = buf[l:]
// Parse the certificate to figure out its size, then call
// x509.ParseCertificate with a correctly-sized byte slice.
sig, err := asn1.Unmarshal(buf, &asn1.RawValue{})
if err != nil {
return nil, trace.Wrap(err)
}
// Parse the cert to check that it is valid - we don't actually need the
// parsed cert after it is proved to be well-formed.
attestationCert := buf[:len(buf)-len(sig)]
if _, err := x509.ParseCertificate(attestationCert); err != nil {
return nil, trace.Wrap(err)
}
return &u2fRegistrationResponse{
PubKey: pubKey,
KeyHandle: keyHandle,
AttestationCert: attestationCert,
Signature: sig,
}, nil
}
func credentialResponseFromU2F(ccdJSON, appIDHash []byte, resp *u2fRegistrationResponse) (*wanlib.CredentialCreationResponse, error) {
// Reference:
// https://fidoalliance.org/specs/fido-v2.1-ps-20210615/fido-client-to-authenticator-protocol-v2.1-ps-20210615.html#fig-u2f-compat-makeCredential
pubKeyCBOR, err := wanlib.U2FKeyToCBOR(resp.PubKey)
if err != nil {
return nil, trace.Wrap(err)
}
// Assemble authenticator data.
authData := &bytes.Buffer{}
authData.Write(appIDHash[:])
// Attested credential data present.
// https://www.w3.org/TR/webauthn-2/#attested-credential-data.
authData.WriteByte(byte(protocol.FlagAttestedCredentialData | protocol.FlagUserPresent))
binary.Write(authData, binary.BigEndian, uint32(0)) // counter, zeroed
authData.Write(make([]byte, 16)) // AAGUID, zeroed
binary.Write(authData, binary.BigEndian, uint16(len(resp.KeyHandle))) // L
authData.Write(resp.KeyHandle)
authData.Write(pubKeyCBOR)
// Assemble attestation object
attestationObj, err := cbor.Marshal(&protocol.AttestationObject{
RawAuthData: authData.Bytes(),
// See https://www.w3.org/TR/webauthn-2/#sctn-fido-u2f-attestation.
Format: "fido-u2f",
AttStatement: map[string]interface{}{
"sig": resp.Signature,
"x5c": []interface{}{resp.AttestationCert},
},
})
if err != nil {
return nil, trace.Wrap(err)
}
return &wanlib.CredentialCreationResponse{
PublicKeyCredential: wanlib.PublicKeyCredential{
Credential: wanlib.Credential{
ID: base64.RawURLEncoding.EncodeToString(resp.KeyHandle),
Type: string(protocol.PublicKeyCredentialType),
},
RawID: resp.KeyHandle,
},
AttestationResponse: wanlib.AuthenticatorAttestationResponse{
AuthenticatorResponse: wanlib.AuthenticatorResponse{
ClientDataJSON: ccdJSON,
},
AttestationObject: attestationObj,
},
}, nil
}