-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhpka.js
More file actions
1860 lines (1725 loc) · 73.5 KB
/
hpka.js
File metadata and controls
1860 lines (1725 loc) · 73.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
var cryptopp;
try {
cryptopp = require('cryptopp');
} catch (e){
}
var sodium;
try {
sodium = require('sodium');
} catch (e){
}
//FormData. Renaming it this way because I'm afraid it will conflict with the original FormData in case of usage in node-webkit
var fd;
try {
fd = require('form-data');
} catch (e){
}
if (!(sodium || cryptopp)) throw new Error('No sodium or cryptopp modules found. At least one of them must be installed');
//Temporary constraint in v0.3
if (!sodium && cryptopp){
throw new Error('In this version, node-cryptopp support has been disabled (because this module this not ready for actual use)');
}
var assert = require('assert');
var fs = require('fs');
var Buffer = require('buffer').Buffer;
var http = require('http');
var https = require('https');
var url = require('fast-url-parser');
var _HPKAReq = require('./HPKAReq');
var publicKeyUtils = require('./publicKeyUtils');
exports.publicKeyUtils = publicKeyUtils;
var absMaxForSessionTTL = 45 * 365.25 * 24 * 3600; //1/1/2015 00:00:00 UTC, in seconds. A threshold just helping us determine whether the provided wantedSessionExpiration is a TTL or a timestamp
function showCriticalError(m){
console.error('\n------------------------------------------------------------\n');
console.error(m);
console.error('\n------------------------------------------------------------\n');
}
exports.supportedAlgorithms = function(){
var algos = [];
if (cryptopp){
algos.push('ecdsa');
algos.push('rsa');
algos.push('dsa');
}
if (sodium){
algos.push('ed25519');
}
return algos;
}
var getCurveID = function(curveName){
//Prime curves
if (curveName == 'secp112r1') return 0x01;
else if (curveName == 'secp112r2') return 0x02;
else if (curveName == 'secp128r1') return 0x03;
else if (curveName == 'secp128r2') return 0x04;
else if (curveName == 'secp160r1') return 0x05;
else if (curveName == 'secp160r2') return 0x06;
else if (curveName == 'secp160k1') return 0x07;
else if (curveName == 'secp192r1') return 0x08;
else if (curveName == 'secp192k1') return 0x09;
else if (curveName == 'secp224r1') return 0x0A;
else if (curveName == 'secp224k1') return 0x0B;
else if (curveName == 'secp256r1') return 0x0C;
else if (curveName == 'secp256k1') return 0x0D;
else if (curveName == 'secp384r1') return 0x0E;
else if (curveName == 'secp521r1') return 0x0F; //End of prime curves, first binary curve
else if (curveName == 'sect113r1') return 0x80;
else if (curveName == 'sect113r2') return 0x81;
else if (curveName == 'sect131r1') return 0x82;
else if (curveName == 'sect131r2') return 0x83;
else if (curveName == 'sect163r1') return 0x84;
else if (curveName == 'sect163r2') return 0x85;
else if (curveName == 'sect163k1') return 0x86;
else if (curveName == 'sect193r1') return 0x87;
else if (curveName == 'sect193r2') return 0x88;
else if (curveName == 'sect233r1') return 0x89;
else if (curveName == 'sect233k1') return 0x8A;
else if (curveName == 'sect239r1') return 0x8B;
else if (curveName == 'sect283r1') return 0x8C;
else if (curveName == 'sect283k1') return 0x8D;
else if (curveName == 'sect409r1') return 0x8E;
else if (curveName == 'sect409k1') return 0x8F;
else if (curveName == 'sect571r1') return 0x90;
else if (curveName == 'sect571k1') return 0x91;
else return undefined;
};
var getCurveName = function(curveID){
//Prime curves
if (curveID == 0x01) return 'secp112r1';
else if (curveID == 0x02) return 'secp112r2';
else if (curveID == 0x03) return 'secp128r1';
else if (curveID == 0x04) return 'secp128r2';
else if (curveID == 0x05) return 'secp160r1';
else if (curveID == 0x06) return 'secp160r2';
else if (curveID == 0x07) return 'secp160k1';
else if (curveID == 0x08) return 'secp192r1';
else if (curveID == 0x09) return 'secp192k1';
else if (curveID == 0x0A) return 'secp224r1';
else if (curveID == 0x0B) return 'secp224k1';
else if (curveID == 0x0C) return 'secp256r1';
else if (curveID == 0x0D) return 'secp256k1';
else if (curveID == 0x0E) return 'secp384r1';
else if (curveID == 0x0F) return 'secp521r1';
else if (curveID == 0x80) return 'sect113r1'; //End of prime curves, first binary curve
else if (curveID == 0x81) return 'sect113r2';
else if (curveID == 0x82) return 'sect131r1';
else if (curveID == 0x83) return 'sect131r2';
else if (curveID == 0x84) return 'sect163r1';
else if (curveID == 0x85) return 'sect163r2';
else if (curveID == 0x86) return 'sect163k1';
else if (curveID == 0x87) return 'sect193r1';
else if (curveID == 0x88) return 'sect193r2';
else if (curveID == 0x89) return 'sect233r1';
else if (curveID == 0x8A) return 'sect233k1';
else if (curveID == 0x8B) return 'sect239r1';
else if (curveID == 0x8C) return 'sect283r1';
else if (curveID == 0x8D) return 'sect283k1';
else if (curveID == 0x8E) return 'sect409r1';
else if (curveID == 0x8F) return 'sect409k1';
else if (curveID == 0x90) return 'sect571r1';
else if (curveID == 0x91) return 'sect571k1';
else return undefined;
};
var getVerbId = function(verb){
if (typeof verb != 'string') throw new TypeError('verb must be a string');
verb = verb.toLowerCase();
if (verb == 'get') return 0x01;
else if (verb == 'post') return 0x02;
else if (verb == 'put') return 0x03;
else if (verb == 'delete') return 0x04;
else if (verb == 'head') return 0x05;
else if (verb == 'trace') return 0x06;
else if (verb == 'options') return 0x07;
else if (verb == 'connect') return 0x08;
else if (verb == 'patch') return 0x09;
else return undefined;
};
var getVerbFromId = function(verbID){
if (typeof verbID != 'number') throw new TypeError('verbID must be a number');
if (verbID == 0x01) return 'get';
else if (verbID == 0x02) return 'post';
else if (verbID == 0x03) return 'put';
else if (verbID == 0x04) return 'delete';
else if (verbID == 0x05) return 'head';
else if (verbID == 0x06) return 'trace';
else if (verbID == 0x07) return 'options';
else if (verbID == 0x08) return 'connect';
else if (verbID == 0x09) return 'patch';
else return undefined;
};
/*
* SERVER METHODS
*/
//Extracting all request details from the blob. Cf HPKA spec
//Note about buffers, indexes, and lack of checks :
var processReqBlob = function(pubKeyBlob){
var buf = new Buffer(pubKeyBlob, 'base64');
var byteIndex = 0;
//Reading the version number
var versionNumber = buf[byteIndex];
if (versionNumber != 0x01){
throw new RangeError('PROTOCOL_VERSION');
}
byteIndex++;
//Reading the timestamp
var timestampLeft, timestampRight;
timeStampLeft = buf.readUInt32BE(byteIndex);
byteIndex += 4;
timeStampRight = buf.readUInt32BE(byteIndex);
byteIndex += 4;
var timeStamp = joinUInt(timeStampLeft, timeStampRight);
//timeStamp *= 1000;
//Checking that the signature isn't older than 120 seconds
var actualTimestamp = Date.now();
//actualTimestamp -= actualTimestamp % 1000;
actualTimestamp = Math.floor(actualTimestamp / 1000);
//console.log('Actual timestamp : ' + actualTimestamp);
//console.log('Req timestamp : ' + timeStamp);
if (actualTimestamp >= timeStamp + 120) throw new RangeError("Request is too old");
//if ((actualTimestamp > timeStamp + 120) || (actualTimestamp < timeStamp - 30)) throw new TypeError("Request is too old or ahead of time");
//Reading the username length
var usernameLength = buf[byteIndex];
byteIndex++;
//Reading the username
var username = buf.toString('utf8', byteIndex, byteIndex + usernameLength);
var usernameBuf = buf.slice(byteIndex, byteIndex + usernameLength);
byteIndex += usernameLength;
//Reading the action type
var actionType = buf[byteIndex];
byteIndex++;
if (!(actionType >= 0x00 && actionType <= 0x05)){
throw new RangeError('invalid actionType');
}
//Reading the key type
var keyType = buf[byteIndex];
byteIndex++;
//Initializing the result object
var req = {};
req.username = username;
req.usernameBuffer = usernameBuf;
req.actionType = actionType;
req.timeStamp = timeStamp;
//var byteIndex = 4;
if (keyType == 1){ //ECDSA case
//Reading the x and y coordinates of the public point
var publicPtXLength = buf.readUInt16BE(byteIndex);
byteIndex += 2;
var xVal, yVal;
xVal = buf.toString('hex', byteIndex, byteIndex + publicPtXLength);
byteIndex += publicPtXLength;
var publicPtYLength = buf.readUInt16BE(byteIndex);
byteIndex += 2;
yVal = buf.toString('hex', byteIndex, byteIndex + publicPtYLength);
byteIndex += publicPtYLength;
//Reading the curveID
var curveId = buf.readUInt8(byteIndex);
byteIndex++;
//Building public key object
var curveName = getCurveName(curveId);
req.keyType = 'ecdsa';
req.curveName = curveName;
req.point = {};
req.point.x = xVal;
req.point.y = yVal;
} else if (keyType == 2){ //RSA case
req.keyType = 'rsa';
var modulusLength = buf.readUInt16BE(byteIndex);
byteIndex += 2;
var modulus = buf.toString('hex', byteIndex, byteIndex + modulusLength);
byteIndex += modulusLength;
var publicExpLength = buf.readUInt16BE(byteIndex);
byteIndex += 2;
var publicExponent = buf.toString('hex', byteIndex, byteIndex + publicExpLength);
byteIndex += publicExpLength;
req.publicExponent = publicExponent;
req.modulus = modulus;
} else if (keyType == 4){ //DSA case
req.keyType = 'dsa';
var primeFieldLength = buf.readUInt16BE(byteIndex);
byteIndex += 2;
var primeField = buf.toString('hex', byteIndex, byteIndex + primeFieldLength);
byteIndex += primeFieldLength;
var dividerLength = buf.readUInt16BE(byteIndex);
byteIndex += 2;
var divider = buf.toString('hex', byteIndex, byteIndex + dividerLength);
byteIndex += dividerLength;
var baseLength = buf.readUInt16BE(byteIndex);
byteIndex += 2;
var base = buf.toString('hex', byteIndex, byteIndex + baseLength);
byteIndex += baseLength;
var publicElementLength = buf.readUInt16BE(byteIndex);
byteIndex += 2;
var publicElement = buf.toString('hex', byteIndex, byteIndex + publicElementLength);
byteIndex += publicElementLength;
req.primeField = primeField;
req.divider = divider;
req.base = base;
req.publicElement = publicElement;
} else if (keyType == 8){
req.keyType = 'ed25519';
var publicKeyLength = buf.readUInt16BE(byteIndex);
byteIndex += 2;
var publicKey = buf.toString('hex', byteIndex, byteIndex + publicKeyLength);
byteIndex += publicKeyLength;
req.publicKey = publicKey;
} else throw new TypeError('Unknown key type');
//Session agreement and revocation cases
if (actionType == 0x04 || actionType == 0x05){ //Session-id agreement or revocation
var sessionIdLength, sessionId, sessionIdBuf;
//Reading the sessionId's length
sessionIdLength = buf[byteIndex];
byteIndex++;
//Reading the sessionId
sessionId = buf.toString('utf8', byteIndex, byteIndex + sessionIdLength);
sessionIdBuf = buf.slice(byteIndex, byteIndex + sessionIdLength);
byteIndex += sessionIdLength;
req.sessionId = sessionId;
req.sessionIdBuffer = sessionIdBuf;
if (actionType == 0x04){
/*
If it's a session agreement request,
an expiration date for the sessionId
may be optionally provided, in which
case this method should parse it and
add it to the returned HPKAReq object
*/
//Calc remaining bytes
var rem = remainingBytes();
if (rem != 8) return new _HPKAReq(req);
//Extract timestamp
var expLeft = buf.readUInt32BE(byteIndex);
byteIndex += 4;
var expRight = buf.readUInt32BE(byteIndex);
byteIndex += 4;
//Check that it's in the future
var expirationTimestamp = joinUInt(expLeft, expRight);
if (expirationTimestamp < Math.floor(Date.now()/1000)){
throw new RangeError('expiration is already past');
}
req.sessionExpiration = expirationTimestamp;
}
}
return new _HPKAReq(req);
function remainingBytes(){
return buf.length - byteIndex;
}
};
//If buffer, take it as is. If string, assume it's base64-encoded
function processSessionBlob(sessionBlob){
var sessionBuf;
if (Buffer.isBuffer(sessionBlob)) sessionBuf = sessionBlob;
else if (typeof sessionBlob == 'string') sessionBuf = new Buffer(sessionBlob, 'base64');
else throw new TypeError('invalid type for sessionBlob');
var byteIndex = 0;
//Reading the version number
var versionNumber = sessionBuf[byteIndex];
byteIndex++;
if (versionNumber != 0x01){
throw new RangeError('PROTOCOL_VERSION');
}
//Reading username length
var usernameLength = sessionBuf[byteIndex];
byteIndex++;
if (usernameLength > remainingBytes()){
throw new Error('malformed session request');
}
//Reading username
var username = sessionBuf.toString('utf8', byteIndex, byteIndex + usernameLength);
var usernameBuf = sessionBuf.slice(byteIndex, byteIndex + usernameLength);
byteIndex += usernameLength;
//Reading timestamp
var timestampLeft, timestampRight;
timestampLeft = sessionBuf.readUInt32BE(byteIndex);
byteIndex += 4;
timestampRight = sessionBuf.readUInt32BE(byteIndex);
byteIndex += 4;
var timestamp = joinUInt(timestampLeft, timestampRight);
var currentTimestamp = Math.floor(Date.now() / 1000);
if (currentTimestamp >= timestamp + 120) throw new RangeError('Request is too old');
//Reading sessionId length
var sessionIdLength = sessionBuf[byteIndex];
byteIndex++;
if (sessionIdLength > remainingBytes()){
throw new Error('malformed session request');
}
//Reading sessionId
var sessionId = sessionBuf.toString('utf8', byteIndex, byteIndex + sessionIdLength);
var sessionIdBuf = sessionBuf.slice(byteIndex, byteIndex + sessionIdLength);
byteIndex += sessionIdLength;
function remainingBytes(){
return sessionBuf.length - byteIndex;
}
return {username: username, usernameBuffer: usernameBuf, timestamp: timestamp, sessionId: sessionId, sessionIdBuffer: sessionIdBuf};
}
/*
* req : object containing all the public key information that will be used to verify the signature
* reqBlob : the req blob of which we will verify the signature, string encoded in base64
* signature : the signature that we will verify, corresponding to reqBlob, hex-encoded string
* callback : callback function taking a boolean indicating the validity of the signature
*/
var verifySignatureWithoutProcessing = function(req, reqBlob, httpReq, signature, callback){
if (!callback) console.log('Callback not received');
//Checking if the key type is ECDSA
//console.log('Parsed req : ' + JSON.stringify(req));
//console.log('Verfying signature');
var signedBlob = appendHostAndPathFromReq(reqBlob, httpReq);
//console.log('sent signedBlob: ' + signedBlob.toString('utf8'));
/*if (req.keyType == 'ed25519'){
console.log('reqBlob\n' + (new Buffer(reqBlob, 'base64')).toString('hex'));
console.log('signedBlob\n' + signedBlob.toString('hex'));
}*/
//console.log('reqBlob\n' + (new Buffer(reqBlob, 'base64')).toString('hex'));
//console.log('signedBlob\n' + signedBlob.toString('hex'));
//console.log('signature\n' + signature);
if (!signedBlob){
console.log('Error: can\'t get the blob of which we have to check the authenticity');
console.log('reqBlob:\n' + JSON.stringify(reqBlob));
console.log('url: ' + httpReq.url + '\nhostname: ' + httpReq.headers.hostname + '\nhost: ' + httpReq.headers.host);
process.exit(1);
}
var keyType = req.keyType;
if (!(keyType == 'ecdsa' || keyType == 'rsa' || keyType == 'dsa' || keyType == 'ed25519')){
throw new Error('Unknown key type');
}
//console.log('Blob to verify:\n' + signedBlob.toString('hex'));
if ((keyType == 'ecdsa' || keyType == 'rsa' || keyType == 'dsa') && !cryptopp){
req.err = 'ECDSA, RSA and DSA are not supported since cryptopp is not installed';
req.errcode = 12;
callback(true); //Even though the signature can't be verified. If callback(false) was called, the middleware will throw an "invalid signature" message to the client
return;
}
if (keyType == 'ed25519' && !sodium){
req.err = 'Ed25519 are not supported since sodium is not installed';
req.errcode = 12;
callback(true); //Even though the signature can't be verified. If callback(false) was called, the middleware will throw an "invalid signature" message to the client
return;
}
var keyOptions;
if (keyType == 'ecdsa'){
keyOptions = req.curveName;
} else if (keyType == 'rsa'){
keyOptions = req.modulus;
} else if (keyType == 'dsa'){
keyOptions = req.primeField;
}
/*if (!isValidSigLength(signature, keyType, keyOptions)){
callback(false);
return;
}*/
try {
if (req.keyType == 'ecdsa'){
if (req.curveName.indexOf('secp') > -1){ //Checking is the curve is a prime field one
var isValid = cryptopp.ecdsa.prime.verify(signedBlob.toString('utf8'), (new Buffer(signature, 'base64')).toString('hex'), req.point, req.curveName, 'sha1');
//console.log('isValid: ' + isValid);
callback(isValid);
} else if (req.curveName.indexOf('sect') > -1){ //Binary curves aren't supported in ECDSA on binary fields in the node-cryptopp binding lib v0.1.2
throw new TypeError("Unsupported curve type. See cryptopp README page");
} else throw new TypeError("Unknown curve type");
} else if (req.keyType == 'rsa'){
//console.log('RSA sig length: ' + signedBlob.length);
signedBlob = signedBlob.toString('utf8');
var isValid = cryptopp.rsa.verify(signedBlob, (new Buffer(signature, 'base64')).toString('hex'), req.modulus, req.publicExponent);
//console.log('verifySignatureWithoutProcessing isValid: ' + isValid);
callback(isValid);
} else if (req.keyType == 'dsa'){
var isValid = cryptopp.dsa.verify(signedBlob.toString('utf8'), (new Buffer(signature, 'base64')).toString('hex'), req.primeField, req.divider, req.base, req.publicElement);
//console.log('isValid: ' + isValid);
callback(isValid)
} else if (req.keyType == 'ed25519'){
if (Buffer.byteLength(signature, 'base64') != 64){
callback(false);
return;
}
var isValid = sodium.api.crypto_sign_verify_detached(new Buffer(signature, 'base64'), signedBlob, new Buffer(req.publicKey, 'hex'));
//console.log('verifySignatureWithoutProcessing isValid: ' + isValid);
callback(isValid);
/*if (typeof signedMessage === 'undefined') {callback(false); return;}
//Note: the signed message is a Base64 encoded string, hence the content of signedMessage buffer is the "already encoded" base64 string.
if (signedMessage.toString('ascii') == reqBlob) callback(true);
else callback(false);*/
}
} catch (e){
callback(false);
}
};
//External / out-of-context signature validation. Note: reqUrl must be a full URL (with protocol and everything)
//This function throws an exception if the reqBlob is malformed, or returns an error as first parameter of the callback
var verifySignature = function(reqBlob, signature, reqUrl, method, callback){
if (typeof reqBlob != 'string') throw new TypeError('reqBlob must be a base64 string');
if (!(Buffer.isBuffer(signature) || typeof signature == 'string')) throw new TypeError('signature must either be a buffer or a string');
if (typeof reqUrl != 'string') throw new TypeError('reqUrl must be a string');
if (typeof method != 'string') throw new TypeError('method must be a string');
var req;
try {
req = processReqBlob(reqBlob);
} catch (e){
if (!callback) throw e;
callback(e);
return;
}
var reqUrlStr = reqUrl.toString('utf8'); //Start after the first byte (being the verbId);
var parsedUrl = url.parse(reqUrlStr);
var httpReqMimic = {
headers: {
host: parsedUrl.hostname || parsedUrl.host
},
url: parsedUrl.path || parsedUrl.pathname,
method: method
};
verifySignatureWithoutProcessing(req, reqBlob, httpReqMimic, signature, function(isValid){
callback(undefined, isValid, req.username, req);
});
};
exports.verifySignature = verifySignature;
//Expressjs middlware builder
/* Config object signature
{
loginCheck: function(HPKAReq, res, callback(isValid)),
registration: function(HPKAReq, res),
deletion: function(HPKAReq, res),
keyRotation: function(HPKAReq, RotationReq, res),
strict: boolean,
sessionCheck: function(SessionReq, req, res, callback(isValid))
sessionAgreement: function(HPKAReq, req, callback(accepted, serverSetExpiration)),
sessionRevocation: function(HPKAReq, req, callback(revoked))
}
*/
exports.expressMiddleware = function(loginCheck, registration, deletion, keyRotation, strict, sessionCheck, sessionAgreement, sessionRevocation){
if (!(typeof loginCheck == 'function' && typeof registration == 'function' && typeof deletion == 'function' && typeof keyRotation == 'function')) throw new TypeError('loginCheck and registration parameters must be event handlers (ie, functions)');
if (!(typeof strict == 'undefined' || typeof strict == 'boolean')) throw new TypeError("When 'strict' is defined, it must be a boolean");
if (sessionCheck){
if (typeof sessionCheck != 'function') throw new TypeError('when sessionCheck is defined, it must be a function');
if (typeof sessionAgreement != 'function') throw new TypeError('when sessionCheck is defined, sessionAgreement must also be defined and must be a function');
if (typeof sessionRevocation != 'function') throw new TypeError('when sessionCheck is defined, sessionRevocation must also be defined and must be a function');
}
var middlewareFunction = function(req, res, next){
if (req.get('HPKA-Req') && req.get("HPKA-Signature")){
//console.log('HPKA Headers found');
try {
var HPKAReqBlob = req.get("HPKA-Req"), HPKASignature = req.get("HPKA-Signature");
var HPKAReq;
try {
HPKAReq = processReqBlob(HPKAReqBlob);
} catch (e){
console.log('HPKA-Req parsing issue; e : ' + e);
if (strict){
if (e.message == 'PROTOCOL_VERSION'){
res.status(445).set('HPKA-Error', '0');
res.send('Unsupported protocol version');
} else {
res.status(445).set('HPKA-Error', '1');
res.send('Malformed HPKA request');
}
} else {
next();
}
return;
}
if (HPKAReq.keyType == 'ecdsa' || HPKAReq.keyType == 'rsa' || HPKAReq.keyType == 'dsa'){
showCriticalError('Crypto++ support has been disabled in this version of node-hpka, until node-cryptopp is fixed');
res.status(445).set('HPKA-Error', '12');
res.send('Forbidden key type');
return;
}
try {
verifySignatureWithoutProcessing(HPKAReq, HPKAReqBlob, req, HPKASignature, function(isValid){
if (isValid){
//console.log('actionType : ' + HPKAReq.actionType);
//console.log('Username : ' + HPKAReq.username);
if (HPKAReq.actionType == 0){
//Authentified HTTP request
//Check that the user is registered and the public key valid
//console.log('Calling login handler');
loginCheck(HPKAReq, req, res, function(isKeyValid){
//console.log('Is key valid : ' + isKeyValid);
if (isKeyValid){
req.username = HPKAReq.username;
req.hpkareq = HPKAReq;
next();
} else {
if (strict){
res.status(445).set('HPKA-Error', '3');
res.send('Invalid key');
} else {
next();
}
}
});
return;
} else if (HPKAReq.actionType == 0x01){
//Registration
//console.log('Calling registration handler');
req.hpkareq = HPKAReq;
req.username = HPKAReq.username;
registration(HPKAReq, req, res, next);
return;
} else if (HPKAReq.actionType == 0x02){
//User deletion
deletion(HPKAReq, req, res);
} else if (HPKAReq.actionType == 0x03){
//Key rotation
var newKeyBlob = req.get('HPKA-NewKey');
var newKeySignature = req.get('HPKA-NewKeySignature');
var newKeySignature2 = req.get('HPKA-NewKeySignature2');
var newKeyReq;
try {
newKeyReq = processReqBlob(newKeyBlob);
} catch (e){
res.status(445).set('HPKA-Error', '1');
res.send('HPKA-NewKey cannot be parsed');
}
if (newKeyReq.actionType != 3){
res.status(445).set('HPKA-Error', '1');
res.send('actionType must be 0x03 in both HPKA-Reqs when rotating keys');
}
if (HPKAReq.username != newKeyReq.username){
res.status(445).set('HPKA-Error', '1');
res.send('usernames must be the same in both requests');
}
verifySignatureWithoutProcessing(HPKAReq, newKeyBlob, req, newKeySignature, function(newKeySignIsValid){
if (newKeySignIsValid){
verifySignatureWithoutProcessing(newKeyReq, newKeyBlob, req, newKeySignature2, function(newKeySign2IsValid){
if (newKeySign2IsValid){
req.hpkareq = HPKAReq;
req.username = HPKAReq.username;
keyRotation(HPKAReq, newKeyReq, req, res, next);
} else {
res.status(445).set('HPKA-Error', 2);
res.send('Self-signature on new key is invalid');
}
});
} else {
res.status(445).set('HPKA-Error', 2);
res.send('Signature of new key with actual key is invalid');
}
});
} else if (HPKAReq.actionType == 0x04){
if (!sessionAgreement){
res.status(445).set('HPKA-Error', 7);
res.send('Session agreement is not supported');
return;
}
var sessionId = HPKAReq.sessionId;
assert(typeof sessionId == 'string' && sessionId.length > 0, 'SessionId should be defined and non-empty');
assert(typeof HPKAReq.sessionExpiration || (typeof HPKAReq.sessionExpiration == 'number' && HPKAReq.sessionExpiration > 0), 'sessionExpiration should either be a undefined or a number');
var sessionExpiration = HPKAReq.sessionExpiration || 0;
sessionAgreement(HPKAReq, req, res, function(accepted, serverSetExpiration){
if (accepted){
res.set('HPKA-Session-Expiration', serverSetExpiration || sessionExpiration);
res.send('Session created');
} else {
res.status(445).set('HPKA-Error', 15);
res.send('Session not accepted');
}
});
} else if (HPKAReq.actionType == 0x05){
if (!sessionRevocation){
res.set('HPKA-Error', 7);
res.send('Session revocation is not supported');
return;
}
var sessionId = HPKAReq.sessionId;
assert(typeof sessionId == 'string' && sessionId.length > 0, 'SessionId should be defined and non-empty');
sessionRevocation(HPKAReq, req, res, function(completed){
if (completed){
res.send('SessionId revoked');
} else {
res.set('HPKA-Error', 16);
res.send('SessionId cannot be revoked');
}
});
} else {
res.status(445);
if (Number(HPKAReq.actionType) < 0 || Number(HPKAReq.actionType) > 5){
//Invalid action types
res.set('HPKA-Error', '8');
res.send('Unknown action type. What the hell are you doing?');
//console.log("Unknown action type : " + HPKAReq.actionType );
} else {
//Valid action type, but not implemented here yet
res.set('HPKA-Error', '7');
res.send('Unsupported action type. What the hell are you doing?');
}
}
} else {
//console.log('Invalid signature : ' + JSON.stringify(HPKAReq));
if (strict){
res.status(445).set('HPKA-Error', '2');
res.send('Invalid signature');
} else {
next();
}
}
});
} catch (e){
console.log('error : ' + e);
if (strict){
res.status(445).set('HPKA-Error', '2');
res.send('Invalid signature');
} else {
next();
}
return;
}
} catch (e){
console.log('error : ' + e);
next();
}
} else if (req.get('HPKA-Session')){
var sessionBlob = req.get('HPKA-Session');
var sessionReq;
try {
sessionReq = processSessionBlob(sessionBlob);
//console.log('Parsed session req: ' + JSON.stringify(sessionReq));
} catch (e){
if (strict){
if (e.message == 'PROTOCOL_VERSION'){
res.status(445).set('HPKA-Error', '0');
res.send('Unsupported protocol version');
} else {
res.status(445).set('HPKA-Error', '1');
res.send('Malformed request');
}
} else {
next();
}
return;
}
sessionCheck(sessionReq, req, res, function(isValid){
if (isValid){
req.sessionReq = sessionReq;
req.username = sessionReq.username;
req.sessionId = sessionReq.sessionId;
next();
} else {
if (strict){
res.status(445).set('HPKA-Error', 2);
res.send('Invalid token');
} else {
next();
}
}
});
} else {
//console.log('HPKA headers not found');
res.set('HPKA-Available', '1');
next();
}
};
return middlewareFunction;
};
//Standard HTTP middlware builder
/* Config object signature
{
loginCheck: function(HPKAReq, req, res, callback(isValid)),
registration: function(HPKAReq, req, res),
deletion: function(HPKAReq, req, res),
keyRotation: function(HPKAReq, RotationReq, req, res),
strict: boolean,
sessionCheck: function(sessionReq, req, res, callback(isValid)),
sessionAgreement: function(HPKAReq, req, callback(accepted, serverSetExpiration)),
sessionRevocation: function(HPKAReq, req, callback(revoked))
}
*/
exports.httpMiddleware = function(requestHandler, loginCheck, registration, deletion, keyRotation, strict, sessionCheck, sessionAgreement, sessionRevocation){
if (!(typeof requestHandler == 'function' && typeof loginCheck == 'function' && typeof registration == 'function' && typeof deletion == 'function' && typeof keyRotation == 'function')) throw new TypeError('requestHandler, loginCheck, registration, deletion and keyRotation parameters must all be functions');
if (!(typeof strict == 'undefined' || typeof strict == 'boolean')) throw new TypeError("When 'strict' is defined, it must be a boolean");
if (sessionCheck){
if (typeof sessionCheck != 'function') throw new TypeError('when sessionCheck is defined, it must be a function');
if (typeof sessionAgreement != 'function') throw new TypeError('when sessionCheck is defined, sessionAgreement must also be defined and must be a function');
if (typeof sessionRevocation != 'function') throw new TypeError('when sessionCheck is defined, sessionRevocation must also be defined and must be a function');
}
function writeErrorRes(res, message, errorCode){
res.writeHead(445, {'Content-Type': 'text/plain', 'Content-Length': message.length.toString(), 'HPKA-Error': errorCode.toString()});
res.write(message);
res.end();
}
var middleware = function(req, res){
//console.log('Headers found by the server : ' + JSON.stringify(req.headers));
if (req.headers['hpka-req'] && req.headers['hpka-signature']){
//console.log('HPKA headers found');
try {
var HPKAReqBlob = req.headers['hpka-req'], HPKASignature = req.headers['hpka-signature'];
var HPKAReq;
//Parsing the request
try {
HPKAReq = processReqBlob(HPKAReqBlob);
} catch (e){
if (strict){
if (e.message == 'PROTOCOL_VERSION'){
writeErrorRes(res, 'Unsupported protocol version', 0);
} else {
console.log('parsing error, e : ' + e);
writeErrorRes(res, 'Malformed HPKA request', 1);
}
} else {
requestHandler(req, res);
}
return;
}
if (HPKAReq.keyType == 'ecdsa' || HPKAReq.keyType == 'rsa' || HPKAReq.keyType == 'dsa'){
showCriticalError('Crypto++ support has been disabled in this version of node-hpka, until node-cryptopp is fixed');
writeErrorRes(res, 'Forbidden key type', 12);
return;
}
//Checking the signature then calling the handlers according to the actionType
try {
verifySignatureWithoutProcessing(HPKAReq, HPKAReqBlob, req, HPKASignature, function(isValid){
if (isValid){
function next(){
requestHandler(req, res);
}
//console.log('Signature is valid');
//Checking the action type and calling the right handlers
if (HPKAReq.actionType == 0x00){ //Authenticated HTTP request
loginCheck(HPKAReq, req, res, function(isValid){
if (isValid){
req.username = HPKAReq.username;
req.hpkareq = HPKAReq;
next();
} else {
if (strict){
writeErrorRes(res, 'Invalid key', 3);
} else {
next();
}
}
});
} else if (HPKAReq.actionType == 0x01){ //Registration request
registration(HPKAReq, req, res, next);
return;
} else if (HPKAReq.actionType == 0x02){ //User deletion request
deletion(HPKAReq, req, res);
return;
} else if (HPKAReq.actionType == 0x03){ //Key rotation request
if (!req.headers['hpka-newkey']) writeErrorRes(res, 'Missing HPKA-NewKey header', 1);
if (!req.headers['hpka-newkeysignature']) writeErrorRes(res, 'Missing HPKA-NewKeySignature header', 1);
if (!req.headers['hpka-newkeysignature2']) writeErrorRes(res, 'Missing HPKA-NewKeySignature2 header', 1);
var newKeyBlob = req.headers['hpka-newkey'];
var newKeyReq;
try {
newKeyReq = processReqBlob(newKeyBlob);
} catch (e){
console.log('newkey parsing error, e : ' + e);
writeErrorRes(res, 'HPKA-NewKey cannot be parsed', 1);
return;
}
if (newKeyReq.actionType != 0x03) writeErrorRes(res, 'actionType must be 0x03 in both HPKA-Reqs when rotating keys', 1);
if (HPKAReq.username != newKeyReq.username) writeErrorRes(res, 'usernames must be the same in both requests', 1);
var newKeySignature = req.headers['hpka-newkeysignature'];
var newKeySignature2 = req.headers['hpka-newkeysignature2'];
//Verifying new
verifySignatureWithoutProcessing(HPKAReq, newKeyBlob, req, newKeySignature, function(newKeySignIsValid){
if (newKeySignIsValid){
verifySignatureWithoutProcessing(newKeyReq, newKeyBlob, req, newKeySignature2, function(newKeySign2IsValid){
if (newKeySign2IsValid){
keyRotation(HPKAReq, newKeyReq, req, res, next);
return;
} else {
writeErrorRes(res, 'Self-signature on new key is invalid', 2);
}
});
} else {
writeErrorRes(res, 'Signature of new key with actual key is invalid', 2);
}
});
} else if (HPKAReq.actionType == 0x04){
if (!sessionAgreement){
writeErrorRes(res, 'Session agreement is not supported', 7);
return;
}
var sessionId = HPKAReq.sessionId;
assert(typeof sessionId == 'string' && sessionId.length > 0, 'SessionId should be defined and non-empty');
assert(typeof HPKAReq.sessionExpiration || (typeof HPKAReq.sessionExpiration == 'number' && HPKAReq.sessionExpiration > 0), 'sessionExpiration should either be a undefined or a number');
var sessionExpiration = HPKAReq.sessionExpiration || 0;
sessionAgreement(HPKAReq, req, res, function(accepted, serverSetExpiration){
if (accepted){
var message = 'Session created';
res.writeHead(200, {
'Content-Length': message.length,
'HPKA-Session-Expiration': serverSetExpiration || sessionExpiration
});
res.write(message);
res.end();
} else {
writeErrorRes(res, 'Session not accepted', 15);
}
});
} else if (HPKAReq.actionType == 0x05){
if (!sessionRevocation){
writeErrorRes(res, 'Session revocation is not supported', 7);
return;
}
var sessionId = HPKAReq.sessionId;
assert(typeof sessionId == 'string' && sessionId.length > 0, 'SessionId should be defined and non-empty');
sessionRevocation(HPKAReq, req, res, function(completed){
if (completed){
var message = 'SessionId revoked';
res.writeHead(200, {'Content-Length': message.length});
res.write(message);
res.end();
} else {
writeErrorRes(res, 'SessionId cannot be revoked', 16);
}
});
} else {
if (Number(HPKAReq.actionType) < 0 || Number(HPKAReq.actionType) > 5){
//Unknown actionType
writeErrorRes(res, 'Invald actionType', 8);
} else {
//Unsupported actionType as of now
writeErrorRes(res, 'Unsupported actionType', 7);
}
}
} else {
//console.log('Signature is not valid');
if (strict){
writeErrorRes(res, 'Invalid signature', 2);
} else {
requestHandler(req, res);
}
}
});
} catch (e){
//throw e;
console.log('error : ' + e);
if (strict){
writeErrorRes(res, 'Invalid signature', 2);
} else {
requestHandler(req, res);
}
return;
}
} catch (e){
//throw e;
console.log('error : ' + e);
requestHandler(req, res);
}
} else if (req.headers['hpka-session']){
var sessionBlob = req.headers['hpka-session'];
var sessionReq;
try {
sessionReq = processSessionBlob(sessionBlob);
//console.log('Parsed session req: ' + JSON.stringify(sessionReq));
} catch (e){
if (strict){
if (e.message == 'PROTOCOL_VERSION'){
writeErrorRes(res, 'Unsupported protocol version', 0);
} else {
writeErrorRes(res, 'Malformed request', 1);
}
} else {
next();
}
return;
}
sessionCheck(sessionReq, req, res, function(isValid){
if (isValid){
req.sessionReq = sessionReq;
req.username = sessionReq.username;
req.sessionId = sessionReq.sessionId;
next();
} else {
if (strict){
writeErrorRes(res, 'Invalid token', 2);
} else {
next();
}
}
});
function next(){
requestHandler(req, res);
}
} else {
//console.log('HPKA headers not found');
res.setHeader('HPKA-Available', '1');
requestHandler(req, res);
}
};
return middleware;
}