-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathOnlyKeyComm.js
More file actions
2719 lines (2394 loc) · 84.5 KB
/
OnlyKeyComm.js
File metadata and controls
2719 lines (2394 loc) · 84.5 KB
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
const desktopApp = typeof nw !== "undefined";
let userPreferences, request;
if (desktopApp) {
userPreferences = require("./scripts/userPreferences.js");
request = require("request");
}
let backupsigFlag = -1;
let fwchecked = false;
let dialog;
let myOnlyKey;
let onlyKeyConfigWizard;
const DEVICE_TYPES = {
CLASSIC: "classic",
GO: "go",
};
const SUPPORTED_DEVICES = [
{
vendorId: 5824, //OnlyKey firmware before Beta 7
productId: 1158,
maxInputReportSize: 64,
maxOutputReportSize: 64,
maxFeatureReportSize: 0,
},
{
vendorId: 7504, //OnlyKey firmware Beta 7+ http://www.linux-usb.org/usb.ids
productId: 24828,
maxInputReportSize: 64,
maxOutputReportSize: 64,
maxFeatureReportSize: 0,
},
{
vendorId: 0000, //Black Vault Labs Bootloaderv1
productId: 45057,
maxInputReportSize: 64,
maxOutputReportSize: 64,
maxFeatureReportSize: 0,
},
];
function getSupportedDevice(deviceInfo) {
let supportedDevice;
for (let d = 0; d < SUPPORTED_DEVICES.length; d++) {
let device = SUPPORTED_DEVICES[d];
const isMatch = Object.keys(device).every(
(prop) => device[prop] == deviceInfo[prop]
);
if (isMatch) {
supportedDevice = device;
break;
}
}
return supportedDevice;
}
/* jshint esnext:true */
// A proxy for the Chrome HID service. Stored in a global variable so it is
// accessible for integration tests. We use this to simulate an OnlyKey being
// plugged into the computer.
const chromeHid = {
// chrome.hid.connect(integer deviceId, function callback)
connect: function (deviceId, callback) {
if (deviceId === "mockDevice") {
return callback({
connectionId: "mockConnection",
});
} else {
return chrome.hid.connect(deviceId, callback);
}
},
// chrome.hid.disconnect(integer connectionId, function callback)
disconnect: chrome.hid.disconnect,
// chrome.hid.getDevices(object options, function callback)
getDevices: chrome.hid.getDevices,
// chrome.hid.receive(integer connectionId, function callback)
receive: function (connectionId, callback) {
// console.log('>>> receive called with', arguments);
if (connectionId === "mockConnection") {
if (this._pendingReceive) {
throw "There must not be multiple pending receives.";
}
this._pendingReceive = callback;
} else {
return chrome.hid.receive(connectionId, callback);
}
},
mockResponse: function (response) {
// Response is [reportId, data]. Note that WebDriver.executeScript will
// convert the ArrayBuffer data to an object, so we have to convert it
// back.
var [reportId, data] = response;
response = [reportId, new Uint8Array(Object.values(data)).buffer];
if (!this._pendingReceive) {
throw "Expected a pending receive, found none.";
}
var callback = this._pendingReceive;
this._pendingReceive = null;
callback.apply(chrome.hid, response);
},
_pendingReceive: null,
// chrome.hid.send(integer connectionId, integer reportId, ArrayBuffer data, function callback)
send: function (connectionId, reportId, data, callback) {
// console.log('>>> send called with', arguments);
if (connectionId === "mockConnection") {
this._sent.push(arguments);
// Simulate a successful send operation by calling the callback
// without setting chrome.runtime.lastError.
callback();
} else {
chrome.hid.send(connectionId, reportId, data, callback);
}
},
_sent: [],
// Event: chrome.hid.onDeviceAdded
onDeviceAdded: {
addListener: function (callback) {
this._callbacks.push(callback);
return chrome.hid.onDeviceAdded.addListener(callback);
},
_callbacks: [],
mockDeviceAdded: function () {
this._callbacks.forEach(function (callback) {
callback.call(null, {
collections: [
{
reportIds: [],
usage: 1,
usagePage: 61904,
},
],
deviceId: "mockDevice",
maxFeatureReportSize: 0,
maxInputReportSize: 64,
maxOutputReportSize: 64,
productId: 1158,
productName: "Keyboard/RawHID",
reportDescriptor: {},
serialNumber: "4294967295",
vendorId: 5824,
});
});
},
},
// Event: chrome.hid.onDeviceRemoved
onDeviceRemoved: {
addListener: function (callback) {
return chrome.hid.onDeviceRemoved.addListener(callback);
},
},
};
function OnlyKeyHID(onlyKeyConfigWizardArg) {
onlyKeyConfigWizard = onlyKeyConfigWizardArg;
myOnlyKey = new OnlyKey();
dialog = new DialogMgr();
}
function OnlyKey(params = {}) {
this.connection = -1;
this.currentSlotId = null;
Object.assign(this, params.deviceInfo); // vendorId, productId, maxInputReportSize, etc
this.fwUpdateSupport = false;
this.isBootloader = false;
this.isLocked = true;
this.keyTypeModifiers = {
Backup: 128, // 0x80
Signature: 64, // 0x40
Decryption: 32, // 0x20
};
this.labels = [];
this.lastMessages = {
sent: [],
received: [],
};
this.messageHeader = [255, 255, 255, 255];
this.messageFields = {
LABEL: 1,
URL: 15,
NEXTKEY4: 18, //Before Username
NEXTKEY1: 16, //After Username
DELAY1: 17,
USERNAME: 2,
NEXTKEY5: 19, //Before OTP
NEXTKEY2: 3, //After Password
DELAY2: 4,
PASSWORD: 5,
NEXTKEY3: 6, //After OTP
DELAY3: 7,
TFATYPE: 8,
TFAUSERNAME: 9,
YUBIAUTH: 10,
YUBIANDHMAC: 29,
LOCKOUT: 11,
WIPEMODE: 12,
BACKUPKEYMODE: 20,
derivedchallengeMode: 21,
storedchallengeMode: 22,
SECPROFILEMODE: 23,
TYPESPEED: 13,
LEDBRIGHTNESS: 24,
LOCKBUTTON: 25,
hmacchallengeMode: 26,
modkeyMode: 27,
KBDLAYOUT: 14,
};
this.messages = {
OKSETPIN: 225, //0xE1
OKSETSDPIN: 226, //0xE2
OKSETPIN2: 227, //0xE3
OKSETTIME: 228, //0xE4
OKGETLABELS: 229, //0xE5
OKSETSLOT: 230, //0xE6
OKWIPESLOT: 231, //0xE7
OKGETPUBKEY: 236,
OKSIGN: 237,
OKWIPEPRIV: 238,
OKSETPRIV: 239,
OKDECRYPT: 240,
OKRESTORE: 241,
OKFWUPDATE: 244,
};
this.pendingMessages = {};
this.version = "";
}
OnlyKey.prototype.setConnection = function (connectionId) {
console.info("Setting connectionId to " + connectionId);
this.connection = connectionId;
if (connectionId === -1) {
myOnlyKey = new OnlyKey({
deviceInfo: this.deviceInfo,
});
myOnlyKey.setInitialized(false);
dialog.open(ui.disconnectedDialog);
} else {
dialog.open(ui.workingDialog);
onlyKeyConfigWizard.init(myOnlyKey);
}
};
OnlyKey.prototype.sendMessage = function (options, callback) {
var bytesPerMessage = 64;
var msgId =
typeof options.msgId === "string" ? options.msgId.toUpperCase() : null;
var slotId =
typeof options.slotId === "number" || typeof options.slotId === "string"
? options.slotId
: null;
var fieldId =
typeof options.fieldId === "string" || typeof options.fieldId === "number"
? options.fieldId
: null;
var contents =
typeof options.contents === "number" ||
(options.contents && options.contents.length)
? options.contents
: "";
var contentType =
(options.contentType && options.contentType.toUpperCase()) || "HEX";
callback = typeof callback === "function" ? callback : handleMessage;
var reportId = 0;
var bytes = new Uint8Array(bytesPerMessage);
var cursor = 0;
for (; cursor < this.messageHeader.length; cursor++) {
bytes[cursor] = this.messageHeader[cursor];
}
if (msgId && this.messages[msgId]) {
bytes[cursor] = strPad(this.messages[msgId], 2, 0);
cursor++;
}
if (slotId !== null) {
bytes[cursor] = strPad(slotId, 2, 0);
cursor++;
}
if (fieldId !== null) {
if (this.messageFields[fieldId]) {
bytes[cursor] = strPad(this.messageFields[fieldId], 2, 0);
} else {
bytes[cursor] = fieldId;
}
cursor++;
}
if (!Array.isArray(contents)) {
switch (typeof contents) {
case "string":
contents = contents.replace(
/\\x([a-fA-F0-9]{2})/g,
(match, capture) => {
return String.fromCharCode(parseInt(capture, 16));
}
);
for (var i = 0; i < contents.length && cursor < bytes.length; i++) {
if (contents.charCodeAt(i) > 255) {
throw "I am not smart enough to decode non-ASCII data.";
}
bytes[cursor++] = contents.charCodeAt(i);
}
break;
case "number":
if (contents < 0 || contents > 255) {
throw "Byte value out of bounds.";
}
bytes[cursor++] = contents;
break;
}
} else {
contents.forEach(function (val) {
bytes[cursor++] = contentType === "HEX" ? hexStrToDec(val) : val;
});
}
var pad = 0;
for (; cursor < bytes.length; ) {
bytes[cursor++] = pad;
}
console.info(
"SENDING " + msgId + " to connectionId " + this.connection + ":",
bytes
);
chromeHid.send(this.connection, reportId, bytes.buffer, async function () {
if (msgId != "OKFWUPDATE") await wait(100);
if (chrome.runtime.lastError) {
console.error(
"ERROR SENDING" + (msgId ? " " + msgId : "") + ":",
chrome.runtime.lastError,
{
connectionId: this.connection,
}
);
callback("ERROR SENDING PACKETS");
} else {
myOnlyKey.setLastMessage("sent", msgId);
callback(null, "OK");
}
});
};
OnlyKey.prototype.setLastMessage = function (type, msgStr = "") {
if (msgStr) {
var newMessage = {
text: msgStr,
timestamp: new Date().getTime(),
};
var messages = this.lastMessages[type] || [];
var numberToKeep = 3;
if (messages.length === numberToKeep) {
messages.slice(numberToKeep - 1);
}
messages = [newMessage].concat(messages);
this.lastMessages[type] = messages;
if (type === "received" && onlyKeyConfigWizard) {
onlyKeyConfigWizard.setLastMessages(messages);
}
}
};
OnlyKey.prototype.getLastMessage = function (type) {
return this.lastMessages[type] &&
this.lastMessages[type][0] &&
this.lastMessages[type][0].hasOwnProperty("text")
? this.lastMessages[type][0].text
: "";
};
OnlyKey.prototype.getLastMessageIndex = function (type, index) {
return this.lastMessages[type] &&
this.lastMessages[type][index] &&
this.lastMessages[type][index].hasOwnProperty("text")
? this.lastMessages[type][index].text
: "";
};
OnlyKey.prototype.flushMessage = async function (callback = () => {}) {
const messageTypes = Object.keys(this.pendingMessages);
const pendingMessagesTypes = messageTypes.filter(
(type) => this.pendingMessages[type] === true
);
if (!pendingMessagesTypes.length) {
console.info("No pending messages to flush.");
return callback();
}
const msgId = pendingMessagesTypes[0];
console.info(`Flushing pending ${msgId}.`);
this.sendPinMessage({ msgId, poll: false }, () => {
pollForInput({ flush: true }, (err, msg) => {
this.setLastMessage("received", "Canceled");
if (msg) {
console.info("Flushed previous message.");
return this.flushMessage(callback);
} else {
return callback();
}
});
});
};
OnlyKey.prototype.listenforvalue = async function (succeed_msg) {
await listenForMessageIncludes2("Error", succeed_msg).catch(error => {
throw error;
});
};
OnlyKey.prototype.listen = function (callback) {
pollForInput({}, callback);
};
OnlyKey.prototype.setTime = async function (callback) {
var currentEpochTime = Math.round(new Date().getTime() / 1000.0).toString(16);
console.info("Setting current epoch time =", currentEpochTime);
var timeParts = currentEpochTime.match(/.{2}/g);
// Send OKSETTIME Twice, fixes issue where when attaching OnlyKey to a VM response is not received
// Also clear out any rogue messages from other apps
var options = {
contents: timeParts,
msgId: "OKSETTIME",
};
this.sendMessage(options, this.sendMessage(options, callback));
};
OnlyKey.prototype.getLabels = async function (callback) {
this.labels = "";
await wait(900);
this.sendMessage(
{
msgId: "OKGETLABELS",
},
handleGetLabels
);
};
function handleGetLabels(err, msg) {
msg = typeof msg === "string" ? msg.trim() : "";
console.info("HandleGetLabels msg:", msg);
if (myOnlyKey.getLastMessage("sent") !== "OKGETLABELS") {
return;
}
if (myOnlyKey.labels === "") {
myOnlyKey.labels = [];
return myOnlyKey.listen(handleGetLabels);
}
// if second char of response is a pipe, theses are labels
var msgParts = msg.split("|");
var slotNum = parseInt(msgParts[0], 10);
if (
msg.includes("Error not in config mode") ||
myOnlyKey.getLastMessage("received") ==
"Error not in config mode, hold button 6 down for 5 sec"
) {
this.setLastMessage(
"received",
"Error not in config mode, hold button 6 down for 5 sec"
);
} else if (
msg.indexOf("|") !== 2 ||
typeof slotNum !== "number" ||
slotNum < 1 ||
slotNum > 12
) {
myOnlyKey.listen(handleGetLabels);
} else {
myOnlyKey.labels[slotNum - 1] = msgParts[1];
initSlotConfigForm();
if (slotNum < 12 && (msg.indexOf("|") == 2 || msg.indexOf("|") == 3)) {
myOnlyKey.listen(handleGetLabels);
}
}
}
OnlyKey.prototype.sendPinMessage = function (
{ msgId = "", pin = "", poll = true },
callback = () => {}
) {
this.pendingMessages[msgId] = !this.pendingMessages[msgId];
var cb = poll ? pollForInput.bind(this, {}, callback) : callback;
console.info(`sendPinMessage ${msgId}`);
const messageParams = {
msgId,
};
if (
myOnlyKey.getLastMessage("received") ==
"Error PIN is not between 7 - 10 digits"
) {
this.setLastMessage("received", "Canceled");
messageParams.msgId = "OKSETPIN";
messageParams.poll = false;
}
if (
myOnlyKey.getLastMessage("received").includes("UNLOCKED") ||
myOnlyKey.getLastMessage("received").includes("INITIALIZED")
) {
var cb2 = cb();
cb = pollForInput.bind(this, {}, cb2);
}
const deviceType = myOnlyKey.getDeviceType();
if (deviceType === DEVICE_TYPES.GO) {
messageParams.contents = pin;
messageParams.contentType = "DEC";
}
this.sendMessage(messageParams, cb);
console.info("last messages");
console.info(myOnlyKey.getLastMessageIndex("received", 0));
console.info(myOnlyKey.getLastMessageIndex("received", 1));
};
OnlyKey.prototype.sendSetPin = function (callback) {
console.info("sendSetPin");
this.sendPinMessage(
{
msgId: "OKSETPIN",
},
callback
);
};
OnlyKey.prototype.sendSetSDPin = function (callback) {
this.sendPinMessage(
{
msgId: "OKSETSDPIN",
},
callback
);
};
OnlyKey.prototype.sendSetPin2 = function (callback) {
this.sendPinMessage(
{
msgId: "OKSETPIN2",
},
callback
);
};
OnlyKey.prototype.sendPin_GO = function (pins, callback) {
// if only 1 pin is sent, just send those pin chars as a login attempt
// otherwise, concatenate all PINs sent and fill with null (hex 0)
const pinCount = pins.length;
const bytesPerPin = 16;
const pinBytesLength =
pinCount === 1 ? pins[0].length : pinCount * bytesPerPin;
let pinBytes = new Array(pinBytesLength).fill(0);
pins.forEach((pin, i) => {
if (typeof pin !== "string") pin = "";
// PIN chars should only be ascii 0-9
// add 48 to send as DEC
pin
.split("")
.forEach((char, j) => (pinBytes[i * 16 + j] = 48 + Number(char)));
});
this.sendPinMessage(
{
// msgId: pinCount === 1 ? 'OKPIN' : 'OKSETPIN',
msgId: "OKSETPIN",
pin: pinBytes,
},
async () => {
// Check if PIN attempts exceeded
if (
myOnlyKey
.getLastMessage("received")
.indexOf("Error password attempts for this session exceeded") === 0
) {
document.getElementById("locked-text-go").innerHTML =
"To prevent lockout OnlyKey only permits 3 failed PIN attempts at a time, please remove and reinsert OnlyKey to try again.";
console.info("PIN attempts exeeded");
} else {
document.getElementById("locked-text-go").innerHTML = `
<h3>Please enter your PIN</h3>
<form name="unlockOkGoForm" id="unlockOkGoForm">
<input type="password" name="unlockOkGoPin" id="unlockOkGoPin" />
<input type="button" name="unlockOkGoSubmit" id="unlockOkGoSubmit" value="Unlock" />
</form>
`;
}
return callback();
}
);
};
OnlyKey.prototype.setSlot = function (slotArg, field, value, callback) {
let slot = slotArg || this.getSlotNum();
if (typeof slot !== "number") slot = this.getSlotNum(slot);
var options = {
contents: value,
msgId: "OKSETSLOT",
slotId: slot,
fieldId: field,
};
this.sendMessage(options, callback);
};
OnlyKey.prototype.wipeSlot = function (slot, field, callback) {
slot = slot || this.getSlotNum();
if (typeof slot !== "number") slot = this.getSlotNum(slot);
var options = {
msgId: "OKWIPESLOT",
slotId: slot,
fieldId: field || null,
};
this.sendMessage(options, callback);
};
OnlyKey.prototype.getSlotNum = function (slotId) {
slotId = slotId || this.currentSlotId;
var parts = slotId.split("");
return parseInt(parts[0], 10) + (parts[1].toLowerCase() === "a" ? 0 : 6);
};
OnlyKey.prototype.setYubiAuth = function (
publicId,
privateId,
secretKey,
callback
) {
this.setSlot(
"XX",
"YUBIAUTH",
(publicId + privateId + secretKey).match(/.{2}/g),
async () => {
await this.listenforvalue("set AES Key");
return callback();
}
);
};
OnlyKey.prototype.wipeYubiAuth = function (callback) {
this.wipeSlot("XX", "YUBIAUTH", async () => {
await this.listenforvalue("wiped AES Key");
return callback();
});
};
OnlyKey.prototype.setRSABackupKey = async function (key, passcode, cb) {
var privKey;
let error;
try {
var privKeys = await openpgp.key.readArmored(key);
privKey = privKeys.keys[0];
var success = privKey.decrypt(passcode);
if (!success) {
error = "Private Key decryption failed.";
this.setLastMessage("received", error + " Did you forget your passcode?");
throw Error(error);
}
if (!(privKey.primaryKey && privKey.primaryKey.params)) {
error =
"Private Key decryption was successful, but resulted in invalid mpi data.";
this.setLastMessage("received", error);
throw Error(error);
}
if (
!(
privKey.primaryKey &&
privKey.primaryKey.params &&
privKey.primaryKey.params.length === 6
)
) {
error =
"Private Key decryption was successful, but resulted in invalid mpi data.";
this.setLastMessage("received", error);
throw Error(error);
}
} catch (parseError) {
error = "Error parsing RSA key.";
this.setLastMessage("received", error);
throw Error(error + "\n\n" + parseError);
}
return onlyKeyConfigWizard.initKeySelect(privKey, function (err) {
ui.rsaForm.setError(err || "");
if (typeof cb === "function") cb(err);
});
};
OnlyKey.prototype.setBackupPassphrase = async function (passphrase, cb) {
// abcdefghijklmnopqrstuvwxyz
let key, type, slot;
try {
key = await Array.from(openpgp.crypto.hash.digest(8, passphrase)); // 32 byte backup key is Sha256 hash of passphrase
type = 161; //Backup and Decryption key
slot = 131;
} catch (e) {
return cb(e);
}
this.setPrivateKey(slot, type, key, async function (err) {
onlyKeyConfigWizard.initForm.reset();
await wait(300);
await listenForMessageIncludes2(
"Error not in config mode, hold button 6 down for 5 sec",
"Success"
);
cb(err);
});
};
OnlyKey.prototype.submitFirmware = function (fileSelector, cb) {
if (fileSelector.files && fileSelector.files.length) {
var file = fileSelector.files[0];
var reader = new FileReader();
reader.onload = (function (theFile) {
return async function (e) {
let contents = e.target && e.target.result && e.target.result.trim();
try {
console.info("unparsed contents", contents);
contents = parseFirmwareData(contents);
console.info("parsed contents", contents);
} catch (parseError) {
throw new Error("Could not parse firmware file.\n\n" + parseError);
}
if (contents) {
onlyKeyConfigWizard.newFirmware = contents;
if (!myOnlyKey.isBootloader) {
console.info("Working... Do not remove OnlyKey");
const temparray = "1234";
submitFirmwareData(temparray, function (err) {
//First send one message to kick OnlyKey (in config mode) into bootloader
console.info("Firmware file sent to OnlyKey");
myOnlyKey.listen(handleMessage); //OnlyKey will respond with "SUCCESSFULL FW LOAD REQUEST, REBOOTING..." or "ERROR NOT IN CONFIG MODE, HOLD BUTTON 6 DOWN FOR 5 SEC"
});
} else {
await loadFirmware();
}
} else {
throw new Error("Incorrect firmware data format.");
}
};
})(file);
// Read in the image file as a data URL.
reader.readAsText(file);
} else {
throw new Error("Please select a file first.");
}
};
OnlyKey.prototype.submitRestore = function (fileSelector, cbArg) {
const cb = typeof cbArg === "function" ? cbArg : () => {};
const _this = this;
ui.restoreForm.setError("");
if (fileSelector.files && fileSelector.files.length) {
var file = fileSelector.files[0];
var reader = new FileReader();
reader.onload = (function (theFile) {
return function (e) {
var contents = e.target && e.target.result && e.target.result.trim();
try {
contents = parseBackupData(contents);
} catch (parseError) {
const error = "Could not parse backup file.";
_this.setLastMessage("received", error);
throw Error(error + "\n\n" + parseError);
}
if (contents) {
var step10text = document.getElementById("step10-text");
step10text.innerHTML =
"Restoring from backup please wait...<br><br>" +
"<img src='/images/Pacman-0.8s-200px.gif' height='40' width='40'><br><br>";
submitRestoreData(contents, async function (err) {
if (err) {
_this.setLastMessage(error);
throw Error(error);
}
_this.setLastMessage("Backup file sent to OnlyKey, please wait...");
await wait(10000);
step10text.innerHTML = "";
cb();
});
} else {
const error = "Incorrect backup data format.";
_this.setLastMessage(error);
throw Error(error);
}
};
})(file);
// Read in the image file as a data URL.
reader.readAsText(file);
} else {
var contents = "000000000";
submitRestoreData(contents, function (err) {
if (err) {
_this.setLastMessage(error);
throw Error(error);
}
_this.setLastMessage("Backup file sent to OnlyKey.");
cb();
});
}
};
OnlyKey.prototype.setPrivateKey = function (slot, type, key, callback) {
var msg, contentType;
if (Array.isArray(key) || key.constructor === Uint8Array) {
// RSA private key is an array of DEC bytes
contentType = "DEC";
msg = key;
} else {
// private key strings should be pairs of HEX bytes
msg = key.match(/.{2}/g);
}
var options = {
contents: msg,
msgId: "OKSETPRIV",
slotId: slot,
fieldId: type,
contentType: contentType,
};
this.sendMessage(options, callback);
};
OnlyKey.prototype.wipePrivateKey = function (slot, callback) {
var options = {
msgId: "OKWIPEPRIV",
slotId: slot,
};
this.sendMessage(options, callback);
};
OnlyKey.prototype.restore = async function (
restoreData,
packetHeader,
callback
) {
var msg = [packetHeader];
msg = msg.concat(restoreData.match(/.{2}/g));
var options = {
contents: msg,
msgId: "OKRESTORE",
};
this.sendMessage(options, callback);
};
OnlyKey.prototype.firmware = async function (
firmwareData,
packetHeader,
callback
) {
var msg = [packetHeader];
msg = msg.concat(firmwareData.match(/.{2}/g));
var options = {
contents: msg,
msgId: "OKFWUPDATE",
};
console.info("OKFWUPDATE message sent ");
console.info(options);
this.sendMessage(options, callback);
};
OnlyKey.prototype.setLockout = function (lockout, callback) {
this.setSlot("XX", "LOCKOUT", lockout, async () => {
await this.listenforvalue("set idle timeout");
return callback();
});
};
OnlyKey.prototype.setWipeMode = function (wipeMode) {
this.setSlot("XX", "WIPEMODE", wipeMode, async () => {
return await this.listenforvalue("set Wipe Mode");
});
};
OnlyKey.prototype.setSecProfileMode = function (secProfileMode, callback) {
secProfileMode = parseInt(secProfileMode, 10);
var options = {
contents: secProfileMode,
msgId: "OKSETSLOT",
slotId: "XX",
fieldId: "SECPROFILEMODE",
};
this.sendMessage(options, callback);
};
OnlyKey.prototype.setderivedchallengeMode = function (derivedchallengeMode) {
this.setSlot("XX", "derivedchallengeMode", derivedchallengeMode, async () => {
return await this.listenforvalue("challenge mode");
});
};
OnlyKey.prototype.setstoredchallengeMode = function (storedchallengeMode) {
this.setSlot("XX", "storedchallengeMode", storedchallengeMode, async () => {
return await this.listenforvalue("challenge mode");
});
};
OnlyKey.prototype.sethmacchallengeMode = function (hmacchallengeMode) {
this.setSlot("XX", "hmacchallengeMode", hmacchallengeMode, async () => {
return await this.listenforvalue("HMAC Challenge Mode");
});
};
OnlyKey.prototype.setmodkeyMode = function (modkeyMode) {
this.setSlot("XX", "modkeyMode", modkeyMode, async () => {
return await this.listenforvalue("Sysadmin Mode");
});
};
OnlyKey.prototype.setbackupKeyMode = function (backupKeyMode, callback) {
backupKeyMode = parseInt(backupKeyMode, 10);
const cb = callback || async function () {
await this.listenforvalue("set Backup Key Mode");
}.bind(this);
return this.setSlot("XX", "BACKUPKEYMODE", backupKeyMode, cb);
};
OnlyKey.prototype.setTypeSpeed = function (typeSpeed) {
this.setSlot("XX", "TYPESPEED", typeSpeed, async () => {
return await this.listenforvalue("set keyboard typespeed");
});
};
OnlyKey.prototype.setLedBrightness = function (ledBrightness) {
this.setSlot("XX", "LEDBRIGHTNESS", ledBrightness, async () => {
return await this.listenforvalue("set LED brightness");
});
};
OnlyKey.prototype.setLockButton = function (lockButton) {
this.setSlot("XX", "LOCKBUTTON", lockButton, async () => {
return await this.listenforvalue("set lock button");
});
};
OnlyKey.prototype.setKBDLayout = function (kbdLayout) {
this.setSlot("XX", "KBDLAYOUT", kbdLayout, async () => {
return await this.listenforvalue("set keyboard layout");
});
};
OnlyKey.prototype.setVersion = function (version) {
this.version = version;
};
OnlyKey.prototype.getVersion = function () {
return this.version;
};