forked from keycard-tech/keycard-go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
command_set.go
448 lines (371 loc) · 11 KB
/
command_set.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
package keycard
import (
"crypto/ecdsa"
"crypto/rand"
"crypto/sha256"
"encoding/asn1"
"encoding/hex"
"errors"
"math/big"
"github.com/GridPlus/keycard-go/apdu"
"github.com/GridPlus/keycard-go/crypto"
"github.com/GridPlus/keycard-go/globalplatform"
"github.com/GridPlus/keycard-go/gridplus"
"github.com/GridPlus/keycard-go/types"
ethcrypto "github.com/ethereum/go-ethereum/crypto"
log "github.com/sirupsen/logrus"
)
var ErrNoAvailablePairingSlots = errors.New("no available pairing slots")
var ErrCertInvalid = errors.New("pairing detected invalid certificate")
type CommandSet struct {
c types.Channel
sc *SecureChannel
ApplicationInfo *types.ApplicationInfo
PairingInfo *types.PairingInfo
}
func NewCommandSet(c types.Channel) *CommandSet {
return &CommandSet{
c: c,
sc: NewSecureChannel(c),
ApplicationInfo: &types.ApplicationInfo{},
}
}
func (cs *CommandSet) SetPairingInfo(key []byte, index int) {
cs.PairingInfo = &types.PairingInfo{
Key: key,
Index: index,
}
}
func (cs *CommandSet) Select() error {
var SafecardAID = []byte{0xA0, 0x00, 0x00, 0x08, 0x20, 0x00, 0x01, 0x01}
cmd := globalplatform.NewCommandSelect(SafecardAID)
cmd.SetLe(0)
resp, err := cs.c.Send(cmd)
if err != nil {
log.Error("could not send select command. err: ", err)
return err
}
log.Debug("select response:\n", hex.Dump(resp.Data))
instanceUID, cardPubKey, err := gridplus.ParseSelectResponse(resp.Data)
if err != nil {
return err
}
log.Debugf("instanceUID: % X", instanceUID)
log.Debugf("select response pubKey: % X", cardPubKey)
//Generating secure channel secrets here in advance of pairing and opening channel
err = cs.sc.GenerateSecret(cardPubKey)
if err != nil {
log.Error("unable to generate secure channel secrets. err: ", err)
return err
}
return nil
}
func (cs *CommandSet) Init(secrets *Secrets) error {
data, err := cs.sc.OneShotEncrypt(secrets)
if err != nil {
return err
}
init := NewCommandInit(data)
resp, err := cs.c.Send(init)
return cs.checkOK(resp, err)
}
func (cs *CommandSet) Pair() error {
//Generate random salt and keypair
clientSalt := make([]byte, 32)
rand.Read(clientSalt)
pairingPrivKey, err := ethcrypto.GenerateKey()
if err != nil {
log.Error("unable to generate pairing keypair. err: ", err)
return err
}
pairingPubKey := pairingPrivKey.PublicKey
//Exchange pairing key info with card
cmd := gridplus.NewAPDUPairStep1(clientSalt, &pairingPubKey)
resp, err := cs.c.Send(cmd)
if err != nil {
log.Error("unable to send Pair Step 1 command. err: ", err)
return err
}
pairStep1Resp, err := gridplus.ParsePairStep1Response(resp.Data)
if err != nil {
log.Error("could not parse pair step 2 response. err: ", err)
}
//Validate card's certificate has valid GridPlus signature
certValid := gridplus.ValidateCardCertificate(pairStep1Resp.SafecardCert)
log.Debug("certificate signature valid: ", certValid)
if !certValid {
log.Error("unable to verify card certificate.")
return ErrCertInvalid
}
log.Debug("pair step 2 safecard cert:\n", hex.Dump(pairStep1Resp.SafecardCert.PubKey))
cardCertPubKey, err := gridplus.ParseCertPubkeyToECDSA(pairStep1Resp.SafecardCert.PubKey)
if err != nil {
log.Error("unable to parse certificate public key. err: ", err)
return err
}
pubKeyValid := gridplus.ValidateECCPubKey(cardCertPubKey)
log.Debug("certificate public key valid: ", pubKeyValid)
if !pubKeyValid {
log.Error("card pubkey invalid")
return err
}
//challenge message test
ecdhSecret := crypto.GenerateECDHSharedSecret(pairingPrivKey, cardCertPubKey)
secretHashArray := sha256.Sum256(append(clientSalt, ecdhSecret...))
secretHash := secretHashArray[0:]
type ECDSASignature struct {
R, S *big.Int
}
signature := &ECDSASignature{}
_, err = asn1.Unmarshal(pairStep1Resp.SafecardSig, signature)
if err != nil {
log.Error("could not unmarshal certificate signature.", err)
}
//validate that card created valid signature over same salted and hashed ecdh secret
valid := ecdsa.Verify(cardCertPubKey, secretHash, signature.R, signature.S)
if !valid {
log.Error("ecdsa sig not valid")
return errors.New("could not verify shared secret challenge")
}
log.Debug("card signature on challenge message valid: ", valid)
cryptogram := sha256.Sum256(append(pairStep1Resp.SafecardSalt, secretHash...))
cmd = gridplus.NewAPDUPairStep2(cryptogram[0:])
resp, err = cs.c.Send(cmd)
if err != nil {
log.Error("error sending pair step 2 command. err: ", err)
return err
}
pairStep2Resp, err := gridplus.ParsePairStep2Response(resp.Data)
if err != nil {
log.Error("could not parse pair step 2 response. err: ", err)
}
log.Debugf("pairStep2Resp: % X", pairStep2Resp)
//Derive Pairing Key
pairingKey := sha256.Sum256(append(pairStep2Resp.Salt, secretHash...))
log.Debugf("derived pairing key: % X", pairingKey)
//Store pairing info for use in OpenSecureChannel
cs.SetPairingInfo(pairingKey[0:], pairStep2Resp.PairingIdx)
return nil
}
func (cs *CommandSet) Unpair(index uint8) error {
cmd := NewCommandUnpair(index)
resp, err := cs.sc.Send(cmd)
return cs.checkOK(resp, err)
}
func (cs *CommandSet) OpenSecureChannel() error {
if cs.ApplicationInfo == nil {
return errors.New("cannot open secure channel without setting PairingInfo")
}
cmd := NewCommandOpenSecureChannel(uint8(cs.PairingInfo.Index), cs.sc.RawPublicKey())
resp, err := cs.c.Send(cmd)
if err = cs.checkOK(resp, err); err != nil {
return err
}
encKey, macKey, iv := crypto.DeriveSessionKeys(cs.sc.Secret(), cs.PairingInfo.Key, resp.Data)
cs.sc.Init(iv, encKey, macKey)
err = cs.mutualAuthenticate()
if err != nil {
return err
}
return nil
}
func (cs *CommandSet) GetStatus(info uint8) (*types.ApplicationStatus, error) {
cmd := NewCommandGetStatus(info)
resp, err := cs.sc.Send(cmd)
if err = cs.checkOK(resp, err); err != nil {
return nil, err
}
return types.ParseApplicationStatus(resp.Data)
}
func (cs *CommandSet) GetStatusApplication() (*types.ApplicationStatus, error) {
return cs.GetStatus(P1GetStatusApplication)
}
func (cs *CommandSet) GetStatusKeyPath() (*types.ApplicationStatus, error) {
return cs.GetStatus(P1GetStatusKeyPath)
}
func (cs *CommandSet) VerifyPIN(pin string) error {
cmd := NewCommandVerifyPIN(pin)
resp, err := cs.sc.Send(cmd)
return cs.checkOK(resp, err)
}
func (cs *CommandSet) ChangePIN(pin string) error {
cmd := NewCommandChangePIN(pin)
resp, err := cs.sc.Send(cmd)
return cs.checkOK(resp, err)
}
func (cs *CommandSet) ChangePUK(puk string) error {
cmd := NewCommandChangePUK(puk)
resp, err := cs.sc.Send(cmd)
return cs.checkOK(resp, err)
}
func (cs *CommandSet) ChangePairingSecret(password string) error {
secret := generatePairingToken(password)
cmd := NewCommandChangePairingSecret(secret)
resp, err := cs.sc.Send(cmd)
return cs.checkOK(resp, err)
}
func (cs *CommandSet) GenerateKey() ([]byte, error) {
cmd := NewCommandGenerateKey()
resp, err := cs.sc.Send(cmd)
if err = cs.checkOK(resp, err); err != nil {
return nil, err
}
return resp.Data, nil
}
func (cs *CommandSet) RemoveKey() error {
cmd := NewCommandRemoveKey()
resp, err := cs.sc.Send(cmd)
return cs.checkOK(resp, err)
}
func (cs *CommandSet) DeriveKey(path string) error {
cmd, err := NewCommandDeriveKey(path)
if err != nil {
return err
}
resp, err := cs.sc.Send(cmd)
return cs.checkOK(resp, err)
}
func (cs *CommandSet) ExportKey(derive bool, makeCurrent bool, onlyPublic bool, path string) ([]byte, error) {
var p1 uint8
if derive == false {
p1 = P1ExportKeyCurrent
} else if makeCurrent == false {
p1 = P1ExportKeyDerive
} else {
p1 = P1ExportKeyDeriveAndMakeCurrent
}
var p2 uint8
if onlyPublic == true {
p2 = P2ExportKeyPublicOnly
} else {
p2 = P2ExportKeyPrivateAndPublic
}
cmd, err := NewCommandExportKey(p1, p2, path)
if err != nil {
return nil, err
}
resp, err := cs.sc.Send(cmd)
err = cs.checkOK(resp, err)
if err != nil {
return nil, err
}
return resp.Data, nil
}
func (cs *CommandSet) ExportSeed() ([]byte, error) {
cmd := NewCommandExportSeed()
resp, err := cs.sc.Send(cmd)
if err != nil {
return nil, err
}
seed, err := gridplus.ParseExportSeedResponse(resp.Data)
if err != nil {
return nil, err
}
return seed, nil
}
func (cs *CommandSet) SetPinlessPath(path string) error {
cmd, err := NewCommandSetPinlessPath(path)
if err != nil {
return err
}
resp, err := cs.sc.Send(cmd)
return cs.checkOK(resp, err)
}
func (cs *CommandSet) Sign(data []byte) (*types.Signature, error) {
cmd, err := NewCommandSign(data, P1SignCurrentKey, "")
if err != nil {
return nil, err
}
resp, err := cs.sc.Send(cmd)
if err = cs.checkOK(resp, err); err != nil {
return nil, err
}
return types.ParseSignature(data, resp.Data)
}
func (cs *CommandSet) SignWithPath(data []byte, path string) (*types.Signature, error) {
cmd, err := NewCommandSign(data, P1SignDerive, path)
if err != nil {
return nil, err
}
resp, err := cs.sc.Send(cmd)
if err = cs.checkOK(resp, err); err != nil {
return nil, err
}
return types.ParseSignature(data, resp.Data)
}
func (cs *CommandSet) SignPinless(data []byte) (*types.Signature, error) {
cmd, err := NewCommandSign(data, P1SignPinless, "")
if err != nil {
return nil, err
}
resp, err := cs.c.Send(cmd)
if err = cs.checkOK(resp, err); err != nil {
return nil, err
}
return types.ParseSignature(data, resp.Data)
}
func (cs *CommandSet) LoadSeed(seed []byte) ([]byte, error) {
cmd := NewCommandLoadSeed(seed)
resp, err := cs.sc.Send(cmd)
if err = cs.checkOK(resp, err); err != nil {
return nil, err
}
return resp.Data, nil
}
func (cs *CommandSet) mutualAuthenticate() error {
data := make([]byte, 32)
if _, err := rand.Read(data); err != nil {
return err
}
cmd := NewCommandMutuallyAuthenticate(data)
resp, err := cs.sc.Send(cmd)
return cs.checkOK(resp, err)
}
func (cs *CommandSet) checkOK(resp *apdu.Response, err error, allowedResponses ...uint16) error {
if err != nil {
return err
}
if len(allowedResponses) == 0 {
allowedResponses = []uint16{apdu.SwOK}
}
for _, code := range allowedResponses {
if code == resp.Sw {
return nil
}
}
return apdu.NewErrBadResponse(resp.Sw, "unexpected response")
}
func (cs *CommandSet) IdentifyCard(hash []byte) ([]byte, error) {
cmd := NewCommandIdentifyCard(hash)
resp, err := cs.c.Send(cmd)
if err != nil {
return nil, err
}
return resp.Data, nil
}
func (cs *CommandSet) ExportCert() ([]byte, error) {
cmd := NewCommandExportCert()
resp, err := cs.c.Send(cmd)
if err != nil {
return nil, err
}
return resp.Data, nil
}
// Supported by SafeCard applet v2.3 and above
func (cs *CommandSet) ExportData() ([]byte, error) {
// Pages is a constant defined by `SAVED_DATA_NUM_PAGES` in the SafeCard applet
// We need to fetch all pages to make a full export of the data.
// Note that the data is TLV encoded, but the encoding is out of scope
// for this library
pages := 4
data := make([]byte, 0)
for i := 0; i < pages; i++ {
cmd := NewCommandExportData(uint8(i))
resp, err := cs.sc.Send(cmd)
if err = cs.checkOK(resp, err); err != nil {
return nil, err
}
data = append(data, resp.Data...)
}
return data, nil
}