-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnox-main.js
707 lines (673 loc) · 24.2 KB
/
nox-main.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
/* jshint node: true, esversion: 6 */
"use strict";
// Module to control application life.
const {app} = require('electron');
// Module to create native browser window.
const {BrowserWindow} = require('electron');
var
Path = require('path'),
http = require('http'),
DataFile = require('./DataFile'),
// communications functions
NoxiousClient = require('./NoxiousClient'),
myNoxClient = new NoxiousClient(),
// cononical json.stringify
// Stringify objects in a consistent way prior to hashing/signing
jsStringify = require('canonical-json'),
contactList =
new DataFile(Path.join(app.getPath('userData'), 'Contacts.json')),
contactRequestList =
new DataFile(Path.join(app.getPath('userData'), 'ContactRequests.json')),
thsBuilder = require('ths'),
ths = new thsBuilder(app.getPath('userData')),
fork = require('child_process').fork,
cryptoWorker = fork('./cryptoWorker.js'),
NoxiousCrypto = require('./NoxiousCrypto'),
myCrypto = new NoxiousCrypto({
path: Path.join(app.getPath('userData'), 'PrivateKey.json')
}),
dataTransmitDomain = require('domain').create(),
contactRequestDomain = require('domain').create(),
myAddress;
function notifyCommError(error) {
let msgObj = {};
msgObj.method = 'error';
switch(error) {
case 'EHOSTUNREACH':
msgObj.content = {
type: 'communication',
message: 'The recipient does not appear to be online at this time. ' +
'Try again later.'};
break;
case 'ETTLEXPIRED':
msgObj.content = {
type: 'communication',
message: 'There seems to be trouble with your Internet connection. ' +
'Try again later.'};
break;
default:
msgObj.content = {
type: 'communication',
message: 'A communication error occurred, see the console log for ' +
'more information.'};
break;
}
notifyGUI(msgObj);
}
dataTransmitDomain.on('error', function(err) {
console.log(err);
notifyCommError(err.code);
});
contactRequestDomain.on('error', function(err) {
console.log(err);
notifyCommError(err.code);
updateRequestStatus(err.domainEmitter._dstaddr, 'failed');
});
function notifyGUI(msg) {
if(!mainWindow.webContents.isLoading()) {
mainWindow.webContents.send(msg.method, msg.content);
}
}
function isValidTorHiddenServiceName(name) {
let toReturn = false;
if(name.search(/^[a-zA-Z2-7]{16}\.onion$/) != -1) {
// it matched
toReturn = true;
}
return toReturn;
}
function getContacts(forceReload) {
if(contactList.size() > 0 || forceReload) {
var msgObj = {};
msgObj.method = 'contact';
msgObj.content = {
type: 'initContactList', contactList: contactList.getAll()
};
notifyGUI(msgObj);
}
}
function getContactRequests() {
let msgObj = {};
msgObj.method = 'contact';
if(contactRequestList.size() > 0) {
msgObj.content = {
type: 'initContactRequestList',
contactRequestList: contactRequestList.getAll()
};
} else {
msgObj.content = {
type: 'clearContactRequestList', contactRequestList: {}
};
}
notifyGUI(msgObj);
}
function updateRequestStatus(contactAddress, status, updateGui) {
if(updateGui === undefined) {
updateGui = true;
}
let tmpContact = contactRequestList.get(contactAddress);
tmpContact.status = status;
contactRequestList.set(contactAddress, tmpContact);
if(updateGui) {
getContactRequests();
}
}
function buildEncryptedMessage(destAddress, msgText) {
let tmpCrypto =
new NoxiousCrypto({'pubPem': contactList.get(destAddress).pubPem});
let msgContent = {};
msgContent.type = 'message';
msgContent.from = myAddress;
msgContent.to = destAddress;
msgContent.msgText = msgText;
let msgObj = {};
msgObj.content = msgContent;
// sign using my private key
msgObj.signature = myCrypto.signString(jsStringify(msgContent));
// encrypt using recipients public key
let encryptedData = tmpCrypto.encrypt(JSON.stringify(msgObj));
let encObj = {};
encObj.content = {
type: 'encryptedData', clearFrom: myAddress, data: encryptedData
};
encObj.protocol = '1.0';
return encObj;
}
function buildContactRequest(destAddress) {
let introObj = {};
introObj.type = 'introduction';
introObj.from = myAddress;
introObj.to = destAddress;
introObj.pubPem = myCrypto.pubPem;
let msgObj = {};
msgObj.content = introObj;
msgObj.signature = myCrypto.signString(jsStringify(introObj));
msgObj.protocol = '1.0';
return msgObj;
}
function transmitContactRequest(destAddress) {
contactRequestDomain.run(function() {
myNoxClient.transmitObject(
destAddress, buildContactRequest(destAddress), function(res) {
switch(res.status) {
case 200:
updateRequestStatus(destAddress, 'delivered');
break;
case 409:
updateRequestStatus(destAddress, 'failed');
var msgObj = {};
msgObj.method = 'error';
var failedReason = res.body.reason;
switch(failedReason) {
case 'EKEYSIZE':
msgObj.content = {
type: 'contact',
message: 'The contact request was rejected because your ' +
'public encryption key is not proper. Please upgrade your ' +
'Noxious software.'};
break;
case 'EPROTOCOLVERSION':
msgObj.content = {
type: 'contact',
message: 'The contact request was rejected because the ' +
'message format is not proper. Please upgrade your ' +
'Noxious software.'};
break;
default:
msgObj.content = {
type: 'contact',
message: 'The recipient already has your contact ' +
'information. Ask them to delete your contact ' +
'information and try again.'};
break;
}
notifyGUI(msgObj);
break;
}
});
});
}
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the javascript object is GCed.
var mainWindow = null;
var pageLoaded = false;
var server = http.createServer(function(req, res) {
if(req.method === 'GET') {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello world!');
} else if(req.method === 'POST') {
if(req.url === '/') {
var reqBody = '';
req.on('data', function(d) {
reqBody += d;
if(reqBody.length > 1e7) {
res.writeHead(
413, 'Request Entity Too Large', {'Content-Type': 'text/html'});
res.end('<!doctype html><html><head><title>413</title></head>' +
'<body>413: Request Entity Too Large</body></html>');
}
});
req.on('end', function() {
console.log('[HTTP Server] ', reqBody);
let status = preProcessMessage(reqBody);
if(status.code == 200) {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify({status: 'OK'}));
processMessage(reqBody);
} else {
res.writeHead(status.code, {'Content-Type': 'application/json'});
res.end(JSON.stringify({reason: status.reason}));
}
});
}
}
});
server.listen(1111, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1111');
function relayMessage(msg) {
mainWindow.webContents
.send('msg', 'from: ' + msg.name + ' message: ' + msg.message);
}
function registerContactRequest(req) {
// add to list of other contact requests for saving to disk
// build object
// TODO is a date/time wanted or needed here? Other Data?
// this same data structure is copied to the contact list upon acceptance.
var tmpObj = {};
tmpObj.pubPem = req.pubPem ;
tmpObj.contactAddress = req.from;
// check for dups in requests list and contact list
if(!contactRequestList.has(req.from) && !contactList.has(req.from)) {
// this is a new incoming contact Request
console.log('[contact] New Contact Request Received');
tmpObj.direction = 'incoming';
contactRequestList.set(req.from, tmpObj);
let msgObj = {};
msgObj.method = 'contact';
msgObj.content = {
type: 'contactRequest', from: req.from, direction: 'incoming'
};
notifyGUI(msgObj);
} else if(contactRequestList.has(req.from) &&
contactRequestList.get(req.from).direction == 'outgoing') {
// this person accepted a contact request
contactList.set(
req.from, {
pubPem: tmpObj.pubPem, contactAddress: tmpObj.contactAddress
});
contactRequestList.delete(req.from);
getContacts();
getContactRequests();
} else if(contactRequestList.get(req.from)) {
console.log('[contact] Contact request is from an existing contact.');
}
}
function preProcessMessage(msg) {
// default statusCode = forbidden;
var status = {};
status.code = 403;
status.reason = '';
var msgObj = JSON.parse(msg);
console.log('[preProcessMessage] Start');
// TODO this function should verify message integrity
if(msgObj.protocol === '1.0') {
if(msgObj.content !== undefined) {
var content = msgObj.content;
if(content.type !== undefined) {
switch(content.type) {
case 'introduction':
if(content.from !== undefined && content.from &&
isValidTorHiddenServiceName(content.from)) {
if(!contactList.has(content.from) &&
!contactRequestList.has(content.from)) {
// we don't know this person already, intro is OK
status.code = 200;
} else if(contactRequestList.has(content.from) &&
contactRequestList.get(content.from).direction == 'outgoing' &&
contactRequestList.get(content.from).status == 'delivered') {
// we're expecting to hear back from this person, intro is OK
status.code = 200;
} else {
// contact request (key exchange) process needs to be repeated.
status.code = 409;
}
}
if(status.code === 200) {
// so far so good, but now check the pubkey, reset status code
status.code = 403;
var minKeySize = 3072;
var tmpCrypto = new NoxiousCrypto({'pubPem': content.pubPem});
var keySize = tmpCrypto.keySize;
console.log(
'[preprocessing message] The key size is ', keySize, 'bits.');
if(keySize < minKeySize) {
console.log(
'[preprocessing message] The key must be at least ',
minKeySize, ' bits');
status.code = 409;
status.reason = 'EKEYSIZE';
} else {
console.log(
'[preprocessing message] The key size meets the ',
minKeySize, 'bit requirement');
status.code = 200;
}
}
break;
case 'encryptedData':
if(content.clearFrom !== undefined && content.clearFrom &&
isValidTorHiddenServiceName(content.clearFrom)) {
if(contactList.has(content.clearFrom)) {
// this is from an existing contact, it's OK
status.code = 200;
} else {
// there is no public key for this contact
status.code = 410;
}
}
break;
}
}
} else {
// protocol version mismatch
console.log('[preprocessing message] Protocol version mismatch.');
status.code = 409;
status.reason = 'EPROTOCOLVERSION';
}
}
return status;
}
cryptoWorker.on('message', function(msgObj) {
switch(msgObj.type) {
case 'decryptedData':
var decObj = msgObj.data;
// console.log('Decrypted Data: ', decObj);
var content = decObj.content;
var signature = decObj.signature;
// TODO additional integrity checks?
if(content.to && content.to == myAddress && content.from &&
isValidTorHiddenServiceName(content.from) && content.type &&
content.msgText) {
if(contactList.has(content.from)) {
switch(content.type) {
case 'message':
var tmpCrypto = new NoxiousCrypto({
'pubPem': contactList.get(content.from).pubPem
});
if(tmpCrypto.signatureVerified(jsStringify(content), signature)) {
console.log('[process message] Message is properly signed.');
if(content.to == myAddress && content.from !== undefined &&
content.from && content.from !== myAddress) {
console.log(
'[process message] Message is properly addressed.');
var incomingMessage = {
method: 'message',
content: {
type: 'message',
from: content.from,
msgText: content.msgText
}
};
notifyGUI(incomingMessage);
}
} else {
console.log('[process message] Message is NOT properly ' +
'signed. Disregarding.');
}
break;
}
}
}
break;
}
});
function processMessage(msg) {
var msgObj = JSON.parse(msg);
var content = msgObj.content;
switch(content.type) {
case 'introduction':
var signature = msgObj.signature;
var tmpCrypto = new NoxiousCrypto({'pubPem': content.pubPem});
if(tmpCrypto.signatureVerified(jsStringify(content), signature)) {
console.log('[process message] Introduction is properly signed.');
// TODO enhance from address checking, for now, not null or undefined,
// and not myAddress
if(content.to == myAddress && content.from !== undefined &&
content.from && content.from !== myAddress) {
// content.to and content.from are part of the signed content.
console.log('[process message] Introduction is properly addressed.');
registerContactRequest(content);
}
} else {
console.log('[process message] Introduction is NOT properly signed. ' +
'Disregarding.');
}
break;
case 'encryptedData':
var workerMsg = {};
workerMsg.type = 'decrypt';
workerMsg.data = content.data;
cryptoWorker.send(workerMsg);
break;
}
}
function startHiddenService() {
// we know that tor is loaded and web page is loaded.
var serviceList = ths.getServices();
console.log('Service List: %j',serviceList);
function noxiousExists(element) {
return element.name === 'noxious';
}
var noxiousProperties = serviceList.filter(noxiousExists);
if(noxiousProperties === 0) {
// does not exist, create it
console.log('Creating new noxious service');
ths.createHiddenService('noxious','1111');
ths.saveConfig();
// FIXME: https://github.com/Mowje/node-ths/issues/5
var myDelegate = function() {
ths.signalReload();
};
var myVar = setTimeout(myDelegate, 250);
}
// FIXME: does not work properly on initial startup:
// https://github.com/Mowje/node-ths/issues/3
ths.getOnionAddress('noxious', function(err, onionAddress) {
if(err) {
console.error(
'[getOnionAddress] Error while reading hostname file: ' + err);
} else {
console.log('[getOnionAddress] Onion Address is: ', onionAddress);
myAddress = onionAddress;
var msgObj = {};
msgObj.method = 'status';
msgObj.content = {type: 'onionAddress', content: myAddress};
notifyGUI(msgObj);
}
});
}
// track ths / tor bootstrapping
ths.on('bootstrap', function(state) {
var msgObj = {};
msgObj.method = 'status';
msgObj.content = {type: 'bootstrap', content: state};
notifyGUI(msgObj);
});
// This method will be called when atom-shell has done everything
// initialization and ready for creating browser windows.
app.on('ready', function() {
// handles communication between browser and io.js (webpage)
const {ipcMain} = require('electron');
// var ipc = require('ipc');
var workerMsg = {};
workerMsg.type = 'init';
workerMsg.pathToKey = {
path: Path.join(app.getPath('userData'), 'PrivateKey.json')
};
cryptoWorker.send(workerMsg);
// Create the browser window.
mainWindow = new BrowserWindow({width: 900, height: 600});
ths.start(false, function() {
console.log("tor Started!");
if(!mainWindow.webContents.isLoading()) {
startHiddenService();
}
});
// and load the index.html of the app.
mainWindow.loadURL('file://' + __dirname + '/index.html');
mainWindow.webContents.on('did-finish-load', function() {
console.log('[webContents] Finished loading.');
getContacts();
getContactRequests();
});
ipcMain.on('message', function(event, content) {
console.log('[message event] ', content);
switch(content.type) {
case 'sendEncrypted':
var encObj =
buildEncryptedMessage(content.destAddress, content.msgText);
dataTransmitDomain.run(function() {
myNoxClient.transmitObject(
content.destAddress, encObj, function(res) {
var msgObj = {};
switch(res.status) {
case 200:
// OK
msgObj.method = 'message';
msgObj.content = {
type: 'status', status: 'delivered', msgId: content.msgId
};
notifyGUI(msgObj);
break;
case 410:
// recipient does not have the public key (anymore)
msgObj.method = 'error';
msgObj.content = {
type: 'message',
message: 'The recipient no longer has you in their ' +
'contact list. Delete the contact, then send a contact ' +
'request.'};
notifyGUI(msgObj);
msgObj.method = 'message';
msgObj.content = {
type: 'status', status: 'failed', msgId: content.msgId
};
notifyGUI(msgObj);
break;
case 409:
var failedReason = res.body.reason;
switch(failedReason) {
case 'EPROTOCOLVERSION':
msgObj.method = 'error';
msgObj.content = {
type: 'message',
message: 'The message was rejected because the ' +
'message format is not proper. Please upgrade your ' +
'Noxious software.'};
notifyGUI(msgObj);
msgObj.method = 'message';
msgObj.content = {
type: 'status', status: 'failed', msgId: content.msgId
};
notifyGUI(msgObj);
break;
}
break;
}
});
});
break;
}
});
ipcMain.on('contact', function(event, content) {
console.log('[contact event] ', content);
switch(content.type) {
case 'acceptContactRequest':
// user has chosen to accept the contact request
// send a contact request to sender to provide pubKey
updateRequestStatus(content.contactAddress, 'sending', false);
contactRequestDomain.run(function() {
myNoxClient.transmitObject(
content.contactAddress, buildContactRequest(content.contactAddress),
function(res) {
if(res.status == 200) {
contactList.set(
content.contactAddress, {
pubPem: contactRequestList
.get(content.contactAddress).pubPem,
contactAddress: content.contactAddress
});
contactRequestList.delete(content.contactAddress);
getContacts();
getContactRequests();
} else if(res.status == 409) {
// this can occur in a case where a successfully transmitted
// contact request is deleted before a reply is sent.
updateRequestStatus(content.contactAddress, 'failed');
var msgObj = {};
msgObj.method = 'error';
var failedReason = res.body.reason;
switch(failedReason) {
case 'EKEYSIZE':
msgObj.content = {
type: 'contact',
message: 'The contact request was rejected because ' +
'your public encryption key is not proper. Please ' +
'upgrade your Noxious software.'};
break;
default:
msgObj.content = {
type: 'contact',
message: 'The recipient already has your contact ' +
'information. Ask them to delete your contact ' +
'information and try again.'};
break;
}
notifyGUI(msgObj);
}
});
});
break;
case 'delContactRequest':
contactRequestList.delete(content.contactAddress);
break;
case 'declineContactRequest':
contactRequestList.delete(content.contactAddress);
getContactRequests();
break;
case 'sendContactRequest':
var msgObj = {};
// do not send request to myAddress or to existing contacts
if(content.contactAddress === myAddress) {
msgObj.method = 'error';
msgObj.content = {
type: 'contact',
message: 'You may not send a contact request to your own ' +
'Client ID.'};
notifyGUI(msgObj);
} else if(contactList.has(content.contactAddress)) {
msgObj.method = 'error';
msgObj.content = {
type: 'contact',
message: 'You may not send a contact request to an existing ' +
'contact. Delete the contact and try again.'};
notifyGUI(msgObj);
} else if(contactRequestList.get(content.contactAddress)) {
msgObj.method = 'error';
msgObj.content = {
type: 'contact',
message: 'There is already a pending contact request for this ' +
'Client ID. Delete the contact request and try again.'};
notifyGUI(msgObj);
} else {
transmitContactRequest(content.contactAddress);
var contactRequest = {
contactAddress: content.contactAddress,
direction: 'outgoing', status: 'sending'
};
contactRequestList.set(content.contactAddress, contactRequest);
// reinit the request list
getContactRequests();
}
break;
case 'retryContactRequest':
// user wants to resend a failed failed contact requests
// the address has already passed inspection and the GUI has been
// set to show sending status
transmitContactRequest(content.contactAddress);
break;
case 'setNickName':
var contactInfo = contactList.get(content.contactAddress);
contactInfo.nickName = content.nickName;
contactList.set(content.contactAddress, contactInfo);
break;
case 'delNickName':
var contactInfoDel = contactList.get(content.contactAddress);
contactInfoDel.nickName = '';
contactList.set(content.contactAddress, contactInfoDel);
break;
case 'delContact':
contactList.delete(content.contactAddress);
getContacts(true);
break;
}
});
// Emitted when the window is closed.
mainWindow.on('closed', function() {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
});
});
app.on('before-quit', function(e) {
if(ths.isTorRunning()) {
e.preventDefault();
ths.stop(function() {
console.log("tor has been stopped");
app.quit();
});
}
cryptoWorker.kill();
console.log('I\'m quitting.');
});