This repository has been archived by the owner on Oct 18, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nfc.go
486 lines (391 loc) · 13 KB
/
nfc.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
/*
Copyright (C) 2019 Steven Mirabito (smirabito@csh.rit.edu)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package device
import (
"crypto/ecdsa"
"errors"
"github.com/ComputerScienceHouse/gatekeeper/keys"
"github.com/ComputerScienceHouse/gatekeeper/sig"
"github.com/fuzxxl/freefare/0.3/freefare"
"github.com/fuzxxl/nfc/2.0/nfc"
"github.com/google/uuid"
"github.com/labstack/gommon/log"
"io/ioutil"
"math/big"
"strings"
"time"
)
// The polling interval for reading a target
const targetLoopTimer = 50 * time.Millisecond
// baseAppId represents the first AID within a MiFare Classic mapped AID
// (0xF....?) in the middle (0x7F) of an unassigned function cluster (0xF7)
const baseAppId uint32 = 0xff77f0
// masterAppId represents the master AID, used for PICC master key derivation
const masterAppId uint32 = 0
// The default master/application keys; for uninitialized cards and newly created applications, this is all zeros
var (
defaultDESKey = [8]byte{0x0}
defaultAESKey = [16]byte{0x0}
defaultDESFireDESKey = freefare.NewDESFireDESKey(defaultDESKey)
defaultDESFireAESKey = freefare.NewDESFireAESKey(defaultAESKey, 0)
)
// MiFare application settings
const (
initialApplicationSettings byte = 0x9
finalApplicationSettings byte = 0xE0
initialPICCSettings byte = 0x09
finalPICCSettings byte = 0x08
)
// File ACLs
var (
// Read: Key 0, Write: Key 0, Read & Write: Key 0, Change Access Rights: Key 0
initialFileSettings = freefare.MakeDESFireAccessRights(0x0, 0x0, 0x0, 0x0)
// Read: Key 1, Write: Never, Read & Write: Never, Change Access Rights: Never
finalUUIDFileSettings = freefare.MakeDESFireAccessRights(0x1, 0xF, 0xF, 0xF)
// Read: Key 2, Write: Never, Read & Write: Never, Change Access Rights: Key 3
finalAuthenticityFileSettings = freefare.MakeDESFireAccessRights(0x2, 0xF, 0x3, 0x3)
)
// UUID file parameters
const (
mangledUUIDLength = 32
)
// Authenticity file parameters
const (
authenticityRLength = 48
authenticitySLength = 48
authenticityFileSize = authenticityRLength + authenticitySLength
)
type nfcDevice struct {
Device nfc.Device
}
type Realm struct {
Name string
Slot uint32
AssociationID uuid.UUID
AuthKey []byte
ReadKey []byte
UpdateKey []byte
PublicKey *ecdsa.PublicKey
PrivateKey *ecdsa.PrivateKey
}
func OpenNFCDevice(log log.Logger) (*nfcDevice, error) {
device, err := nfc.Open("")
if err != nil {
return nil, err
}
if err := device.InitiatorInit(); err != nil {
return nil, err
}
log.Infof("NFC reader opened: %s", device.String())
return &nfcDevice{
Device: device,
}, nil
}
func NFCHealthz() bool {
nfcStatus := true
nullLog := log.New("")
nullLog.SetOutput(ioutil.Discard)
nfcDevice, err := OpenNFCDevice(*nullLog)
if err != nil || nfcDevice == nil {
nfcStatus = false
} else {
_ = nfcDevice.Close(*nullLog)
}
return nfcStatus
}
func (d *nfcDevice) Close(log log.Logger) error {
if err := d.Device.Close(); err != nil {
return err
}
log.Infof("NFC device successfully closed")
return nil
}
func (d *nfcDevice) Connect(log log.Logger) (*freefare.DESFireTag, error) {
log.Infof("Waiting for card...")
for {
time.Sleep(targetLoopTimer)
tags, err := freefare.GetTags(d.Device)
if err != nil {
log.Errorf("Failed to get tags from device: %s", err)
return nil, err
}
if len(tags) < 1 {
// Keep polling until a tag is found
continue
}
tag := tags[0]
target, success := tag.(freefare.DESFireTag)
if success != true {
log.Warnf("Not a DESFire target, ignoring")
continue
}
if err = target.Connect(); err != nil {
// Can't connect to the tag
log.Warnf("Unable to connect to target, ignoring: %s", err)
continue
}
// Set the communication modes
target.WriteSettings = freefare.Enciphered
target.ReadSettings = freefare.Enciphered
log.Infof("Connected to a %s target with UID %s", target.String(), target.UID())
return &target, nil
}
}
func (d *nfcDevice) Issue(target freefare.DESFireTag, systemSecret []byte, realms []Realm, log log.Logger) error {
// Get the target's UID
uid := target.UID()
// Derive PICC master key
log.Infof("Deriving PICC master key...")
mAppId := freefare.NewDESFireAid(masterAppId)
_, err := keys.DeriveDESFireKey(systemSecret, mAppId, 0, []byte(uid))
if err != nil {
return err
}
// Write each realm as an application
for _, realm := range realms {
appId := freefare.NewDESFireAid(baseAppId + realm.Slot)
uuidArr := []byte(realm.AssociationID.String())
mangledUUID := strings.Replace(realm.AssociationID.String(), "-", "", -1)
if len(mangledUUID) != mangledUUIDLength {
return errors.New("unexpected size of mangled UUID")
}
log.Infof("Deriving application keys for '%s' realm...", realm.Name)
// Derive app master key
appMasterKey, err := keys.DeriveDESFireKey(systemSecret, appId, 0, []byte(uid))
if err != nil {
return err
}
// Derive app transport keys
appReadKey := keys.GenDESFireKey(realm.ReadKey)
appAuthKey, err := keys.DeriveDESFireKey(systemSecret, appId, 2, uuidArr)
if err != nil {
return err
}
appUpdateKey, err := keys.DeriveDESFireKey(systemSecret, appId, 3, uuidArr)
if err != nil {
return err
}
log.Infof("Creating authenticity data...")
// Sign the UUID and create the authenticity data
rData, sData, err := sig.Sign(realm.PrivateKey, uuidArr)
if err != nil {
return err
}
rDataBytes := rData.Bytes()
sDataBytes := sData.Bytes()
if len(rDataBytes) != authenticityRLength {
return errors.New("unexpected size of authenticity data (R value)")
}
if len(sDataBytes) != authenticitySLength {
return errors.New("unexpected size of authenticity data (S value)")
}
// Ensure we're on the master application
log.Infof("Switching to the master application...")
if err = target.SelectApplication(mAppId); err != nil {
return err
}
// Authenticate to the target
log.Infof("Authenticating to tag...")
if err = target.Authenticate(0, *defaultDESFireDESKey); err != nil {
return err
}
// Create the application
log.Infof("Creating application in slot %d...", realm.Slot)
if err = target.CreateApplication(appId, initialApplicationSettings, 4|freefare.CryptoAES); err != nil {
return err
}
// Select the newly created application
log.Infof("Selecting application...")
if err = target.SelectApplication(appId); err != nil {
return err
}
// Authenticate to the application
log.Infof("Authenticating to application...")
if err = target.Authenticate(0, *defaultDESFireAESKey); err != nil {
return err
}
// Change the application transport keys
log.Infof("Changing application transport keys...")
if err = target.ChangeKey(1, *appReadKey, *defaultDESFireAESKey); err != nil {
return err
}
if err = target.ChangeKey(2, *appAuthKey, *defaultDESFireAESKey); err != nil {
return err
}
if err = target.ChangeKey(3, *appUpdateKey, *defaultDESFireAESKey); err != nil {
return err
}
// Create the UUID data file
log.Infof("Writing UUID data file...")
if err = target.CreateDataFile(1, freefare.Enciphered, initialFileSettings, mangledUUIDLength, false); err != nil {
return err
}
dataLen, err := target.WriteData(1, 0, []byte(mangledUUID))
if err != nil {
return err
}
if dataLen != mangledUUIDLength {
return errors.New("failed to write UUID to target")
}
// Create the authenticity file
log.Infof("Writing authenticity file...")
if err = target.CreateDataFile(2, freefare.Enciphered, initialFileSettings, authenticityFileSize, false); err != nil {
return err
}
// Write the R value to the authenticity file
dataLen, err = target.WriteData(2, 0, rDataBytes)
if err != nil {
return err
}
if dataLen != authenticityRLength {
return errors.New("failed to write authenticity file (R value) to target")
}
// Append the S value to the authenticity file
dataLen, err = target.WriteData(2, authenticityRLength, sDataBytes)
if err != nil {
return err
}
if dataLen != authenticitySLength {
return errors.New("failed to write authenticity file (S value) to target")
}
log.Infof("Applying file ACLs...")
if err = target.ChangeFileSettings(1, freefare.Enciphered, finalUUIDFileSettings); err != nil {
return err
}
if err = target.ChangeFileSettings(2, freefare.Enciphered, finalAuthenticityFileSettings); err != nil {
return err
}
// Change the application master key
log.Infof("Changing application master key...")
if err = target.ChangeKey(0, *appMasterKey, *defaultDESFireAESKey); err != nil {
return err
}
// Re-authenticate to the application
if err = target.Authenticate(0, *appMasterKey); err != nil {
return err
}
// Change the application key settings
log.Infof("Finalizing application settings...")
if err = target.ChangeKeySettings(finalApplicationSettings); err != nil {
return err
}
}
// Switch back to the master application
log.Infof("Switching to the master application...")
if err = target.SelectApplication(mAppId); err != nil {
return err
}
// Authenticate to the target
log.Infof("Authenticating to tag...")
if err = target.Authenticate(0, *defaultDESFireDESKey); err != nil {
return err
}
// Change the key settings to allow us to change the PICC master key
if err = target.ChangeKeySettings(initialPICCSettings); err != nil {
return err
}
// TODO: Must return and save real tag UID or will not be able to re-derive PICC master key
// Change the PICC master key
//log.Infof("Changing PICC master key...")
//if err = target.ChangeKey(0, *piccMasterKey, *defaultDESFireDESKey); err != nil {
// return err
//}
// Re-authenticate to the target
//if err = target.Authenticate(0, *piccMasterKey); err != nil {
// return err
//}
// Set the final key settings
//log.Infof("Finalizing PICC settings...")
//if err = target.ChangeKeySettings(finalPICCSettings); err != nil {
// return err
//}
// Enable random UID
//log.Infof("Enabling random PICC UID...")
//if err = target.SetConfiguration(false, true); err != nil {
// return err
//}
// Successfully issued card
return nil
}
func (d *nfcDevice) Authenticate(target freefare.DESFireTag, realm Realm, log log.Logger) (*uuid.UUID, error) {
appId := freefare.NewDESFireAid(baseAppId + realm.Slot)
appReadKey := keys.GenDESFireKey(realm.ReadKey)
// Select the realm's application
if err := target.SelectApplication(appId); err != nil {
return nil, err
}
// Authenticate to the application
if err := target.Authenticate(1, *appReadKey); err != nil {
return nil, err
}
// Read the UUID from the application
mangledUUID := make([]byte, mangledUUIDLength)
dataLen, err := target.ReadData(1, 0, mangledUUID)
if err != nil {
return nil, err
}
if dataLen != mangledUUIDLength {
return nil, errors.New("failed to read UUID from target")
}
// Parse the data read into a valid UUID
targetUUID, err := uuid.ParseBytes(mangledUUID)
if err != nil {
return nil, err
}
// Derive the authentication key
appAuthKey, err := keys.DeriveDESFireKey(realm.AuthKey, appId, 2, []byte(targetUUID.String()))
if err != nil {
return nil, err
}
// Authenticate with the derived key
if err := target.Authenticate(2, *appAuthKey); err != nil {
return nil, err
}
// Read the authenticity data (R value) from the target
rDataBytes := make([]byte, authenticityRLength)
dataLen, err = target.ReadData(2, 0, rDataBytes)
if err != nil {
return nil, err
}
if dataLen != authenticityRLength {
return nil, errors.New("failed to read authenticity data (R value) from target")
}
// Read the authenticity data (S value) from the target
sDataBytes := make([]byte, authenticitySLength)
dataLen, err = target.ReadData(2, authenticityRLength, sDataBytes)
if err != nil {
return nil, err
}
if dataLen < authenticitySLength {
return nil, errors.New("failed to read authenticity data (S value) from target")
}
// Verify UUID signature
targetUUIDBytes := []byte(targetUUID.String())
rData, sData := new(big.Int), new(big.Int)
rData.SetBytes(rDataBytes)
sData.SetBytes(sDataBytes)
if !sig.Verify(realm.PublicKey, targetUUIDBytes, rData, sData) {
return nil, errors.New("target UUID failed signature verification")
}
// Authenticated, return the UUID
return &targetUUID, nil
}
func (d *nfcDevice) Disconnect(target freefare.DESFireTag, log log.Logger) error {
if err := target.Disconnect(); err != nil {
log.Warnf("Unable to disconnect from target (already disconnected?): %s", err)
return err
}
log.Infof("Disconnected from target %s", target.UID())
return nil
}