forked from duerig/xml-signer
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathxml-signer.js
executable file
·755 lines (701 loc) · 19.4 KB
/
xml-signer.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
/*global require: true */
require.config({
'paths': {
'underscore': 'lib/underscore-min',
'jquery': 'require-jquery',
'bootstrap': 'lib/bootstrap/js/bootstrap.min'
},
'shim': {
'underscore': {
'exports': '_'
}
}
});
require(['jquery', 'underscore', 'error', 'lib/forge/forge',
'lib/xml-crypto/signed-xml',
'text!template/credential.txt', 'text!template/no-key.html',
'text!template/authorize.html', 'bootstrap'],
function ($, _, error, forge, sigExport, xmlText, noKeyText, authorizeText) {
'use strict';
var SignedXml = sigExport.SignedXml;
var singleDay = 1000*60*60*24;
var saList = [];
function parseSaList(str)
{
saList = [];
var lines = str.split('\n');
_.each(lines, function (line) {
var fields = line.split(' ');
if (fields.length > 1)
{
var name = fields[0].split('+')[1];
var url;
if (fields.length === 2)
{
var urlPaths = fields[1].split('/');
url = urlPaths[0] + '//' + urlPaths[2].split(':')[0] +
'/getsslcertjs.php3';
}
else if (fields.length === 3)
{
url = fields[2];
}
if (url)
{
saList.push({ name: name,
url: url });
}
else
{
console.log('Invalid URL for ', fields[0]);
}
}
});
}
function parseSaListJson(str) {
$.each(str['identity-providers'], function() {
saList.push({ name: this.urn.split('+')[1],
url: this['web-cert-url'],
icon: this.icon })
})
}
var debugCert = null;
var toolId = $('script#tool_id').text();
var speakerCert = null;
var xmlTemplate = _.template(xmlText);
var authorizeTemplate = _.template(authorizeText);
var xml = "";
var encryptedKey = "";
var certList = [];
var certWindow;
var userId = 'urn:publicid:IDN+jonlab.testbed.emulab.net+user+jld';
var defaultMA = { url: null, name: null};
var myCert = $('script#tool_cert').text().replace(/\\n/g, "\n");
var backTo = $('script#backto').text();
function initialize()
{
var promise = $.get('https://www.emulab.net/protogeni/boot/salist.json');
promise.then(function (response) {
parseSaListJson(response);
var params = getQueryParams(window.location.search);
if (toolId == '') {
toolId = params.id;
}
if (toolId)
{
var data = { ready: true };
if (window.opener) {
window.addEventListener('message', messageToolCert, false);
window.opener.postMessage(data, '*');
console.log('posting ready message');
} else {
var fake_event = { data: { certificate: myCert, tool: true } }
messageToolCert(fake_event);
}
}
else
{
messageToolCert(null);
}
}, function (error) {
console.log('Error fetching SA List: ', error);
flagError();
});
}
function messageToolCert(event)
{
/* If the tool requested an MA by URL, extract it. */
if (event && event.data.ma)
{
defaultMA.url = event.data.ma.url;
defaultMA.name = event.data.ma.name;
}
if (event && event.data.certificate && event.data.tool)
{
debugCert = event.data.certificate;
var speakerCertList = extractCertificates(event.data.certificate);
if (speakerCertList.length > 0)
{
speakerCert = speakerCertList[0];
}
// var cannedCert = $('#preset-bundle');
var userCert;
try {
userCert = JSON.parse(window.localStorage.certificateList)[0];
} catch (e) {}
if (! userCert && event.data.userBundle)
{
userCert = event.data.userBundle;
}
/*
if (! userCert && cannedCert.length > 0)
{
userCert = cannedCert[0].textContent;
}
*/
if ((toolId && speakerCert)
|| (! toolId && ! speakerCert))
{
if (userCert)
{
setupClientPem(userCert);
_.defer(initAuthorize);
}
else
{
_.defer(initNoKey);
}
}
else
{
flagError();
}
}
}
function flagError()
{
$('#main-content').html('<h1>Error</h1><p>There was an error initializing. Close this window and try again.</p>');
}
function extractCertificates(pem)
{
var inCert = false;
var userCertificate = "";
var result = [];
var lines = pem.split('\n');
var i = 0;
for (i = 0; i < lines.length; i += 1)
{
if (lines[i] === "-----BEGIN CERTIFICATE-----")
{
inCert = true;
userCertificate = "";
}
else if (lines[i] === "-----END CERTIFICATE-----")
{
inCert = false;
result.push(userCertificate);
}
else if (inCert)
{
userCertificate += lines[i] + '\n';
}
}
return result;
}
function wrapCertificates(list)
{
var result = "";
var i = 0;
for (; i < list.length; i += 1)
{
result += "-----BEGIN CERTIFICATE-----\n";
result += list[i];
result += "-----END CERTIFICATE-----\n";
}
return result;
}
function extractKey(pem)
{
var pkcs1_begin = "-----BEGIN RSA PRIVATE KEY-----";
var pkcs1_end = "-----END RSA PRIVATE KEY-----";
var pkcs8_begin = "-----BEGIN PRIVATE KEY-----";
var pkcs8_end = "-----END PRIVATE KEY-----";
var inKey = false;
var key = "";
var lines = pem.split('\n');
var i = 0;
for (i = 0; i < lines.length; i += 1)
{
if (lines[i] === pkcs1_begin || lines[i] === pkcs8_begin)
{
key = lines[i] + '\n';
inKey = true;
}
else if (lines[i] === pkcs1_end || lines[i] === pkcs8_end)
{
key += lines[i] + '\n';
inKey = false;
}
else if (inKey)
{
key += lines[i] + '\n';
}
}
return key;
}
function initNoKey()
{
$('#main-content').html(noKeyText);
$('#sa-form').submit(clickGetCert);
$('#sa-button').click(clickGetCert);
$('#paste-form').submit(clickPasteCert);
$('#paste-button').click(clickPasteCert);
$('#forgetAll').click(clickLogout);
window.addEventListener('message', messageCert);
var choice = $('#sa-choice');
var i = 0;
var defaultFound = false;
for (i = 0; i < saList.length; i += 1)
{
var attrs = 'value="' + saList[i].url + '"';
if (defaultMA.url && defaultMA.url == saList[i].url)
{
defaultFound = true;
attrs += ' selected="selected"'
}
choice.append('<option ' + attrs + '>' + saList[i].name +
'</option>');
}
if (! defaultFound && defaultMA.url && defaultMA.name)
{
choice.append('<option value="' + defaultMA.url + '" selected="selected">'
+ defaultMA.name + '</option>');
}
$('#default-choice-1').click(function() {
$('#sa-choice').val('https://www.emulab.net/getsslcertjs.php3');
$('#sa-button').click();
});
$('#default-choice-2').click(function() {
$('#sa-choice').val('https://portal.geni.net/secure/loadcert.php');
$('#sa-button').click();
});
}
function initAuthorize()
{
var fillId = '';
if (toolId)
{
fillId = toolId;
}
var content = authorizeTemplate({id: fillId});
$('#main-content').html(content);
if (! toolId)
{
$('.tool-info').hide();
}
else
{
$('.no-tool-info').hide();
}
$('#sign').click(clickSign);
$('#private').submit(clickSign);
$('#logout').click(clickLogout);
window.removeEventListener('message', messageCert);
window.addEventListener('message', messageAck);
if (! isEncrypted(encryptedKey))
{
var shouldAccept = false;
try {
var accepted = JSON.parse(window.localStorage.accepted);
if (accepted[toolId] !== undefined)
{
$('#time').val(accepted[toolId]);
shouldAccept = true;
}
} catch (e) {}
if (shouldAccept)
{
clickSign();
}
$('#password-container').hide();
$('.password-text').hide();
$('#rememberCheckContainer').show();
}
else
{
$('#password-container').show();
$('.password-text').show();
$('#rememberCheckContainer').hide();
}
getCertFields(certList);
$('#advancedCheck').change(function() {
if ($('.toggleAdvanced').hasClass('toggled')) {
$('.toggleAdvanced').each(function() {
$(this).removeClass('toggled');
});
}
else {
$('.toggleAdvanced').each(function() {
$(this).addClass('toggled');
});
}
});
}
/**
* Populate the KeyInfo block in the signature. Add a KeyValue block
* with the signing public key info (modulus and exponent). Put the
* full certificate chain in the X509Data block so that it can be
* verified.
*
* @param chain an one or more certificates in an array where the
* first is the signing certificate.
*/
function GENIKeyInfo(chain)
{
this.chain = chain;
/**
* Note: This is a private function from forge.rsa
* Converts a positive BigInteger into 2's-complement big-endian bytes.
*
* @param b the big integer to convert.
*
* @return the bytes.
*/
this.bnToBytes = function(b) {
// prepend 0x00 if first byte >= 0x80
var hex = b.toString(16);
if(hex[0] >= '8') {
hex = '00' + hex;
}
return forge.util.hexToBytes(hex);
}
this.keyValue = function(pemcert) {
var cert = parsePemCert(this.chain[0]);
var modulus = cert.publicKey.n;
var modulus64 = forge.util.encode64(this.bnToBytes(modulus), 64);
/* forge puts CR and NL in, we just want NL. */
modulus64 = modulus64.replace(/\r\n/g,"\n");
var exponent = cert.publicKey.e;
var exponent64 = forge.util.encode64(this.bnToBytes(exponent), 64);
var res = "\n<KeyValue>\n<RSAKeyValue>\n<Modulus>";
res += modulus64;
res += "\n</Modulus>\n<Exponent>";
res += exponent64;
res += "</Exponent>\n</RSAKeyValue></KeyValue>";
return res;
}
this.getKeyInfo = function(key) {
var res = "";
if (this.chain) {
res += this.keyValue(this.chain[0]);
res += "\n<X509Data>";
for (var i = 0; i < this.chain.length; i++) {
res += "\n<X509Certificate>";
res += this.chain[i];
res += "</X509Certificate>";
}
res += "\n</X509Data>";
}
return res
};
this.getKey = function(keyInfo) {
return "";
};
}
var speaksForCredential;
var decryptedPrivateKey;
var userSecret;
function clickSign(event)
{
if (event)
{
event.preventDefault();
}
if (! isEncrypted(encryptedKey) && $('#rememberCheck')[0].checked)
{
try {
var acceptedStr = window.localStorage.accepted;
var accepted;
if (acceptedStr)
{
accepted = JSON.parse(window.localStorage.accepted);
}
else
{
accepted = {};
}
accepted[toolId] = $('#time').val();
window.localStorage.accepted = JSON.stringify(accepted);
} catch (e) { }
}
var durationDays = parseInt($('#time').val(), 10);
var timeOffset = 120 * singleDay;
if (durationDays && durationDays > 0 && durationDays < 400)
{
timeOffset = durationDays * singleDay;
}
var e = new Date();
e.setTime(e.getTime() + timeOffset);
var eString = e.toISOString();
var xml = xmlTemplate({ 'expires': eString,
'userKeyhash': getKeyhash(certList[0]),
'toolKeyhash': getKeyhash(speakerCert) });
var password = $('#password').val();
try
{
var decrypted = forge.pki.decryptRsaPrivateKey(encryptedKey, password);
decryptedPrivateKey = decrypted;
var sig = new SignedXml();
sig.addReference("//*[local-name(.)='credential']");
sig.signingKey = decrypted;
sig.signatureNode = "//*[local-name(.)='signatures']";
if (certList.length > 0)
{
sig.keyInfoProvider = new GENIKeyInfo(certList);
}
sig.computeSignature(xml);
speaksForCredential = sig.getSignedXml();
var userToken = generateUserToken(speakerCert);
var data = {
id: toolId,
credential: speaksForCredential,
userToken: userToken,
userCertificate: wrapCertificates(certList)
};
if (window.opener) {
window.opener.postMessage(data, '*');
console.log('posting credential');
} else {
// This can't be the only way to redirect with POST, sigh...
var backForm = document.createElement('form');
backForm.method = 'POST';
backForm.action = backTo;
backForm.name = 'backto';
var idInput = document.createElement('input');
idInput.type = 'hidden';
idInput.name = 'data_id';
idInput.value = data.id;
var credentialInput = document.createElement('input');
credentialInput.type = 'hidden';
credentialInput.name = 'data_credential';
credentialInput.value = data.credential;
backForm.appendChild(idInput);
backForm.appendChild(credentialInput);
backForm.submit();
}
}
catch (e)
{
console.log('Error signing credential:', e);
error.show();
$('#password-container #password').on('input', function() {
error.hide();
$('#password-container #password').off('input');
})
}
}
function clickGetCert(event)
{
event.preventDefault();
if (certWindow)
{
certWindow.close();
}
var url = $('#sa-choice').val();
if (url !== '')
{
var encodedToolId = encodeURIComponent(toolId);
url += '?toolid=' + encodedToolId;
certWindow = window.open(url, 'Slice Authority Credential',
'height=400,width=600');
}
return false;
}
function clickPasteCert(event)
{
event.preventDefault();
var input = $('#paste-input');
if (input.val() !== '')
{
addCert(input.val());
}
return false;
}
function messageAck(event)
{
console.log('messageAck');
if (event.source === window.opener && event.data && event.data.id &&
event.data.id === toolId)
{
if (event.data.ack)
{
window.close();
}
else if (event.data.toolToken)
{
sendAuthorizationToken(event.data.toolToken);
}
}
}
function sendAuthorizationToken(toolToken)
{
var encryptedCredential = encryptWithSecrets(userSecret, getToolSecret(toolToken));
var data = {
id: toolId,
encryptedCredential: encryptedCredential,
credential: speaksForCredential
};
window.opener.postMessage(data, '*');
console.log('posting auth token');
}
function generateUserToken(speakerCert)
{
var secretBytes = forge.random.getBytesSync(32);
userSecret = forge.util.bytesToHex(secretBytes);
var p7 = forge.pkcs7.createEnvelopedData();
var cert = forge.pki.certificateFromPem(wrapCertificates([speakerCert]));
p7.addRecipient(cert);
p7.content = forge.util.createBuffer(userSecret);
p7.encrypt();
return forge.pkcs7.messageToPem(p7);
}
function getToolSecret(toolToken)
{
var p7 = forge.pkcs7.messageFromPem(toolToken);
p7.decrypt(p7.recipients[0], decryptedPrivateKey);
return p7.content.toString();
}
function encryptWithSecrets(userSecret, toolSecret)
{
var md = forge.md.sha256.create();
md.update(speaksForCredential + userSecret + toolSecret);
return md.digest().toHex();
}
function messageCert(event)
{
console.log('messageCert');
if (event.source === certWindow && event.data && event.data.authority)
{
if (event.data.certificate)
{
addCert(event.data.certificate);
}
else if (event.data.sfcred)
{
reflectCred(event.data.sfcred);
}
}
}
function addCert(cert)
{
setupClientPem(cert);
if (isEncrypted(encryptedKey))
{
try {
window.localStorage.certificateList = JSON.stringify([cert]);
} catch (e) {}
}
initAuthorize();
}
function setupClientPem(pem)
{
encryptedKey = extractKey(pem);
certList = extractCertificates(pem);
}
/*
* Reflect a speaks-for credential back to the original tool
*/
function reflectCred(cred)
{
var data = {
id: toolId,
credential: cred
};
window.opener.postMessage(data, '*');
console.log('posting reflect cred');
window.removeEventListener('message', messageCert);
window.addEventListener('message', messageAck);
}
function clickLogout(event)
{
event.preventDefault();
try {
delete window.localStorage.certificateList;
delete window.localStorage.accepted;
} catch (e) {}
certList = [];
encryptedKey = "";
initNoKey();
return false;
}
function htmlEncode(value)
{
var result = '';
if (value) {
result = $('<div />').text(value).html();
}
return result;
};
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {};
var re = /[?&]?([^=]+)=([^&]*)/g;
var tokens = re.exec(qs);
while (tokens) {
params[decodeURIComponent(tokens[1])]
= decodeURIComponent(tokens[2]);
tokens = re.exec(qs);
}
return params;
}
function parsePemCert(pem)
{
var cert = forge.pki.certificateFromPem('-----BEGIN CERTIFICATE-----\n' +
pem + '\n' +
'-----END CERTIFICATE-----\n');
return cert;
}
function getKeyhash(pem)
{
var cert = parsePemCert(pem);
var asnBitstring = forge.pki.publicKeyToRSAPublicKey(cert.publicKey);
var derBitstring = forge.asn1.toDer(asnBitstring);
var sha1 = forge.md.sha1.create();
sha1.update(derBitstring.bytes());
return sha1.digest().toHex();
}
function isEncrypted(key)
{
var result = true;
try
{
var decrypted = forge.pki.decryptRsaPrivateKey(key, '');
// If there are no exceptions, this is an unencrypted key.
result = false;
}
catch (e) {}
return result;
}
function getCertFields (certificateList)
{
// _.each(certificateList, function (certificate) {
var cert = parsePemCert(certificateList[0]);
var found = false;
var urn;
var name;
var altField;
_.each(cert.extensions, function (field) {
if (field.name === 'subjectAltName')
{
altField = field;
}
});
if (altField)
{
_.each(altField.altNames, function (item) {
if (item.type === 6 && item.value.substr(0, 12) === 'urn:publicid')
{
urn = item.value;
}
});
}
if (urn)
{
name = urn.split('+')[3];
found = true;
}
if (found)
{
var authorityUrn = 'urn:publicid:IDN+' + urn.split('+')[1] +
'+authority+sa';
fillUserForm(name, authorityUrn);
}
// });
}
function fillUserForm(name, authority)
{
$('#userName').val(name);
$('#authorityName').val(authority.split('+')[1]);
}
$(document).ready(initialize);
});