-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfido20.go
623 lines (539 loc) · 15.2 KB
/
fido20.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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
package main
import (
cbor "bitbucket.org/bodhisnarkva/cbor/go"
"bytes"
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"encoding/base64"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"github.com/google/uuid"
"github.com/square/go-jose"
"strings"
"sync"
)
type (
Flag byte
Authenticator interface {
MakeCredential(rpId string,
clientDataHash []byte,
relyingParty *PublicKeyCredentialEntity,
user *PublicKeyCredentialUserEntity,
normalizedParameters []map[string]string,
excludeList [][]byte,
extensions map[string]interface{},
requireResidentKey bool) (attestationObject []byte, err error)
GetAssertion(rpId string,
clientDataHash []byte,
whiteList [][]byte,
extensions map[string]interface{}) (identifier, authenticatorData, signature []byte, err error)
}
Credential interface {
Identifier() []byte
RelyingParty() *PublicKeyCredentialEntity
User() *PublicKeyCredentialUserEntity
Serialise() ([]byte, error)
}
CredentialStorage interface {
Store(Credential) error
LoadAll() [][]byte
AAGUID() uuid.UUID
}
CredentialSelector func([]Credential) Credential
CredentialApprover func(Credential) bool
authenticator struct {
sync.RWMutex
sorage CredentialStorage
aauid uuid.UUID
counter uint32
credentials map[string]*publicCredentialHandler
selector CredentialSelector
approver CredentialApprover
}
publicCredentialHandler struct {
idb []byte
Id string `json:"id"`
Rp *PublicKeyCredentialEntity `json:"rp"`
UserEntity *PublicKeyCredentialUserEntity `json:"user"`
PrivateKey jose.JsonWebKey `json:"key"`
}
)
const (
TUP Flag = 1 << iota
UV
RES2
RES3
RES4
RES5
AT
ED
)
func (c *publicCredentialHandler) Identifier() []byte {
return c.idb
}
func (c *publicCredentialHandler) identity() string {
if c.Id == "" {
c.Id = base64.RawURLEncoding.EncodeToString(c.idb)
}
return c.Id
}
func (c *publicCredentialHandler) RelyingParty() *PublicKeyCredentialEntity {
return c.Rp
}
func (c *publicCredentialHandler) User() *PublicKeyCredentialUserEntity {
return c.UserEntity
}
func (c *publicCredentialHandler) marshalPublicCredential() ([]byte, error) {
switch key := c.PrivateKey.Key.(type) {
case *ecdsa.PrivateKey:
if key.Curve == nil || key.X == nil || key.Y == nil || key.D == nil {
return nil, errors.New("Invalid EC Key")
}
//"ES256" / "ES384" / "ES512"
return cbor.Dumps(map[string]interface{}{
"alg": c.PrivateKey.Algorithm,
"x": key.PublicKey.X.Bytes(),
"y": key.PublicKey.Y.Bytes(),
})
case *rsa.PrivateKey:
if key.N == nil || key.E == 0 || key.D == nil || len(key.Primes) < 2 {
return nil, errors.New("Invalid RSA Key")
}
//"RS256" / "RS384" / "RS512" / "PS256" / "PS384" / "PS512"
return cbor.Dumps(map[string]interface{}{
"alg": c.PrivateKey.Algorithm,
"n": key.PublicKey.N.Bytes(),
"e": uint64(key.PublicKey.E),
})
default:
return nil, fmt.Errorf("Unsupported privateKey %T", c.PrivateKey.Key)
}
}
func (c *publicCredentialHandler) Serialise() ([]byte, error) {
return json.MarshalIndent(*c, "", " ")
}
func (k *publicCredentialHandler) deSerialise(data []byte) (err error) {
if data != nil && len(data) > 32 {
err = json.Unmarshal(data, k)
if err == nil {
k.idb, err = base64.RawURLEncoding.DecodeString(k.Id)
}
} else {
err = errors.New("Invalid input")
}
return
}
func (c *publicCredentialHandler) sign(payload []byte) ([]byte, *string, error) {
switch key := c.PrivateKey.Key.(type) {
case *ecdsa.PrivateKey:
var expectedBitSize int
var hash crypto.Hash
switch c.PrivateKey.Algorithm {
case "ES256":
expectedBitSize = 256
hash = crypto.SHA256
case "ES384":
expectedBitSize = 384
hash = crypto.SHA384
case "ES512":
expectedBitSize = 521
hash = crypto.SHA512
}
curveBits := key.Curve.Params().BitSize
if expectedBitSize != curveBits {
return nil, nil, fmt.Errorf("expected %d bit key, got %d bits instead", expectedBitSize, curveBits)
}
hasher := hash.New()
// According to documentation, Write() on hash never fails
_, _ = hasher.Write(payload)
hashed := hasher.Sum(nil)
r, s, err := ecdsa.Sign(rand.Reader, key, hashed)
if err != nil {
return nil, nil, err
}
keyBytes := curveBits / 8
if curveBits%8 > 0 {
keyBytes += 1
}
// We serialize the outpus (r and s) into big-endian byte arrays and pad
// them with zeros on the left to make sure the sizes work out. Both arrays
// must be keyBytes long, and the output must be 2*keyBytes long.
rBytes := r.Bytes()
rBytesPadded := make([]byte, keyBytes)
copy(rBytesPadded[keyBytes-len(rBytes):], rBytes)
sBytes := s.Bytes()
sBytesPadded := make([]byte, keyBytes)
copy(sBytesPadded[keyBytes-len(sBytes):], sBytes)
out := append(rBytesPadded, sBytesPadded...)
return out, &c.PrivateKey.Algorithm, nil
case *rsa.PrivateKey:
var hash crypto.Hash
switch c.PrivateKey.Algorithm {
case "RS256", "PS256":
hash = crypto.SHA256
case "RS384", "PS384":
hash = crypto.SHA384
case "RS512", "PS512":
hash = crypto.SHA512
default:
return nil, nil, fmt.Errorf("Unsupported alg %s", c.PrivateKey.Algorithm)
}
hasher := hash.New()
// According to documentation, Write() on hash never fails
_, _ = hasher.Write(payload)
hashed := hasher.Sum(nil)
var out []byte
var err error
switch c.PrivateKey.Algorithm {
case "RS256", "RS384", "RS512":
out, err = rsa.SignPKCS1v15(rand.Reader, key, hash, hashed)
case "PS256", "PS384", "PS512":
out, err = rsa.SignPSS(rand.Reader, key, hash, hashed, &rsa.PSSOptions{
SaltLength: rsa.PSSSaltLengthAuto,
})
}
if err != nil {
return nil, nil, err
}
return out, &c.PrivateKey.Algorithm, nil
default:
return nil, nil, fmt.Errorf("Unsupported privateKey %T", c.PrivateKey.Key)
}
}
func NewDefaultAuthenticator() Authenticator {
auth, _ := NewAuthenticator(nil, nil, nil)
return auth
}
func NewAuthenticator(storage CredentialStorage, selector CredentialSelector, approver CredentialApprover) (Authenticator, error) {
a := authenticator{
counter: 0,
credentials: make(map[string]*publicCredentialHandler),
}
if storage == nil {
a.aauid = uuid.New()
} else {
a.aauid = storage.AAGUID()
a.sorage = storage
}
if selector == nil {
a.selector = func(creds []Credential) Credential {
if creds != nil && len(creds) > 0 {
return creds[0]
}
return nil
}
} else {
a.selector = selector
}
if approver == nil {
a.approver = func(creds Credential) bool {
return true
}
} else {
a.approver = approver
}
return a.open()
}
func (b authenticator) open() (Authenticator, error) {
if b.sorage != nil {
b.Lock()
defer b.Unlock()
for _, data := range b.sorage.LoadAll() {
cred := &publicCredentialHandler{}
err := cred.deSerialise(data)
if err != nil {
return nil, err
}
b.credentials[cred.identity()] = cred
}
}
return &b, nil
}
//https://w3c.github.io/webauthn/#authenticator-ops
func (b *authenticator) MakeCredential(rpId string,
clientDataHash []byte,
relyingParty *PublicKeyCredentialEntity,
user *PublicKeyCredentialUserEntity,
normalizedParameters []map[string]string,
excludeList [][]byte,
extensions map[string]interface{},
requireResidentKey bool) (attestationObject []byte, err error) {
/*
The caller’s RP ID, as determined by the user agent and the client.
The hash of the serialized client data, provided by the client.
The relying party's PublicKeyCredentialEntity.
The user account’s PublicKeyCredentialEntity.
The PublicKeyCredentialType and cryptographic parameters requested by the Relying Party, with the cryptographic algorithms normalized as per the procedure in Web Cryptography API §algorithm-normalization-normalize-an-algorithm.
A list of PublicKeyCredential objects provided by the Relying Party with the intention that, if any of these are known to the authenticator, it should not create a new credential.
Extension data created by the client based on the extensions requested by the Relying Party.
The requireResidentKey parameter of the options.authenticatorSelection dictionary.
*/
/*
On successful completion of this operation, the authenticator returns the attestation object to the client.
*/
var c *publicCredentialHandler
if c, err = b.findExistingCredential(relyingParty.Id, user.Id, excludeList); err != nil {
return
} else if c != nil {
err = fmt.Errorf("Existing Credential %s %s", relyingParty.Id, user.Id)
return
}
extensionsResult := make(map[string]interface{})
for extId, input := range extensions {
extensionsResult[extId] = input
}
if normalizedParameters == nil || len(normalizedParameters) == 0 {
normalizedParameters = []map[string]string{map[string]string{
"alg": "P-521",
"op": "generateKey",
}}
}
if c, err = b.createCredential(rpId, relyingParty, user, normalizedParameters); err == nil {
var flag Flag = 0
var signBase, signature, attStmt []byte
var alg *string
signBase, err = b.generateSignData(rpId, clientDataHash, flag, c, extensionsResult)
if err != nil {
return
}
signature, alg, err = c.sign(signBase)
if err != nil {
return
}
attStmt, err = cbor.Dumps(map[string]interface{}{
"alg": alg,
"sig": signature,
/*"x5c" : [][]byte{},
"daaKey" : "",*/
})
if err != nil {
return
}
attestationObject, err = cbor.Dumps(map[string]interface{}{
"authData": signBase[:len(signBase)-len(clientDataHash)],
"fmt": "packed",
"attStmt": attStmt,
})
if err != nil {
return
}
if b.sorage != nil {
err = b.sorage.Store(c)
}
}
return
}
func (a *authenticator) findExistingCredential(rp, user string, blackList [][]byte) (*publicCredentialHandler, error) {
a.RLock()
defer a.RUnlock()
if blackList != nil {
for _, id := range blackList {
ids := base64.RawURLEncoding.EncodeToString(id)
if _, ok := a.credentials[ids]; ok {
return nil, fmt.Errorf("Blacklisted credential %s", ids)
}
}
} else {
for _, c := range a.credentials {
if c.RelyingParty().Id == rp && c.User().Id == user {
return c, nil
}
}
}
return nil, nil
}
func (a *authenticator) createCredential(rpid string, rp *PublicKeyCredentialEntity, user *PublicKeyCredentialUserEntity, params []map[string]string) (cred *publicCredentialHandler, err error) {
a.Lock()
defer a.Unlock()
id := make([]byte, 32)
_, err = rand.Read(id)
if err != nil {
return
}
//id := base64.RawURLEncoding.EncodeToString(idb)
cred = &publicCredentialHandler{
idb: id,
Rp: rp,
UserEntity: user,
PrivateKey: jose.JsonWebKey{},
}
if a.approver(cred) {
for _, v := range params {
if alg, ok := v["alg"]; ok {
var privateKey interface{}
if strings.EqualFold("P-521", alg) {
privateKey, err = ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
if err != nil {
return
}
cred.PrivateKey.Algorithm = "ES512"
cred.PrivateKey.Key = privateKey
a.credentials[cred.identity()] = cred
return
} else if strings.EqualFold("P-384", alg) {
privateKey, err = ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
if err != nil {
return
}
cred.PrivateKey.Algorithm = "ES384"
cred.PrivateKey.Key = privateKey
a.credentials[cred.identity()] = cred
return
} else if strings.EqualFold("P-256", alg) {
privateKey, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return
}
cred.PrivateKey.Algorithm = "ES256"
cred.PrivateKey.Key = privateKey
a.credentials[cred.identity()] = cred
return
}
}
}
err = errors.New("Not found any supported alg")
} else {
err = errors.New("User not approved")
}
return
}
func (b *authenticator) GetAssertion(rpId string,
clientDataHash []byte,
whiteList [][]byte,
extensions map[string]interface{}) (identifier, authenticatorData, signature []byte, err error) {
/*
The caller’s RP ID, as determined by the user agent and the client.
The hash of the serialized client data, provided by the client.
A list of credentials acceptable to the Relying Party (possibly filtered by the client).
Extension data created by the client based on the extensions requested by the Relying Party.
*/
if c := b.selectCredential(rpId, whiteList); c != nil {
var signBase []byte
extensionsResult := make(map[string]interface{})
for extId, input := range extensions {
extensionsResult[extId] = input
}
var flag Flag = 0
/*The identifier of the credential used to generate the signature.
The authenticator data used to generate the signature.
The assertion signature.
*/
signBase, err = b.generateSignData(rpId, clientDataHash, flag, nil, extensions)
identifier = c.Identifier()
authenticatorData = signBase[:len(signBase)-len(clientDataHash)]
signature, _, err = c.sign(signBase)
} else {
err = fmt.Errorf("No Credential found rpid=%s", rpId)
}
return
}
func (a *authenticator) selectCredential(rp string, whiteList [][]byte) *publicCredentialHandler {
a.RLock()
defer a.RUnlock()
candidates := make([]Credential, 0)
if whiteList != nil {
for _, id := range whiteList {
if c, ok := a.credentials[base64.RawURLEncoding.EncodeToString(id)]; ok {
if c.RelyingParty().Id == rp {
candidates = append(candidates, c)
}
}
}
} else {
for _, c := range a.credentials {
if c.RelyingParty().Id == rp {
candidates = append(candidates, c)
}
}
}
selected := a.selector(candidates)
if selected != nil {
for _, c := range candidates {
if bytes.Equal(c.Identifier(), selected.Identifier()) {
return c.(*publicCredentialHandler)
}
}
}
return nil
}
func (a *authenticator) generateSignData(rpId string, clientDataHAsh []byte, flag Flag, credential *publicCredentialHandler, extensions map[string]interface{}) ([]byte, error) {
a.Lock()
defer a.Unlock()
var b bytes.Buffer
hs := sha256.New()
if _, err := hs.Write([]byte(rpId)); err != nil {
return nil, err
}
//rpId
b.Write(hs.Sum(nil))
if extensions != nil && len(extensions) > 0 {
flag = flag | ED
}
if credential != nil {
flag = flag | AT
}
//flag
b.WriteByte((byte)(flag))
//counter
a.counter += a.counter
var num []byte
num = make([]byte, 4)
binary.BigEndian.PutUint32(num, a.counter)
b.Write(num)
//attestation Data
if flag&AT == AT {
credentialPublicKey, err := credential.marshalPublicCredential()
if err != nil {
return nil, err
}
//aaguid
for _, idb := range a.aauid {
b.WriteByte(idb)
}
//L
num = make([]byte, 2)
binary.BigEndian.PutUint16(num, uint16(len(credential.Identifier())))
b.Write(num)
//credentialId
b.Write(credential.Identifier())
//credentialPublicKey
b.Write(credentialPublicKey)
}
if flag&ED == ED {
ex, err := cbor.Dumps(extensions)
if err != nil {
return nil, err
}
b.Write(ex)
}
b.Write(clientDataHAsh)
return b.Bytes(), nil
}
func LoadCBOR(blob []byte, v interface{}) error {
e := make(chan error, 1)
if err := loadCBORSafe(blob, v, e); err != nil {
return err
}
return <-e
}
func loadCBORSafe(blob []byte, v interface{}, e chan<- error) error {
defer func() {
if r := recover(); r != nil {
if err, ok := r.(error); ok {
e <- err
} else if msg, ok := r.(string); ok {
e <- errors.New(msg)
} else {
e <- fmt.Errorf("CBOR Panic %s", r)
}
}
close(e)
}()
return cbor.Loads(blob, v)
}