-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathmain.js
4413 lines (3516 loc) · 91.9 KB
/
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
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
/* vim: set ts=8 sw=4 tw=0 noet : */
/*
* Copyright (c) 2020, Indian Institute of Science, Bengaluru
*
* Authors:
* --------
* Arun Babu {barun <at> iisc <dot> ac <dot> in}
* Bryan Robert {bryanrobert <at> iisc <dot> ac <dot> in}
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
"use strict";
const fs = require("fs");
const os = require("os");
const dns = require("dns");
const cors = require("cors");
const ocsp = require("ocsp");
const Pool = require("pg").Pool;
const https = require("https");
const assert = require("assert").strict;
const chroot = require("chroot");
const crypto = require("crypto");
const logger = require("node-color-log");
const lodash = require("lodash");
const cluster = require("cluster");
const express = require("express");
const timeout = require("connect-timeout");
const aperture = require("./node-aperture");
const safe_regex = require("safe-regex");
const geoip_lite = require("geoip-lite");
const bodyParser = require("body-parser");
const compression = require("compression");
const http_request = require("request");
const pgNativeClient = require("pg-native");
const pg = new pgNativeClient();
const TOKEN_LEN = 16;
const TOKEN_LEN_HEX = 2 * TOKEN_LEN;
const EUID = process.geteuid();
const is_openbsd = os.type() === "OpenBSD";
const pledge = is_openbsd ? require("node-pledge") : null;
const unveil = is_openbsd ? require("openbsd-unveil"): null;
const NUM_CPUS = os.cpus().length;
const SERVER_NAME = fs.readFileSync ("server.name","ascii").trim();
const DOCUMENTATION_LINK = fs.readFileSync ("documentation.link","ascii").trim();
const MAX_TOKEN_TIME = 31536000; // in seconds (1 year)
const MIN_TOKEN_HASH_LEN = 64;
const MAX_TOKEN_HASH_LEN = 64;
const MAX_SAFE_STRING_LEN = 512;
const MIN_CERT_CLASS_REQUIRED = Object.freeze ({
/* resource server API */
"/auth/v1/token/introspect" : 1,
"/auth/v1/certificate-info" : 1,
/* data consumer's APIs */
"/auth/v1/token" : 2,
/* for credit topup */
"/marketplace/topup-success" : 2,
/* static files for marketplace */
"/marketplace/topup.html" : 2,
"/marketplace/marketplace.js" : 2,
"/marketplace/marketplace.css" : 2,
/* marketplace APIs */
"/marketplace/v1/credit/info" : 2,
"/marketplace/v1/credit/topup" : 2,
"/marketplace/v1/confirm-payment" : 2,
"/marketplace/v1/audit/credits" : 2,
"/marketplace/v1/credit/transfer" : 3,
/* data provider's APIs */
"/auth/v1/audit/tokens" : 3,
"/auth/v1/token/revoke" : 3,
"/auth/v1/token/revoke-all" : 3,
"/auth/v1/acl" : 3,
"/auth/v1/acl/set" : 3,
"/auth/v1/acl/revert" : 3,
"/auth/v1/acl/append" : 3,
"/auth/v1/group/add" : 3,
"/auth/v1/group/delete" : 3,
"/auth/v1/group/list" : 3,
});
const WHITELISTED_DOMAINS = fs.readFileSync("whitelist.domains","ascii").trim().split("\n");
const WHITELISTED_ENDSWITH = fs.readFileSync("whitelist.endswith","ascii").trim().split("\n");
const LAUNCH_ADMIN_PANEL = fs.readFileSync("admin.panel","ascii").trim() === "yes";
/* --- API statistics --- */
const statistics = {
"start_time" : 0,
"api" : {
"count" : {
"invalid-api" : 0
}
}
};
/* --- environment variables--- */
process.env.TZ = "Asia/Kolkata";
/* --- dns --- */
dns.setServers ([
"1.1.1.1",
"4.4.4.4",
"8.8.8.8",
"[2001:4860:4860::8888]",
"[2001:4860:4860::8844]",
]);
/* --- telegram --- */
const TELEGRAM = "https://api.telegram.org";
const telegram_apikey = fs.readFileSync ("telegram.apikey","ascii").trim();
const telegram_chat_id = fs.readFileSync ("telegram.chatid","ascii").trim();
const telegram_url = TELEGRAM + "/bot" + telegram_apikey +
"/sendMessage?chat_id=" + telegram_chat_id +
"&text=";
/* --- postgres --- */
const DB_SERVER = "127.0.0.1";
const password = {
"DB" : fs.readFileSync("passwords/auth.db.password","ascii").trim(),
};
/* --- razorpay --- */
const rzpay_key_id = fs.readFileSync("rzpay.key.id", "ascii").trim();
const rzpay_key_secret = fs.readFileSync("rzpay.key.secret", "ascii").trim();
const rzpay_url = "https://" +
rzpay_key_id +
":" +
rzpay_key_secret +
"@api.razorpay.com/v1/invoices/";
// async postgres connection
const pool = new Pool ({
host : DB_SERVER,
port : 5432,
user : "auth",
database : "postgres",
password : password.DB,
});
pool.connect();
// sync postgres connection
pg.connectSync (
"postgresql://auth:"+ password.DB + "@" + DB_SERVER + ":5432/postgres",
(err) =>
{
if (err) {
throw err;
}
}
);
/* --- preload negotiator's encoding module for gzip compression --- */
const Negotiator = require("negotiator");
const negotiator = new Negotiator();
try { negotiator.encodings(); }
catch(x) { /* ignore */ }
/* --- express --- */
const app = express();
app.disable("x-powered-by");
app.use(timeout("5s"));
app.use(
cors ({
credentials : true,
methods : ["POST"],
origin : (origin, callback) =>
{
callback (
null,
origin ? true : false
);
}
})
);
app.use(compression());
app.use(bodyParser.raw({type:"*/*"}));
app.use(basic_security_check);
app.use(dns_check);
app.use(ocsp_check);
/* --- aperture --- */
const apertureOpts = {
types : aperture.types,
typeTable : {
ip : "ip",
time : "time",
tokens_per_day : "number", // tokens issued today
api : "string", // the API to be called
method : "string", // the method for API
"cert.class" : "number", // the certificate class
"cert.cn" : "string",
"cert.o" : "string",
"cert.ou" : "string",
"cert.c" : "string",
"cert.st" : "string",
"cert.gn" : "string",
"cert.sn" : "string",
"cert.title" : "string",
"cert.issuer.cn" : "string",
"cert.issuer.email" : "string",
"cert.issuer.o" : "string",
"cert.issuer.ou" : "string",
"cert.issuer.c" : "string",
"cert.issuer.st" : "string",
groups : "string", // CSV actually
country : "string",
region : "string",
timezone : "string",
city : "string",
latitude : "number",
longitude : "number",
}
};
const parser = aperture.createParser (apertureOpts);
const evaluator = aperture.createEvaluator (apertureOpts);
/* --- https --- */
const system_trusted_certs = is_openbsd ?
"/etc/ssl/cert.pem" :
"/etc/ssl/certs/ca-certificates.crt";
const trusted_CAs = [
fs.readFileSync("ca.iudx.org.in.crt"),
fs.readFileSync(system_trusted_certs),
fs.readFileSync("CCAIndia2015.cer"),
fs.readFileSync("CCAIndia2014.cer")
];
const https_options = Object.freeze ({
key : fs.readFileSync("https-key.pem"),
cert : fs.readFileSync("https-certificate.pem"),
ca : trusted_CAs,
requestCert : true,
rejectUnauthorized : true,
});
/* --- static pages --- */
const STATIC_PAGES = Object.freeze ({
/* GET end points */
"/marketplace/topup.html":
fs.readFileSync (
"static/topup.html", "ascii"
),
"/marketplace/marketplace.js":
fs.readFileSync (
"static/marketplace.js", "ascii"
),
"/marketplace/marketplace.css":
fs.readFileSync (
"static/marketplace.css", "ascii"
),
/* templates */
"topup-success-1.html" : fs.readFileSync (
"static/topup-success-1.html", "ascii"
),
"topup-success-2.html" : fs.readFileSync (
"static/topup-success-2.html", "ascii"
),
"topup-failure-1.html" : fs.readFileSync (
"static/topup-failure-1.html", "ascii"
),
"topup-failure-2.html" : fs.readFileSync (
"static/topup-failure-2.html", "ascii"
),
});
const MIME_TYPE = Object.freeze({
"js" : "text/javascript",
"css" : "text/css",
"html" : "text/html"
});
const topup_success_1 = STATIC_PAGES["topup-success-1.html"];
const topup_success_2 = STATIC_PAGES["topup-success-2.html"];
const topup_failure_1 = STATIC_PAGES["topup-failure-1.html"];
const topup_failure_2 = STATIC_PAGES["topup-failure-2.html"];
/* --- functions --- */
function is_valid_token (token, user = null)
{
if (! is_string_safe(token))
return false;
const split = token.split("/");
if (split.length !== 3)
return false;
const issued_by = split[0];
const issued_to = split[1];
const random_hex = split[2];
if (issued_by !== SERVER_NAME)
return false;
if (random_hex.length !== TOKEN_LEN_HEX)
return false;
if (user && user !== issued_to)
return false; // token was not issued to this user
if (! is_valid_email(issued_to))
return false;
return true;
}
function is_valid_tokenhash (token_hash)
{
if (! is_string_safe(token_hash))
return false;
if (token_hash.length < MIN_TOKEN_HASH_LEN)
return false;
if (token_hash.length > MAX_TOKEN_HASH_LEN)
return false;
return true;
}
function is_valid_servertoken (server_token, hostname)
{
if (! is_string_safe(server_token))
return false;
const split = server_token.split("/");
if (split.length !== 2)
return false;
const issued_to = split[0];
const random_hex = split[1];
if (issued_to !== hostname)
return false;
if (random_hex.length !== TOKEN_LEN_HEX)
return false;
return true;
}
function sha1 (string)
{
return crypto
.createHash("sha1")
.update(string)
.digest("hex");
}
function sha256 (string)
{
return crypto
.createHash("sha256")
.update(string)
.digest("hex");
}
function base64 (string)
{
return Buffer
.from(string)
.toString("base64");
}
function send_telegram_to_provider (consumer_id, provider_id, telegram_id, token_hash, request)
{
pool.query ("SELECT chat_id FROM telegram WHERE id = $1::text LIMIT 1", [telegram_id], (error,results) =>
{
if (error)
send_telegram ("Failed to get chat_id for : " + telegram_id + " : provider " + provider_id);
else
{
const url = TELEGRAM + "/bot" + telegram_apikey + "/sendMessage";
const split = request.id.split("/");
const resource = split.slice(2).join("/");
const telegram_message = {
url : url,
form : {
chat_id : results.rows[0].chat_id,
text : '[ IUDX-AUTH ] #' + token_hash + '#\n\n"' +
consumer_id +
'" wants to access "' +
resource + '"\n\n' +
"Request details:\n\n" +
JSON.stringify (request,null,"\t"),
reply_markup : JSON.stringify ({
inline_keyboard : [[
{
text : "\u2714\ufe0f Allow",
callback_data : "allow"
},
{
text : "\u2716\ufe0f Deny",
callback_data : "deny"
}
]]
})
}
};
http_request.post (telegram_message, (error_1, response, body) => {
if (error_1)
{
log ("yellow",
"Telegram failed ! response = " +
String(response) +
" body = " +
String(body)
);
}
});
}
});
}
function send_telegram (message)
{
http_request ( telegram_url + "[ AUTH ] : " + message, (error, response, body) =>
{
if (error)
{
log ("yellow",
"Telegram failed ! response = " +
String(response) +
" body = " +
String(body)
);
}
});
}
function log(color, msg)
{
const message = new Date() + " | " + msg;
if (color === "red") {
send_telegram(message);
}
logger.color(color).log(message);
}
function SERVE_HTML (req,res)
{
const path = req.url.split("?")[0];
const page = STATIC_PAGES[path];
if (! page)
return false;
const split = path.split(".");
const extension = split[split.length - 1].toLowerCase();
const mime = MIME_TYPE[extension] || "text/html";
res.setHeader("Content-Type", mime);
res.status(200).end(page);
return true;
}
function END_SUCCESS (res, response = null)
{
// if no response is given, just send success
if (! response)
response = {"success":true};
res.setHeader("Content-Security-Policy", "default-src 'none'");
res.setHeader("Content-Type", "application/json");
res.status(200).end(JSON.stringify(response) + "\n");
}
function END_ERROR (res, http_status, error, exception = null)
{
if (exception)
log("red", String(exception).replace(/\n/g," "));
res.setHeader("Content-Security-Policy", "default-src 'none'");
res.setHeader("Content-Type", "application/json");
res.setHeader("Connection", "close");
const response = {};
if (typeof error === "string")
response.error = {"message" : error};
else
{
// error is already a JSON
if (error["invalid-input"])
{
response["//"] ="Unsafe characters (if any) in" +
" 'invalid-input' field have been" +
" replaced with '*'";
}
response.error = error;
}
res.status(http_status).end(JSON.stringify(response) + "\n");
res.socket.end();
res.socket.destroy();
delete res.socket;
delete res.locals;
}
function show_statistics (req,res)
{
const now = Math.floor (Date.now() / 1000);
const diff = now - statistics.start_time;
const time = (new Date()).toJSON();
const response = {
time : time,
statistics : []
};
for (const api in statistics.api.count)
{
const rate = statistics.api.count[api]/diff;
response.statistics.push ({
api : api,
count : statistics.api.count[api],
rate : rate
});
}
res.status(200).end(JSON.stringify(response,null,"\t") + "\n");
}
function is_valid_email (email)
{
if (! email || typeof email !== "string")
return false;
if (email.length < 5 || email.length > 64)
return false;
// reject email ids starting with invalid chars
const invalid_start_chars = ".-_@";
if (invalid_start_chars.indexOf(email[0]) !== -1)
return false;
/*
Since we use SHA1 (160 bits) for storing email hashes:
the allowed chars in the email login is -._a-z0-9
which is : 1 + 1 + 1 + 26 + 10 = ~40 possible chars
the worst case brute force attack with 31 chars is
40**31 > 2**160
but for 30 chars it is
40**30 < 2**160
and since we have a good margin for 30 chars
(2**160) - (40**30) > 2**157
hence, as a precaution, limit the login length to 30.
SHA1 has other attacks though, maybe we should switch to better
hash algorithm in future.
*/
const split = email.split("@");
if (split.length !== 2)
return false;
const user = split[0]; // the login
if (user.length === 0 || user.length > 30)
return false;
let num_dots = 0;
for (const chr of email)
{
if (
(chr >= "a" && chr <= "z") ||
(chr >= "A" && chr <= "Z") ||
(chr >= "0" && chr <= "9")
)
{
// ok;
}
else
{
switch (chr)
{
case "-":
case "_":
case "@":
break;
case ".":
++num_dots;
break;
default:
return false;
}
}
}
if (num_dots < 1)
return false;
return true;
}
function is_certificate_ok (req, cert, validate_email)
{
if (! cert || ! cert.subject)
return "No subject found in the certificate";
if (! cert.subject.CN)
return "No CN found in the certificate";
if (validate_email)
{
if (! is_valid_email(cert.subject.emailAddress))
return "Invalid 'emailAddress' field in the certificate";
if (! cert.issuer || ! cert.issuer.emailAddress)
return "Certificate issuer has no 'emailAddress' field";
const issuer_email = cert.issuer.emailAddress.toLowerCase();
if (! is_valid_email(issuer_email))
return "Certificate issuer's emailAddress is invalid";
if (issuer_email.startsWith("iudx.sub.ca@"))
{
const issued_to_domain = cert.subject.emailAddress
.toLowerCase()
.split("@")[1];
const issuer_domain = issuer_email
.toLowerCase()
.split("@")[1];
if (issuer_domain !== issued_to_domain)
{
// TODO
// As this could be a fraud commited by a sub-CA
// maybe revoke the sub-CA certificate
log ("red",
"Invalid certificate: issuer = "+
issuer_domain +
" and issued to = " +
cert.subject.emailAddress
);
return "Invalid certificate issuer";
}
}
}
return "OK";
}
function is_secure (req, res, cert, validate_email = true)
{
res.header("Referrer-Policy", "no-referrer-when-downgrade");
res.header("X-Frame-Options", "deny");
res.header("X-XSS-Protection", "1; mode=block");
res.header("X-Content-Type-Options", "nosniff");
if (req.headers.host && req.headers.host !== SERVER_NAME)
return "Invalid 'host' field in the header";
if (req.headers.origin)
{
const origin = req.headers.origin.toLowerCase();
// e.g Origin = https://www.iudx.org.in:8443/
if (! origin.startsWith("https://"))
{
// allow the server itself to host "http"
if (origin !== "http://" + SERVER_NAME)
return "Insecure 'origin' field";
}
if ((origin.match(/\//g) || []).length < 2)
return "Invalid 'origin' field";
const origin_domain = String (
origin
.split("/")[2] // remove protocol
.split(":")[0] // remove port number
);
let whitelisted = false;
for (const w in WHITELISTED_DOMAINS)
{
if (origin_domain === w)
{
whitelisted = true;
break;
}
}
if (! whitelisted)
{
for (const w in WHITELISTED_ENDSWITH)
{
if (origin_domain.endsWith(w))
{
whitelisted = true;
break;
}
}
}
if (! whitelisted)
{
return "Invalid 'origin' header; this website is not" +
" whitelisted to call this API";
}
res.header("Access-Control-Allow-Origin", req.headers.origin);
res.header("Access-Control-Allow-Methods","POST");
}
const error = is_certificate_ok (req,cert,validate_email);
if (error !== "OK")
return "Invalid certificate : " + error;
return "OK";
}
function has_certificate_been_revoked (socket, cert, CRL)
{
const cert_fingerprint = cert.fingerprint
.replace(/:/g,"")
.toLowerCase();
const cert_serial = cert.serialNumber
.toLowerCase()
.replace(/^0+/,"");
const cert_issuer = cert.issuer.emailAddress.toLowerCase();
for (const c of CRL)
{
c.issuer = c.issuer.toLowerCase();
c.serial = c.serial.toLowerCase().replace(/^0+/,"");
c.fingerprint = c.fingerprint.toLowerCase().replace(/:/g,"");
if (
(c.issuer === cert_issuer) &&
(c.serial === cert_serial) &&
(c.fingerprint === cert_fingerprint)
)
{
return true;
}
}
// If it was issued by a sub-CA then check the sub-CA's cert too
// Assuming depth is <= 3. [email protected] -> sub-CA -> user
if (cert_issuer.startsWith("iudx.sub.ca@"))
{
const ISSUERS = [];
if (cert.issuerCertificate)
{
// both CA and sub-CA are the issuers
ISSUERS.push(cert.issuerCertificate);
if (cert.issuerCertificate.issuerCertificate)
{
ISSUERS.push (
cert.issuerCertificate.issuerCertificate
);
}
}
else
{
/*
if the issuerCertificate is empty,
then the session must have been reused
by the browser.
*/
if (! socket.isSessionReused())
return true;
}
for (const issuer of ISSUERS)
{
if (issuer.fingerprint && issuer.serialNumber)
{
issuer.fingerprint = issuer
.fingerprint
.replace(/:/g,"")
.toLowerCase();
issuer.serialNumber = issuer
.serialNumber
.toLowerCase();
for (const c of CRL)
{
if (c.issuer === "[email protected]")
{
const serial = c.serial
.toLowerCase()
.replace(/^0+/,"");
const fingerprint = c.fingerprint
.replace(/:/g,"")
.toLowerCase();
if (serial === issuer.serial && fingerprint === issuer.fingerprint)
return true;
}
}
}
else
{
/*
if fingerprint OR serial is undefined,
then the session must have been reused
by the browser.
*/
if (! socket.isSessionReused())
return true;
}
}
}
return false;
}
function xss_safe (input)
{
if (typeof input === "string")
return input.replace(/[^-a-zA-Z0-9:/.@_]/g,"*");
else
{
// we can only change string variables
return input;
}
}
function is_string_safe (str, exceptions = "")
{
if (! str || typeof str !== "string")
return false;
if (str.length === 0 || str.length > MAX_SAFE_STRING_LEN)
return false;
exceptions = exceptions + "-/.@";
for (const ch of str)
{
if (
(ch >= "a" && ch <= "z") ||
(ch >= "A" && ch <= "Z") ||
(ch >= "0" && ch <= "9")
)
{
// ok
}
else
{
if (exceptions.indexOf(ch) === -1)
return false;
}
}
return true;
}
function is_iudx_certificate(cert)
{
if (! cert.issuer.emailAddress)
return false;
const email = cert
.issuer
.emailAddress
.toLowerCase();
// certificate issuer should be IUDX CA or a IUDX sub-CA
return (email ==="[email protected]" || email.startsWith("iudx.sub.ca@"));
}
function body_to_json (body)
{
if (! body)
return {};
let string_body;
try
{
string_body = Buffer
.from(body,"utf-8")
.toString("ascii")
.trim();
if (string_body.length === 0)
return {};
}