forked from as19git67/nukible
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nukible.js
1103 lines (984 loc) · 55 KB
/
nukible.js
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var noble = require('noble');
var _ = require('underscore');
var crc = require('crc');
var sodium = require('sodium');
var HSalsa20 = require('./hsalsa20');
var crypto = require('crypto');
var nukible = module.exports = function (options) {
this.options = {};
if (options) {
this.options.nukiLocks = options.nukiLocks || {};
this.options.name = options.name; // name of nuki client
this.options.appId = options.appId; // id of this nuki client
this.options.appType = options.appType; // type of this nuki client
}
this.state = nukible.prototype.STATE_PAIRING_IDLE;
this.initialize.apply(this, arguments);
};
// Attach all inheritable methods to the nukible prototype.
_.extend(nukible.prototype, {
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function () {
},
pair: function (options, callback) {
if (options) {
_.defaults(this.options, options);
}
this.isPaired = false;
this.isInPairing = true;
var self = this;
var t = setTimeout(function () {
console.log("Timeout. Aborting pairing.");
noble.stopScanning();
noble.removeAllListeners('discover');
noble.removeAllListeners('stateChange');
if (_.isFunction(callback)) {
self.isInPairing = false;
callback("pairing timeout");
}
}, 60000);
if (noble.state == 'poweredOn') {
noble.startScanning();
}
noble.on('stateChange', this._pairingOnStateChanged);
noble.on('discover', function (peripheral) {
self._pairingOnPeripheralDiscovered.call(self, peripheral, function (err, result) {
noble.stopScanning();
noble.removeAllListeners('discover');
noble.removeAllListeners('stateChange');
if (err) {
self.isPaired = false;
self.isInPairing = false;
clearTimeout(t);
if (_.isFunction(callback)) {
callback(err);
}
} else {
if (result && result.status) {
switch (result.status) {
case 'paired':
self.isPaired = true;
clearTimeout(t);
if (_.isFunction(callback)) {
callback(null, result.results);
}
break;
case 'disconnected':
if (self.isPaired || !self.isInPairing) {
console.log("Peripheral disconnected.");
} else {
if (_.isFunction(callback)) {
callback("ERROR: peripheral disconnected during pairing.");
}
}
break;
default:
if (_.isFunction(callback)) {
callback("ERROR: pairing failed for unknown reason");
}
}
}
self.isInPairing = false;
}
}
);
});
},
prepareEncryptedDataToSend: function (cmd, authorizationId, sharedSecret, payload) {
var nonce = new Buffer(24);
sodium.api.randombytes_buf(nonce);
var authIdBuffer = new Buffer(4);
authIdBuffer.writeUInt32LE(authorizationId);
var cmdBuffer = new Buffer(2);
cmdBuffer.writeUInt16LE(cmd);
var pDataWithoutCrc = Buffer.concat([authIdBuffer, cmdBuffer, payload]);
var checksum = crc.crc16ccitt(pDataWithoutCrc);
var checksumBuffer = new Buffer(2);
checksumBuffer.writeUInt16LE(checksum);
var pData = Buffer.concat([pDataWithoutCrc, checksumBuffer]);
var pDataEncrypted = sodium.api.crypto_secretbox(pData, nonce, sharedSecret).slice(16); // skip first 16 bytes
// console.log("encrypted message: ", pDataEncrypted);
var lenBuffer = new Buffer(2);
lenBuffer.writeUInt16LE(pDataEncrypted.length);
var aData = Buffer.concat([nonce, authIdBuffer, lenBuffer]);
// console.log("aData: ", aData);
// console.log("pData: ", pData);
return Buffer.concat([aData, pDataEncrypted]);
},
lock: function (options, callback) {
if (options) {
_.defaults(this.options, options);
}
var self = this;
var t = setTimeout(function () {
console.log("Timeout. Aborting lock.");
noble.stopScanning();
noble.removeAllListeners('discover');
noble.removeAllListeners('stateChange');
if (_.isFunction(callback)) {
callback("lock timeout");
}
}, 30000);
if (noble.state == 'poweredOn') {
console.log("start scanning");
noble.startScanning();
}
noble.on('stateChange', this._onStateChanged);
noble.on('discover',
function (peripheral) {
var peripheralId = peripheral.uuid;
var lockPeripheralId = self.options.peripheralId;
if (lockPeripheralId === peripheralId) {
noble.stopScanning();
noble.removeAllListeners('discover');
noble.removeAllListeners('stateChange');
self._onPeripheralDiscovered.call(self, "lock", peripheral, function (err, result) {
clearTimeout(t);
if (err) {
if (_.isFunction(callback)) {
callback(err);
}
} else {
if (result && result.status === 'complete') {
if (_.isFunction(callback)) {
callback(null);
}
} else {
if (_.isFunction(callback)) {
callback("ERROR: unknown");
}
}
}
});
} else {
console.log("ignoring peripheral with id " + peripheralId);
}
});
},
unlock: function (options, callback) {
if (options) {
_.defaults(this.options, options);
}
var self = this;
var t = setTimeout(function () {
console.log("Timeout. Aborting unlock.");
noble.stopScanning();
noble.removeAllListeners('discover');
noble.removeAllListeners('stateChange');
if (_.isFunction(callback)) {
callback("unlock timeout");
}
}, 30000);
if (noble.state == 'poweredOn') {
console.log("start scanning");
noble.startScanning();
}
noble.on('stateChange', this._onStateChanged);
noble.on('discover',
function (peripheral) {
var peripheralId = peripheral.uuid;
var lockPeripheralId = self.options.peripheralId;
if (lockPeripheralId === peripheralId) {
noble.stopScanning();
noble.removeAllListeners('discover');
noble.removeAllListeners('stateChange');
self._onPeripheralDiscovered.call(self, "unlock", peripheral, function (err, result) {
clearTimeout(t);
if (err) {
if (_.isFunction(callback)) {
callback(err);
}
} else {
if (result && result.status === 'complete') {
if (_.isFunction(callback)) {
callback(null);
}
} else {
if (_.isFunction(callback)) {
callback("ERROR: unknown");
}
}
}
});
} else {
console.log("ignoring peripheral with id " + peripheralId);
}
});
},
_pairingOnStateChanged: function (bleState) {
if (bleState === 'poweredOn') {
console.log('scanning for nuki.io Bluetooth LE services...');
//noble.startScanning([nukible.prototype.nukiPairingServiceUuid, nukible.prototype.nukiServiceUuid], true);
noble.startScanning();
} else {
noble.stopScanning();
}
},
_pairingOnPeripheralDiscovered: function (peripheral, callback) {
var self = this;
//
// The advertisment data contains a name, power level (if available),
// certain advertised service uuids, as well as manufacturer data,
// which could be formatted as an iBeacon.
//
console.log('found peripheral:', peripheral.advertisement);
var peripheralName = 'peripheral';
if (peripheral.advertisement.localName) {
peripheralName = peripheral.advertisement.localName;
}
var isConnectable = peripheral.connectable ? "" : "not ";
console.log(peripheralName + " is " + isConnectable + "connectable.");
var peripheralId = peripheral.uuid;
//
// Once the peripheral has been discovered, then connect to it.
// It can also be constructed if the uuid is already known.
///
peripheral.connect(function (err) {
if (err) {
concole.log("ERROR while connecting " + peripheral.advertisement.localName);
callback(err);
} else {
//
// Once the peripheral has been connected, then discover the
// services and characteristics of interest.
//
peripheral.discoverServices(
[nukible.prototype.nukiPairingServiceUuid, nukible.prototype.nukiServiceUuid], function (err, services) {
self._pairingOnPeripheralServiceDiscovered.call(self, err, services, function (err, result) {
peripheral.disconnect();
if (!err && result && result.status === 'paired') {
result.results.peripheralId = peripheralId;
}
callback(err, result);
})
});
}
});
peripheral.disconnect(function () {
callback(null, {status: 'disconnected'})
});
},
_pairingOnPeripheralServiceDiscovered: function (err, services, callback) {
if (err) {
// console.log("discoverServices failed", err);
callback(err);
} else {
var self = this;
this.nukiPairingGeneralDataIOCharacteristic = null;
this.nukiServiceGeneralDataIOCharacteristic = null;
this.nukiUserSpecificDataInputOutputCharacteristic = null;
services.forEach(function (service) {
//
// This must be the service we were looking for.
//
console.log('found service:', service.uuid);
//
// So, discover its characteristics.
//
service.discoverCharacteristics([], function (err, characteristics) {
characteristics.forEach(function (characteristic) {
//
// Loop through each characteristic and match them to the
// UUIDs that we know about.
//
console.log('Found characteristic:', characteristic.uuid);
if (nukible.prototype.nukiPairingGeneralDataIOCharacteristicUuid == characteristic.uuid) {
self.nukiPairingGeneralDataIOCharacteristic = characteristic;
}
else if (nukible.prototype.nukiServiceGeneralDataIOCharacteristicUuid == characteristic.uuid) {
self.nukiServiceGeneralDataIOCharacteristic = characteristic;
}
else if (nukible.prototype.nukiUserSpecificDataInputOutputCharacteristicUuid == characteristic.uuid) {
self.nukiUserSpecificDataInputOutputCharacteristic = characteristic;
}
});
//
// Check to see if we found all of our characteristics.
//
if (self.nukiPairingGeneralDataIOCharacteristic &&
self.nukiServiceGeneralDataIOCharacteristic &&
self.nukiUserSpecificDataInputOutputCharacteristic) {
console.log("All nuki.io characteristics that are needed for pairing were found.");
self.state = nukible.prototype.STATE_PAIRING_CL_REQ_PUBKEY;
// we found a peripheral, stop scanning
noble.stopScanning();
self.nukiPairingGeneralDataIOCharacteristic.subscribe(function () {
self.nukiPairingGeneralDataIOCharacteristic.on('read', function (data, isNotification) {
self._dataReceivedDuringPairing.call(self, data, isNotification, function (err, status) {
if (err && _.isString(err)) {
err += " State: " + self.state;
}
if (err || status) {
self.state = nukible.prototype.STATE_PAIRING_IDLE;
self.nukiPairingGeneralDataIOCharacteristic.removeListener.call(self, 'read', self._dataReceivedDuringPairing);
self.nukiPairingGeneralDataIOCharacteristic.unsubscribe();
callback(err, status);
}
});
});
var d = new Buffer(2);
d.writeUInt16LE(nukible.prototype.CMD_ID_PUBLIC_KEY);
var wCmdWithChecksum = self._prepareDataToSend.call(self, nukible.prototype.CMD_REQUEST_DATA, d);
self.nukiPairingGeneralDataIOCharacteristic.write(wCmdWithChecksum, false, function (err) {
if (err) {
console.log("ERROR: write CMD_ID_PUBLIC_KEY to nukiPairingGeneralDataIOCharacteristic failed", err);
self.nukiPairingGeneralDataIOCharacteristic.removeListener('read', self._dataReceivedDuringPairing);
callback(err);
// } else {
// console.log("CL sent command to request SL PK");
}
});
});
}
});
});
}
},
_onStateChanged: function (bleState) {
if (bleState === 'poweredOn') {
console.log('scanning for nuki.io Bluetooth LE services...');
//noble.startScanning([nukible.prototype.nukiServiceUuid], true);
noble.startScanning();
} else {
noble.stopScanning();
}
},
_onPeripheralDiscovered: function (command, peripheral, callback) {
var self = this;
var peripheralName = 'peripheral';
if (peripheral.advertisement.localName) {
peripheralName = peripheral.advertisement.localName;
}
console.log('found peripheral:', peripheralName);
var isConnectable = peripheral.connectable ? "" : "not ";
console.log(peripheralName + " is " + isConnectable + "connectable.");
peripheral.connect(function (err) {
console.log("connected to peripheral");
peripheral.discoverServices(
[nukible.prototype.nukiServiceUuid], function (err, services) {
if (err) {
callback(err);
} else {
self._onPeripheralServiceDiscovered.call(self, command, peripheral, services, function (err, result) {
peripheral.disconnect();
callback(err, result);
})
}
});
});
},
_onPeripheralServiceDiscovered: function (command, peripheral, services, callback) {
var self = this;
this._currentCommand = command;
this.nukiGeneralDataIOCharacteristic = null;
this.nukiUserSpecificDataInputOutputCharacteristic = null;
services.forEach(function (service) {
//
// This must be the service we were looking for.
//
console.log('found service:', service.uuid);
//
// So, discover its characteristics.
//
service.discoverCharacteristics([], function (err, characteristics) {
characteristics.forEach(function (characteristic) {
//
// Loop through each characteristic and match them to the
// UUIDs that we know about.
//
console.log('Found characteristic:', characteristic.uuid);
if (nukible.prototype.nukiServiceGeneralDataIOCharacteristicUuid == characteristic.uuid) {
self.nukiServiceGeneralDataIOCharacteristic = characteristic;
}
else if (nukible.prototype.nukiUserSpecificDataInputOutputCharacteristicUuid == characteristic.uuid) {
self.nukiUserSpecificDataInputOutputCharacteristic = characteristic;
}
});
//
// Check to see if we found all of our characteristics.
//
if (self.nukiServiceGeneralDataIOCharacteristic &&
self.nukiUserSpecificDataInputOutputCharacteristic) {
console.log("All nuki.io characteristics that are needed were found.");
// we found a peripheral, stop scanning
noble.stopScanning();
self.nukiUserSpecificDataInputOutputCharacteristic.subscribe(function () {
self.nukiUserSpecificDataInputOutputCharacteristic.on('read', function (data, isNotification) {
self._dataReceived.call(self, peripheral, data, isNotification, function (err, status) {
if (err && _.isString(err)) {
err += " State: " + self.state;
}
// status is set when overall action is finished
// if !err && !status then further data is expected to be received
if (err || status) {
self.nukiUserSpecificDataInputOutputCharacteristic.removeListener.call(self, 'read', self._dataReceived);
self.nukiUserSpecificDataInputOutputCharacteristic.unsubscribe();
callback(err, status);
}
});
});
switch (self._currentCommand) {
case 'lock':
var peripheralId = peripheral.uuid;
var lock = self.options.nukiLock;
if (lock) {
var sharedSecret = new Buffer(lock.sharedSecret, 'hex');
self._requestNonceFromSL(lock.nukiAuthorizationId, sharedSecret, function (err, nonceK) {
if (err) {
peripheral.disconnect();
callback(err);
} else {
// console.log("Nonce received from SL:", nonceK);
var data1 = new Buffer(6);
data1.writeUInt8(2, 0); // 0x02 is lock
data1.writeUInt32LE(self.options.appId, 1);
data1.writeUInt8(0, 5); // no flags set
var wData = Buffer.concat([data1, nonceK]);
var wDataEncrypted = self.prepareEncryptedDataToSend(
nukible.prototype.CMD_LOCK_ACTION,
lock.nukiAuthorizationId,
sharedSecret,
wData);
self.nukiUserSpecificDataInputOutputCharacteristic.write(wDataEncrypted, false, function (err) {
if (err) {
console.log("ERROR: failed to send encrypted message for CMD_LOCK_ACTION");
peripheral.disconnect();
callback(err);
}
});
// callback(null, {status: 'unlocked'});
}
}
);
} else {
callback("Not paired with this lock. Peripheral UUID is " + peripheralId);
}
break;
case 'unlock':
var peripheralId = peripheral.uuid;
var lock = self.options.nukiLock;
if (lock) {
var sharedSecret = new Buffer(lock.sharedSecret, 'hex');
self._requestNonceFromSL(lock.nukiAuthorizationId, sharedSecret, function (err, nonceK) {
if (err) {
peripheral.disconnect();
callback(err);
} else {
// console.log("Nonce received from SL:", nonceK);
var data1 = new Buffer(6);
data1.writeUInt8(1, 0); // 0x01 is unlock
data1.writeUInt32LE(self.options.appId, 1);
data1.writeUInt8(0, 5); // no flags set
var wData = Buffer.concat([data1, nonceK]);
var wDataEncrypted = self.prepareEncryptedDataToSend(
nukible.prototype.CMD_LOCK_ACTION,
lock.nukiAuthorizationId,
sharedSecret,
wData);
self.nukiUserSpecificDataInputOutputCharacteristic.write(wDataEncrypted, false, function (err) {
if (err) {
console.log("ERROR: failed to send encrypted message for CMD_LOCK_ACTION");
peripheral.disconnect();
callback(err);
}
});
// callback(null, {status: 'unlocked'});
}
}
);
} else {
callback("Not paired with this lock. Peripheral UUID is " + peripheralId);
}
break;
default:
callback("Command (" + self._currentCommand + ") not implemented");
self._currentCommand = undefined;
}
});
}
});
});
},
_requestNonceFromSL: function (authorizationId, sharedSecret, callback) {
this.receivedData = new Buffer(0);
var wData = new Buffer(2);
wData.writeUInt16LE(nukible.prototype.CMD_CHALLENGE, 0); // request a challenge
var wDataEncrypted = this.prepareEncryptedDataToSend(
nukible.prototype.CMD_REQUEST_DATA,
authorizationId,
sharedSecret,
wData);
this.callbackForChallenge = callback;
var self = this;
// console.log("_requestNonceFromSL: encrypted data", wDataEncrypted);
this.nukiUserSpecificDataInputOutputCharacteristic.write(wDataEncrypted, false, function (err) {
if (err) {
console.log("ERROR: failed to send encrypted message when requesting new challenge from SL");
self.callbackForChallenge = undefined;
callback(err);
}
});
},
_dataReceived: function (peripheral, data, isNotification, callback) {
// console.log("DATA received", data);
this.receivedData = Buffer.concat([this.receivedData, data]);
if (data.length < 20) { // hack
if (this._crcOk(this.receivedData)) {
var tmpCmdId = this.receivedData.readUInt16LE();
switch (tmpCmdId) {
case nukible.prototype.CMD_ERROR:
var errorCode = this.receivedData.readUInt8(2);
var errorCodeStr = errorCode.toString();
switch (errorCode) {
case nukible.prototype.K_ERROR_BAD_PIN:
errorCodeStr = "K_ERROR_BAD_PIN";
break;
case nukible.prototype.K_ERROR_BAD_NONCE:
errorCodeStr = "K_ERROR_BAD_NONCE";
break;
case nukible.prototype.K_ERROR_BAD_PARAMETER:
errorCodeStr = "K_ERROR_BAD_PARAMETER";
break;
}
this.receivedData = new Buffer(0);
callback("ERROR reported from SL: " + errorCodeStr);
return;
case nukible.prototype.CMD_STATUS:
var status = this.receivedData.readUInt8(2);
switch (status) {
case nukible.prototype.STATUS_ACCEPTED:
// console.log("SL sent STATUS_ACCEPTED");
break;
case nukible.prototype.STATUS_COMPLETE:
// console.log("SL sent STATUS_COMPLETE");
callback(null, {status: 'complete'});
}
this.receivedData = new Buffer(0);
return;
}
}
var nonceK = this.receivedData.slice(0, 24);
// var authorizationId = this.receivedData.readUInt32LE(24);
// var messageLen = this.receivedData.readUInt16LE(28);
var encryptedMessage = this.receivedData.slice(30);
var peripheralId = peripheral.uuid;
var lock = this.options.nukiLock;
if (lock) {
if (lock.sharedSecret) {
var sharedSecret = new Buffer(lock.sharedSecret, 'hex');
var prefixBuff = new Buffer(16);
prefixBuff.fill(0);
var decryptedMessge = sodium.api.crypto_secretbox_open(Buffer.concat([prefixBuff, encryptedMessage]), nonceK, sharedSecret);
if (this._crcOk(decryptedMessge)) {
// console.log("CRC ok. Decrypted Message:", decryptedMessge);
var authorizationId = decryptedMessge.readUInt32LE(0);
if (authorizationId === lock.nukiAuthorizationId) {
var cmdId = decryptedMessge.readUInt16LE(4);
var payload = decryptedMessge.slice(6, decryptedMessge.length - 2);
switch (cmdId) {
case nukible.prototype.CMD_CHALLENGE:
// console.log("CHALLENGE received:", payload, payload.length);
if (this.callbackForChallenge) {
this.callbackForChallenge(null, payload);
}
break;
case nukible.prototype.CMD_NUKI_STATES:
// console.log("NUKI STATES", payload, payload.length);
var lockState = payload.readUInt8(1);
var lockStateStr = "unknown";
switch (lockState) {
case 1: // locked
lockStateStr = "locked";
break;
case 2: // unlocking
lockStateStr = "unlocking";
break;
case 3: // unlocked
lockStateStr = "unlocked";
break;
case 4: // locking
lockStateStr = "locking";
break;
case 5: //unlatched
lockStateStr = "unlatched";
break;
case 6: // unlocked (lock'n'go)
lockStateStr = "unlocked - lock'n'go";
break;
}
console.log("State of lock (" + lock.nukiUuid + ") is " + lockStateStr);
break;
case nukible.prototype.CMD_STATUS:
var status = payload.readUInt8(0);
console.log("SL sent status " + status.toString(16));
if (status === nukible.prototype.STATUS_COMPLETE) {
callback();
} else {
if (status === nukible.prototype.STATUS_ACCEPTED) {
console.log("SL sent status accepted");
} else {
callback("ERROR: SL sent STATUS not complete");
}
}
break;
default:
console.log("UNKNOWN message:", decryptedMessge);
callback("ERROR: message received but not expected");
}
} else {
console.log("ignoring data for other authorization-id (" + authorizationId + ")");
}
} else {
callback("Wrong CRC.");
}
} else {
callback("ERROR: don't have sharedSecret for lock with uuid " + lock.nukiUuid);
}
} else {
callback("Not paired with this lock. Peripheral UUID is " + peripheralId);
}
this.receivedData = new Buffer(0);
}
},
_makeKeyBuffer: function (inKey) {
var keyAsBuffer = new Buffer(0);
if (_.isString(inKey)) {
keyAsBuffer = new Buffer(inKey, 'hex');
} else {
if (_.isArray(inKey)) {
keyAsBuffer = new Buffer(inKey);
}
}
return keyAsBuffer;
},
_prepareDataToSend: function (cmd, data) {
var cmdBuffer = new Buffer(2);
cmdBuffer.writeUInt16LE(cmd);
var responseData = Buffer.concat([cmdBuffer, data]);
var checksum = crc.crc16ccitt(responseData);
var checksumBuffer = new Buffer(2);
checksumBuffer.writeUInt16LE(checksum);
var dataToSend = Buffer.concat([responseData, checksumBuffer]);
return dataToSend;
},
_crcOk: function (dataTocheck) {
if (dataTocheck) {
var dataForCrc = dataTocheck.slice(0, dataTocheck.length - 2);
var crcSumCalc = crc.crc16ccitt(dataForCrc);
var crcSumRetrieved = dataTocheck.readUInt16LE(dataTocheck.length - 2);
return crcSumCalc === crcSumRetrieved;
} else {
console.log("CRC check failed. DataToCheck is null");
return false;
}
},
_dataReceivedDuringPairing: function (data, isNotification, callback) {
var rCmd, r, authenticator;
var self = this;
// console.log('response from nuki', data, isNotification);
switch (this.state) {
case nukible.prototype.STATE_PAIRING_CL_REQ_PUBKEY:
// if (this._crcOk(data)) {
rCmd = data.readUInt16LE(0);
if (rCmd === nukible.prototype.CMD_ID_PUBLIC_KEY) {
console.log("Step 4: SL sent first part of public key...");
this.state = nukible.prototype.STATE_PAIRING_CL_REQ_PUBKEY_FIN;
this.rData = data;
} else {
if (rCmd === nukible.prototype.CMD_ERROR) {
var errorCode = data.readUInt8(2);
var errorCommandId = data.readUInt16LE(3);
switch (errorCode) {
case nukible.prototype.P_ERROR_NOT_PAIRING:
callback("ERROR: public key is being requested via request data command, but keyturner is not in pairing mode");
break;
default:
callback("ERROR from SL: " + errorCode.toString(16));
}
} else {
callback("ERROR: not expected command id " + rCmd);
}
}
// } else {
// callback("ERROR: wrong CRC");
// }
break;
case nukible.prototype.STATE_PAIRING_CL_REQ_PUBKEY_FIN:
this.rData = Buffer.concat([this.rData, data]);
if (this._crcOk(this.rData)) {
rCmd = this.rData.readUInt16LE(0);
if (rCmd === nukible.prototype.CMD_ID_PUBLIC_KEY) {
this.slPubKey = this.rData.slice(2, this.rData.length - 2);
console.log("Step 4: SL sent PK:");
console.log("Step 5: creating new CL key pair...");
var clKeys = new sodium.Key.ECDH();
this.clSk = clKeys.sk().get();
this.clPk = clKeys.pk().get();
console.log("Step 7: creating diffie-hellman key...");
// create a Diffie Hellman key out of the clients secret key and the nukis public key
// crypto_scalarmult_curve25519(s,sk,pk)
var k = sodium.api.crypto_scalarmult(self.clSk, self.slPubKey);
// console.log("CL DH Key from CL SK and SL PK: ", k);
console.log("Step 8: derive long term shared key...");
// derive a longterm shared secret key s from k using function kdf1
// static const unsigned char _0[16];
// static const unsigned char sigma[16] = "expand 32-byte k";
// crypto_core_hsalsa20(k,_0,s,sigma)
var hsalsa20 = new HSalsa20();
this.options.sharedSecret = new Buffer(32);
var inv = new Buffer(16);
inv.fill(0);
var c = new Buffer("expand 32-byte k");
hsalsa20.crypto_core(this.options.sharedSecret, inv, k, c);
// console.log("derived shared key: ", this.options.sharedSecret);
this.state = nukible.prototype.STATE_PAIRING_CL_REQ_CHALLENGE;
console.log("Step 6: CL sending PK...");
var wDataWithCrc = this._prepareDataToSend(nukible.prototype.CMD_ID_PUBLIC_KEY, this.clPk);
this.nukiPairingGeneralDataIOCharacteristic.write(wDataWithCrc, false, callback);
} else {
callback("ERROR: not expected command id " + rCmd);
}
} else {
callback("ERROR: wrong CRC");
}
break;
case nukible.prototype.STATE_PAIRING_CL_REQ_CHALLENGE:
rCmd = data.readUInt16LE(0);
if (rCmd === nukible.prototype.CMD_CHALLENGE) {
console.log("Step 9: SL sent first part of challenge...");
this.state = nukible.prototype.STATE_PAIRING_CL_REQ_CHALLENGE_FIN;
this.rData = data;
} else {
callback("ERROR: not expected command id " + rCmd + ".");
}
break;
case nukible.prototype.STATE_PAIRING_CL_REQ_CHALLENGE_FIN:
this.rData = Buffer.concat([this.rData, data]);
if (this._crcOk(this.rData)) {
rCmd = this.rData.readUInt16LE(0);
if (rCmd === nukible.prototype.CMD_CHALLENGE) {
this.nonceK = this.rData.slice(2, this.rData.length - 2);
console.log("Step 9: SL sent challenge.");
console.log("Step 10: CL creates r from CL PK, SL PK and nonceK");
r = Buffer.concat([this.clPk, this.slPubKey, this.nonceK]);
console.log("Step 11: CL creates authenticator from r");
// use HMAC-SHA256 to create the authenticator
authenticator = crypto.createHmac('SHA256', this.options.sharedSecret).update(r).digest();
console.log("Step 13: CL sends authorization authenticator...");
this.state = nukible.prototype.STATE_PAIRING_CL_REQ_CHALLENGE_2;
wDataWithCrc = this._prepareDataToSend(nukible.prototype.CMD_AUTHORIZATION_AUTHENTICATOR, authenticator);
this.nukiPairingGeneralDataIOCharacteristic.write(wDataWithCrc, false, callback);
} else {
callback("ERROR: not expected command id " + rCmd + ".");
}
} else {
callback("ERROR: wrong CRC.");
}
break;
case nukible.prototype.STATE_PAIRING_CL_REQ_CHALLENGE_2:
rCmd = data.readUInt16LE(0);
if (rCmd === nukible.prototype.CMD_CHALLENGE) {
console.log("Step 15a: SL sent first part of challenge.");
this.state = nukible.prototype.STATE_PAIRING_CL_REQ_CHALLENGE_2_FIN;
this.rData = data;
} else {
callback("ERROR: not expected command id " + rCmd + ".");
}
break;
case nukible.prototype.STATE_PAIRING_CL_REQ_CHALLENGE_2_FIN:
this.rData = Buffer.concat([this.rData, data]);
if (this._crcOk(this.rData)) {
rCmd = this.rData.readUInt16LE(0);
if (rCmd === nukible.prototype.CMD_CHALLENGE) {
this.nonceK = this.rData.slice(2, this.rData.length - 2);
this.rData = new Buffer(0);
console.log("Step 15b: SL sent challenge.");
console.log("Step 16a: creating authorization data...");
var ids = new Buffer(5);
ids.writeUInt8(this.options.appType); // ID type: 2: Fob
ids.writeUInt32LE(this.options.appId, 1);
var nameBuffer = new Buffer(32).fill(' ');
var name = new Buffer(this.options.name);
if (name.length > nameBuffer.length) {
name.copy(nameBuffer, 0, 0, nameBuffer.length);
} else {
name.copy(nameBuffer, 0, 0, name.length);
}
this.nonceABF = new Buffer(nukible.prototype.NUKI_NONCEBYTES);
sodium.api.randombytes_buf(this.nonceABF);
// create authenticator for the authorization data message
r = Buffer.concat([ids, nameBuffer, this.nonceABF, this.nonceK]);
// use HMAC-SHA256 to create the authenticator
authenticator = crypto.createHmac('SHA256', this.options.sharedSecret).update(r).digest();
var wData = Buffer.concat([authenticator, ids, nameBuffer, this.nonceABF]);
wDataWithCrc = this._prepareDataToSend(nukible.prototype.CMD_AUTHORIZATION_DATA, wData);
// console.log("CL sending authorization data", wDataWithCrc);
console.log("Step 16b: sending authorization data...");
this.state = nukible.prototype.STATE_PAIRING_SL_SEND_AUTH_ID;
this.nukiPairingGeneralDataIOCharacteristic.write(wDataWithCrc, false, callback);
} else {
callback("ERROR: not expected command id " + rCmd + ".");
}
} else {
callback("ERROR: wrong CRC.");
}
break;
case nukible.prototype.STATE_PAIRING_SL_SEND_AUTH_ID:
this.rData = Buffer.concat([this.rData, data]);
if (this.rData.length >= 88) {
if (this._crcOk(this.rData)) {
rCmd = this.rData.readUInt16LE(0);
if (rCmd === nukible.prototype.CMD_AUTHORIZATION_ID) {
console.log("Step 19: SL sent authorization id");
this.rData = this.rData.slice(2, this.rData.length - 2);
var slAuthenticator = this.rData.slice(0, 32);
var authorizationIdBuffer = this.rData.slice(32, 32 + 4);
var authorizationId = authorizationIdBuffer.readUInt32LE();
var slUuid = this.rData.slice(36, 36 + 16);
this.nonceK = this.rData.slice(36 + 16, 36 + 16 + 32);
// console.log("SL sent authenticator", slAuthenticator);
console.log("SL sent authorization-id " + authorizationId);
console.log("SL sent slUuid", slUuid.toString('hex'));
this.results = {
nukiUuid: slUuid.toString('hex'),
nukiAuthorizationId: authorizationId,
sharedSecret: this.options.sharedSecret.toString('hex')
};
console.log("Step 20: verifying authenticator...");
r = Buffer.concat([authorizationIdBuffer, slUuid, this.nonceK, this.nonceABF]);
// use HMAC-SHA256 to create the authenticator
var cr = crypto.createHmac('SHA256', this.options.sharedSecret).update(r).digest();
if (Buffer.compare(slAuthenticator, cr) === 0) {
console.log("Step 20: authenticator verified ok.");
console.log("Step 21: CL creating authorization-id confirmation message...");
r = Buffer.concat([authorizationIdBuffer, this.nonceK]);
// use HMAC-SHA256 to create the authenticator
authenticator = crypto.createHmac('SHA256', this.options.sharedSecret).update(r).digest();
wData = Buffer.concat([authenticator, authorizationIdBuffer]);
wDataWithCrc = this._prepareDataToSend(nukible.prototype.CMD_AUTHORIZATION_ID_CONFIRMATION, wData);
console.log("Step 21: sending authorization-id confirmation...");
this.state = nukible.prototype.STATE_PAIRING_SL_SEND_STATUS_COMLETE;
this.nukiPairingGeneralDataIOCharacteristic.write(wDataWithCrc, false, function (err) {
if (err) {
callback(err);
} else {
self.rData = new Buffer(0);
// console.log("CL Authorization-ID confirmation sent");
}
});
} else {
callback("CL and SL authenticators are not equal. Possible man in the middle attack.");
}
} else {
callback("ERROR: not expected command id " + rCmd + ".");
}
} else {
callback("ERROR: wrong CRC.");
}
}
break;
case nukible.prototype.STATE_PAIRING_SL_SEND_STATUS_COMLETE:
if (this._crcOk(data)) {
rCmd = data.readUInt16LE(0);
if (rCmd === nukible.prototype.CMD_STATUS) {
console.log("Step 22: SL sent status complete.");
callback(null, {status: 'paired', results: this.results});
} else {
callback("ERROR: not expected command id " + rCmd + ".");
}
} else {
callback("ERROR: wrong CRC.");
}
break;
default:
callback("ERROR: undefined state " + this.state);
}
},