summaryrefslogtreecommitdiff
path: root/www/keygenIE.js
blob: 51da0efac8613782b4ebf136935d9d23b24486e0 (plain)
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
´╗┐var CAcert_keygen_IE = function () {
	
	/// Makes a new DOM text node
	var textnode = function (text) {
		return document.createTextNode(text);
	}
	
	
	/// makes a new <p> element
	var paragraph = function (text) {
		var paragraph = document.createElement("p");
		paragraph.appendChild(textnode(text));
		return paragraph;
	}
	
	
	/// makes a new <pre> elemtent
	var pre = function (text) {
		var pre = document.createElement("pre");
		pre.appendChild(textnode(text));
		return pre;
	}
	
	
	/// makes a new <option> element
	var option = function (text, value) {
		var option = document.createElement("option");
		if (value !== undefined) {
			option.setAttribute("value", value);
		}
		option.appendChild(textnode(text));
		return option;
	}
	
	
	/// Removes all child nodes from the element
	var removeChildren = function (element) {
		element.innerHTML = "";
	}
	
	
	/// Show error message to user from exception
	var showError = function (message, exception) {
		window.alert(message +
				"\n\nError: " + exception.message +
				" (0x" + (-exception.number).toString(16) + " / " +
				exception.number + ")");
	}
	
	
	
	// Get important elements from the DOM
	var form = document.getElementById("CertReqForm");
	var securityLevel = document.getElementById("SecurityLevel");
	var customSettings = document.getElementById("customSettings");
	var provider = document.getElementById("CspProvider");
	var algorithm = document.getElementById("algorithm");
	var algorithmParagraph = document.getElementById("algorithmParagraph");
	var keySize = document.getElementById("keySize");
	var keySizeMin = document.getElementById("keySizeMin");
	var keySizeMax = document.getElementById("keySizeMax");
	var keySizeStep = document.getElementById("keySizeStep");
	var genReq = document.getElementById("GenReq");
	var csr = document.getElementById("CSR");
	var noActiveX = document.getElementById("noActiveX");
	var generatingKeyNotice = document.getElementById("generatingKeyNotice");
	var createRequestErrorChooseAlgorithm = document.getElementById("createRequestErrorChooseAlgorithm");
	var createRequestError = document.getElementById("createRequestError");
	var invalidKeySizeError = document.getElementById("invalidKeySizeError");
	var unsupportedPlatformError = document.getElementById("unsupportedPlatformError");
	
	
	/// Initialise the CertEnroll code (Vista and higher)
	/// returns false if initialisation fails
	var initCertEnroll = function () {
		var factory = null;
		var providerList = null;
		var cspStats = null;
		
		// Try to initialise the ActiveX element. Requires permissions by the user
		try {
			factory = new ActiveXObject(
				"X509Enrollment.CX509EnrollmentWebClassFactory");
			if (!factory) {
				throw {
					name: "NoObjectError",
					message: "Got null at object creation"
				};
			}
			
			// also try to create a useless object here so the library gets
			// initialised and we don't need to check everytime later
			factory.CreateObject("X509Enrollment.CObjectId");
			
			form.style.display = "";
			noActiveX.style.display = "none";
		} catch (e) {
			return false;
		}
		
		
		/// Get the selected provider
		var getProvider = function () {
			var providerIndex = provider.options[provider.selectedIndex].value;
			return providerList.ItemByIndex(providerIndex);
		}
		
		
		/// Get the selected algorithm
		var getAlgorithm = function () {
			var algorithmIndex = algorithm.options[algorithm.selectedIndex].value;
			return alg = cspStats.ItemByIndex(algorithmIndex).CspAlgorithm;
		}
		
		
		/// Get the selected key size
		var getKeySize = function () {
			var alg = getAlgorithm();
			
			var bits = parseInt(keySize.value, 10);
			if ( bits < alg.MinLength || bits > alg.MaxLength ||
					(alg.IncrementLength &&
						(bits - alg.MinLength) % alg.IncrementLength !== 0)
				)
			{
				return false;
			}
			
			return bits;
		}
		
		
		/// Fill the key size list
		var getKeySizeList = function () {
			if (!cspStats) {
				return false;
			}
			
			var alg = getAlgorithm();
			
			// HTML5 attributes
			keySize.setAttribute("min", alg.MinLength);
			keySize.setAttribute("max", alg.MaxLength);
			keySize.setAttribute("step", alg.IncrementLength);
			keySize.setAttribute("value", alg.DefaultLength);
			keySize.value = ""+alg.DefaultLength;
			
			// ugly, but buggy otherwise if done with text nodes
			keySizeMin.innerHTML = alg.MinLength;
			keySizeMax.innerHTML = alg.MaxLength;
			keySizeStep.innerHTML = alg.IncrementLength;
			
			return true;
		}
		
		
		/// Fill the algorithm list
		var getAlgorithmList = function () {
			var i;
			
			if (!providerList) {
				return false;
			}
			
			var csp = getProvider();
			
			cspStats = providerList.GetCspStatusesFromOperations(
					0x1c, //XCN_NCRYPT_ANY_ASYMMETRIC_OPERATION
					//0x10, //XCN_NCRYPT_SIGNATURE_OPERATION
					//0x8, //XCN_NCRYPT_SECRET_AGREEMENT_OPERATION
					//0x4, //XCN_NCRYPT_ASYMMETRIC_ENCRYPTION_OPERATION
					csp
				);
			
			removeChildren(algorithm);
			for (i = 0; i < cspStats.Count; i++) {
				var alg = cspStats.ItemByIndex(i).CspAlgorithm;
				algorithm.appendChild(option(alg.Name, i));
			}
			
			return getKeySizeList();
		}
		
		
		/// Fill the crypto provider list
		var getProviderList = function () {
			var i;
			
			var csps = factory.CreateObject("X509Enrollment.CCspInformations");
			
			// Get provider information
			csps.AddAvailableCsps();
			
			removeChildren(provider);
			
			for (i = 0; i < csps.Count; i++) {
				var csp = csps.ItemByIndex(i);
				provider.appendChild(option(csp.Name, i));
			}
			
			providerList = csps;
			
			return getAlgorithmList();
		}
		
		
		/// Generate a key and create and submit the actual CSR
		var createCSR = function () {
			var providerName, algorithmOid, bits;
			
			var level = securityLevel.options[securityLevel.selectedIndex];
			if (level.value === "custom") {
				providerName = getProvider().Name;
				var alg = getAlgorithm();
				algorithmOid = alg.GetAlgorithmOid(0, 0)
				bits = getKeySize();
				if (!bits) {
					window.alert(invalidKeySizeError.innerHTML);
					return false;
				}
				
			} else {
				
				providerName = "Microsoft Software Key Storage Provider";
				
				algorithmOid = factory.CreateObject("X509Enrollment.CObjectId");
				algorithmOid.InitializeFromValue("1.2.840.113549.1.1.1"); // RSA
				//"1.2.840.10040.4.1" == DSA
				//"1.2.840.10046.2.1" == DH
				
				if (level.value === "high") {
					bits = 4096;
				} else { // medium
					bits = 2048;
				}
			}
			
			
			var privateKey = factory.CreateObject("X509Enrollment.CX509PrivateKey");
			privateKey.ProviderName = providerName;
			privateKey.Algorithm = algorithmOid;
			privateKey.Length = bits;
			privateKey.KeyUsage = 0xffffff; // XCN_NCRYPT_ALLOW_ALL_USAGES
			
			var request = factory.CreateObject(
				"X509Enrollment.CX509CertificateRequestPkcs10");
			request.InitializeFromPrivateKey(
					1, // ContextUser
					privateKey,
					"" // don't use a template
				);
			
			var enroll = factory.CreateObject("X509Enrollment.CX509Enrollment");
			enroll.InitializeFromRequest(request);
			
			generatingKeyNotice.style.display = "";
			
			
			// The request needs to be created after we return so the "please wait"
			// message gets rendered
			var createCSRHandler = function () {
				try {
					csr.value = enroll.CreateRequest(0x1); //XCN_CRYPT_STRING_BASE64
					form.submit();
				} catch (e) {
					showError(createRequestErrorChooseAlgorithm.innerHTML, e);
				}
				
				generatingKeyNotice.style.display = "none";
			}
			
			window.setTimeout(createCSRHandler, 0);
			
			// Always return false, form is submitted by deferred method
			return false;
		}
		
		
		/// Call if securityLevel has changed
		var refreshSecurityLevel = function () {
			var level = securityLevel.options[securityLevel.selectedIndex];
			if (level.value === "custom") {
				getProviderList();
				customSettings.style.display = "";
			} else {
				customSettings.style.display = "none";
			}
		}
		
		securityLevel.onchange = refreshSecurityLevel;
		provider.onchange = getAlgorithmList;
		algorithm.onchange = getKeySizeList;
		genReq.onclick = createCSR;
		
		return true;
	} // end of initCertEnroll()
	
	
	/// Initialise Xenroll code (XP and lower)
	/// returns false if initialisation fails
	var initXEnroll = function () {
		cenroll = null;
		
		providerTypes = Array(
				 1, //PROV_RSA_FULL
				 2, //PROV_RSA_SIG
				 3, //PROV_DSS
				 4, //PROV_FORTEZZA
				 5, //PROV_MS_EXCHANGE
				 6, //PROV_SSL
				12, //PROV_RSA_SCHANNEL
				13, //PROV_DSS_DH
				14, //PROV_EC_ECDSA_SIG
				15, //PROV_EC_ECNRA_SIG
				16, //PROV_EC_ECDSA_FULL
				17, //PROV_EC_ECNRA_FULL
				18, //PROV_DH_SCHANNEL
				20, //PROV_SPYRUS_LYNKS
				21, //PROV_RNG
				22, //PROV_INTEL_SEC
				23, //PROV_REPLACE_OWF
				24  //PROV_RSA_AES
			);
		
		algClasses = Array(
				1 << 13, //ALG_CLASS_SIGNATURE
				//2 << 13, //ALG_CLASS_MSG_ENCRYPT
				//3 << 13, //ALG_CLASS_DATA_ENCRYPT
				//4 << 13, //ALG_CLASS_HASH
				5 << 13  //ALG_CLASS_KEY_EXCHANGE
			);
		
		// Try to initialise the ActiveX element.
		try {
			cenroll = new ActiveXObject("CEnroll.CEnroll");
			
			if (!cenroll) {
				throw {
					name: "NoObjectError",
					message: "Got null at object creation"
				};
			}
			
			form.style.display = "";
			//algorithmParagraph.style.display = "none";
			algorithm.disabled = true;
			noActiveX.style.display = "none";
		} catch (e) {
			return false;
		}
		
		
		/// Get the name of the selected provider
		var getProviderName = function () {
			return provider.options[provider.selectedIndex].text;
		}
		
		
		/// Get the type of the selected provider
		var getProviderType = function () {
			return parseInt(provider.options[provider.selectedIndex].value, 10);
		}
		
		
		var refreshProvider = function () {
			cenroll.ProviderName = getProviderName();
			cenroll.ProviderType = getProviderType();
		}
		
		
		/// Get the ID of the selected algorithm
		var getAlgorithmId = function () {
			return parseInt(
					algorithm.options[algorithm.selectedIndex].value, 10);
		}
		
		
		/// Minimum bit length for exchange keys
		var getMinExKeyLength = function () {
			refreshProvider();
			
			try {
				return cenroll.GetKeyLen(true, true);
			} catch (e) {
				return false;
			}
		}
		
		
		/// Maximum bit length for exchange keys
		var getMaxExKeyLength = function () {
			refreshProvider();
			
			try {
				return cenroll.GetKeyLen(false, true);
			} catch (e) {
				return false;
			}
		}
		
		
		/// Step size for exchange keys
		/// This might not be available on older platforms
		var getStepExKeyLength = function () {
			refreshProvider();
			
			try {
				return cenroll.GetKeyLenEx(3, 1);
			} catch (e) {
				return false;
			}
		}
		
		
		/// Minimum bit length for signature keys
		var getMinSigKeyLength = function () {
			refreshProvider();
			
			try {
				return cenroll.GetKeyLen(true, false);
			} catch (e) {
				return false;
			}
		}
		
		
		/// Maximum bit length for signature keys
		var getMaxSigKeyLength = function () {
			refreshProvider();
			
			try {
				return cenroll.GetKeyLen(false, false);
			} catch (e) {
				return false;
			}
		}
		
		
		/// Step size for signature keys
		/// This might not be available on older platforms
		var getStepSigKeyLength = function () {
			refreshProvider();
			
			try {
				return cenroll.GetKeyLenEx(3, 2);
			} catch (e) {
				return false;
			}
		}
		
		
		/// Get the selected key size
		var getKeySize = function () {
			var bits = parseInt(keySize.value, 10);
			//TODO: check if the bits are sane
			return bits;
		}
		
		
		var getKeySizeLimits = function () {
			// HTML5 attributes
			keySize.setAttribute("min", getMinSigKeyLength());
			keySize.setAttribute("max", getMaxSigKeyLength());
			if (getStepSigKeyLength()) {
				keySize.setAttribute("step", getStepSigKeyLength());
			}
			//keySize.setAttribute("value", alg.DefaultLength);
			//keySize.value = ""+alg.DefaultLength;
			
			// ugly, but buggy otherwise if done with text nodes
			keySizeMin.innerHTML = getMinSigKeyLength();
			keySizeMax.innerHTML = getMaxSigKeyLength();
			keySizeStep.innerHTML = getStepSigKeyLength();
			
			return true;
		}
		
		
		/// Fill the algorithm selection box
		var getAlgorithmList = function () {
			var i, j;
			
			refreshProvider();
			
			removeChildren(algorithm);
			
			for (i = 0; i < algClasses.length; ++i) {
				for (j = 0; true; ++j) {
					try {
						var algId = cenroll.EnumAlgs(j, algClasses[i]);
						var algName = cenroll.GetAlgName(algId);
						algorithm.appendChild(option(algName, algId));
					} catch (e) {
						break;
					}
				}
			}
			
			getKeySizeLimits();
		}
		
		
		/// Fill the provider selection box
		var getProviderList = function () {
			var i, j;
			
			removeChildren(provider);
			
			for (i = 0; i < providerTypes.length; ++i) {
				cenroll.providerType = providerTypes[i];
				
				var providerName = "invalid";
				for (j = 0; true; ++j) {
					try {
						providerName = cenroll.enumProviders(j, 0);
						provider.appendChild(
								option(providerName, providerTypes[i]));
					} catch (e) {
						break;
					}
				}
			}
			
			return getAlgorithmList();
			//return getKeySizeLimits();
		}
		
		
		var createCSR = function () {
			var providerName, bits;
			
			var level = securityLevel.options[securityLevel.selectedIndex];
			if (level.value === "custom") {
				
				refreshProvider();
				
				bits = getKeySize();
				if (bits === false) {
					window.alert(invalidKeySizeError.innerHTML);
					return false;
				}
				
			} else {
				
				cenroll.ProviderName = "Microsoft Enhanced Cryptographic Provider v1.0";
				cenroll.ProviderType = 1; //PROV_RSA_FULL
				
				if (level.value === "high") {
					bits = 4096;
				} else { // medium
					bits = 2048;
				}
			}
			
			cenroll.GenKeyFlags = bits << 16; // keysize is encoded in the uper 16 bits
			//cenroll.GenKeyFlags = cenroll.GenKeyFlags | 0x1; //CRYPT_EXPORTABLE
			
			generatingKeyNotice.style.display = "";
			
			
			// The request needs to be created after we return so the "please wait"
			// message gets rendered
			var createCSRHandler = function () {
				try {
					csr.value = cenroll.createPKCS10("", "1.3.6.1.5.5.7.3.2");
					form.submit();
				} catch (e) {
					showError(createRequestError.innerHTML, e);
				}
				
				generatingKeyNotice.style.display = "none";
				cenroll.Reset();
			}
			
			window.setTimeout(createCSRHandler, 0);
			
			// Always return false, form is submitted by deferred method
			return false;
		}
		
		
		/// Call if securityLevel has changed
		var refreshSecurityLevel = function () {
			var level = securityLevel.options[securityLevel.selectedIndex];
			if (level.value === "custom") {
				getProviderList();
				customSettings.style.display = "";
			} else {
				customSettings.style.display = "none";
			}
		}
		
		securityLevel.onchange = refreshSecurityLevel;
		provider.onchange = getAlgorithmList;
		//provider.onchange = getKeySizeLimits;
		algorithm.onchange = getKeySizeLimits;
		genReq.onclick = createCSR;
		
		return true;
	};
	
	
	// Run the init functions until one is successful
	if (initCertEnroll()) {
		form.style.display = "";
		noActiveX.style.display = "none";
	} else if (initXEnroll()) {
		form.style.display = "";
		noActiveX.style.display = "none";
	} else {
		window.alert(unsupportedPlatformError.innerHTML);
	}
} ();