Project

General

Profile

Download (51.5 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * system_certmanager.php
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2004-2013 BSD Perimeter
7
 * Copyright (c) 2013-2016 Electric Sheep Fencing
8
 * Copyright (c) 2014-2021 Rubicon Communications, LLC (Netgate)
9
 * Copyright (c) 2008 Shrew Soft Inc
10
 * All rights reserved.
11
 *
12
 * Licensed under the Apache License, Version 2.0 (the "License");
13
 * you may not use this file except in compliance with the License.
14
 * You may obtain a copy of the License at
15
 *
16
 * http://www.apache.org/licenses/LICENSE-2.0
17
 *
18
 * Unless required by applicable law or agreed to in writing, software
19
 * distributed under the License is distributed on an "AS IS" BASIS,
20
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21
 * See the License for the specific language governing permissions and
22
 * limitations under the License.
23
 */
24

    
25
##|+PRIV
26
##|*IDENT=page-system-certmanager
27
##|*NAME=System: Certificate Manager
28
##|*DESCR=Allow access to the 'System: Certificate Manager' page.
29
##|*MATCH=system_certmanager.php*
30
##|-PRIV
31

    
32
require_once("guiconfig.inc");
33
require_once("certs.inc");
34
require_once("pfsense-utils.inc");
35

    
36
// Non-display functions moved to this include file for MVC
37
require_once("system_certmanager.inc");
38

    
39
init_config_arr(array('ca'));
40
$a_ca = &$config['ca'];
41

    
42
$cert_methods = array(
43
	"internal" => gettext("Create an internal Certificate"),
44
	"import" => gettext("Import an existing Certificate"),
45
	"external" => gettext("Create a Certificate Signing Request"),
46
	"sign" => gettext("Sign a Certificate Signing Request")
47
);
48

    
49
$cert_keylens = array("1024", "2048", "3072", "4096", "6144", "7680", "8192", "15360", "16384");
50
$cert_keytypes = array("RSA", "ECDSA");
51
$cert_types = array(
52
	"server" => "Server Certificate",
53
	"user" => "User Certificate");
54

    
55
global $cert_altname_types;
56
global $openssl_digest_algs;
57
global $cert_strict_values;
58
$max_lifetime = cert_get_max_lifetime();
59
$default_lifetime = min(3650, $max_lifetime);
60
$openssl_ecnames = cert_build_curve_list();
61
$class = "success";
62

    
63
if (isset($_REQUEST['userid']) && is_numericint($_REQUEST['userid'])) {
64
	$userid = $_REQUEST['userid'];
65
}
66

    
67
if (isset($userid)) {
68
	$cert_methods["existing"] = gettext("Choose an existing certificate");
69
	init_config_arr(array('system', 'user'));
70
	$a_user =& $config['system']['user'];
71
}
72

    
73
$internal_ca_count = 0;
74
foreach ($a_ca as $ca) {
75
	if ($ca['prv']) {
76
		$internal_ca_count++;
77
	}
78
}
79

    
80
if ($_REQUEST['exportp12']) {
81
	$act = 'p12';
82
} elseif ($_REQUEST['exportpkey']) {
83
	$act = 'key';
84
} else {
85
	$act = $_REQUEST['act'];
86
}
87

    
88
if ($act == 'edit') {
89
	$cert_methods = array(
90
		'edit' => gettext("Edit an existing certificate")
91
	);
92
}
93

    
94
if (isset($_REQUEST['id']) && ctype_alnum($_REQUEST['id'])) {
95
	$id = $_REQUEST['id'];
96
}
97
if (!empty($id)) {
98
	$thiscert =& lookup_cert($id);
99
}
100

    
101
/* Actions other than 'new' require an ID.
102
 * 'del' action must be submitted via POST. */
103
if ((!empty($act) &&
104
    ($act != 'new') &&
105
    !$thiscert) ||
106
    (($act == 'del') && empty($_POST))) {
107
	pfSenseHeader("system_certmanager.php");
108
	exit;
109
}
110

    
111
switch ($act) {
112
	case 'del':
113
		$name = htmlspecialchars($thiscert['descr']);
114
		if (cert_in_use($id)) {
115
			$savemsg = sprintf(gettext("Certificate %s is in use and cannot be deleted"), $name);
116
			$class = "danger";
117
		} else {
118
			foreach ($a_cert as $cid => $acrt) {
119
				if ($acrt['refid'] == $thiscert['refid']) {
120
					unset($a_cert[$cid]);
121
				}
122
			}
123
			$savemsg = sprintf(gettext("Deleted certificate %s"), $name);
124
			write_config($savemsg);
125
		}
126
		unset($act);
127
		break;
128
	case 'new':
129
		/* New certificate, so set default values */
130
		$pconfig['method'] = $_POST['method'];
131
		$pconfig['keytype'] = "RSA";
132
		$pconfig['keylen'] = "2048";
133
		$pconfig['ecname'] = "prime256v1";
134
		$pconfig['digest_alg'] = "sha256";
135
		$pconfig['csr_keytype'] = "RSA";
136
		$pconfig['csr_keylen'] = "2048";
137
		$pconfig['csr_ecname'] = "prime256v1";
138
		$pconfig['csr_digest_alg'] = "sha256";
139
		$pconfig['csrsign_digest_alg'] = "sha256";
140
		$pconfig['type'] = "user";
141
		$pconfig['lifetime'] = $default_lifetime;
142
		break;
143
	case 'edit':
144
		/* Editing a certificate, so populate values */
145
		$pconfig['descr'] = $thiscert['descr'];
146
		$pconfig['cert'] = base64_decode($thiscert['crt']);
147
		$pconfig['key'] = base64_decode($thiscert['prv']);
148
		break;
149
	case 'csr':
150
		/* Editing a CSR, so populate values */
151
		$pconfig['descr'] = $thiscert['descr'];
152
		$pconfig['csr'] = base64_decode($thiscert['csr']);
153
		break;
154
	case 'exp':
155
		/* Exporting a certificate */
156
		send_user_download('data', base64_decode($thiscert['crt']), "{$thiscert['descr']}.crt");
157
		break;
158
	case 'req':
159
		/* Exporting a certificate signing request */
160
		send_user_download('data', base64_decode($thiscert['csr']), "{$thiscert['descr']}.req");
161
		break;
162
	case 'key':
163
		/* Exporting a private key */
164
		$keyout = base64_decode($thiscert['prv']);
165
		if (isset($_POST['exportpass']) && !empty($_POST['exportpass'])) {
166
			if ((strlen($_POST['exportpass']) < 4) or (strlen($_POST['exportpass']) > 1023)) {
167
				$savemsg = gettext("Export password must be in 4 to 1023 characters.");
168
				$class = 'danger';
169
				break;
170
			} else {
171
				$res_key = openssl_pkey_get_private($keyout);
172
				if ($res_key) {
173
					$args = array('encrypt_key_cipher' => OPENSSL_CIPHER_AES_256_CBC);
174
					openssl_pkey_export($res_key, $keyout, $_POST['exportpass'], $args);
175
				} else {
176
					$savemsg = gettext("Unable to export password-protected private key.");
177
					$class = 'danger';
178
				}
179
			}
180
		}
181
		if (!empty($keyout)) {
182
			send_user_download('data', $keyout, "{$thiscert['descr']}.key");
183
		}
184
		break;
185
	case 'p12':
186
		/* Exporting a PKCS#12 file containing the certificate, key, and (if present) CA */
187
		if (isset($_POST['exportpass']) && !empty($_POST['exportpass'])) {
188
			if ((strlen($_POST['exportpass']) < 4) or (strlen($_POST['exportpass']) > 1023)) {
189
				$savemsg = gettext("Export password must be in 4 to 1023 characters.");
190
				$class = 'danger';
191
				break;
192
			} else {
193
				$password = $_POST['exportpass'];
194
			}
195
		} else {
196
			$password = null;
197
		}
198
		$args = array();
199
		$args['friendly_name'] = $thiscert['descr'];
200
		$args['encrypt_key_cipher'] = OPENSSL_CIPHER_AES_256_CBC;
201
		$ca = lookup_ca($thiscert['caref']);
202
		if ($ca) {
203
			/* If the CA can be found, then add the CA to the container */
204
			$args['extracerts'] = openssl_x509_read(base64_decode($ca['crt']));
205
		}
206
		$res_crt = openssl_x509_read(base64_decode($thiscert['crt']));
207
		$res_key = openssl_pkey_get_private(base64_decode($thiscert['prv']));
208
		$exp_data = "";
209
		openssl_pkcs12_export($res_crt, $exp_data, $res_key, $password, $args);
210
		send_user_download('data', $exp_data, "{$thiscert['descr']}.p12");
211
		break;
212
	default:
213
		break;
214
}
215

    
216
if ($_POST['save'] == gettext("Save")) {
217
	/* Creating a new entry */
218
	$input_errors = array();
219
	$pconfig = $_POST;
220

    
221
	switch ($pconfig['method']) {
222
		case 'sign':
223
			$reqdfields = explode(" ",
224
				"descr catosignwith");
225
			$reqdfieldsn = array(
226
				gettext("Descriptive name"),
227
				gettext("CA to sign with"));
228

    
229
			if (($_POST['csrtosign'] === "new") &&
230
			    ((!strstr($_POST['csrpaste'], "BEGIN CERTIFICATE REQUEST") || !strstr($_POST['csrpaste'], "END CERTIFICATE REQUEST")) &&
231
			    (!strstr($_POST['csrpaste'], "BEGIN NEW CERTIFICATE REQUEST") || !strstr($_POST['csrpaste'], "END NEW CERTIFICATE REQUEST")))) {
232
				$input_errors[] = gettext("This signing request does not appear to be valid.");
233
			}
234

    
235
			if ( (($_POST['csrtosign'] === "new") && (strlen($_POST['keypaste']) > 0)) && 
236
			    ((!strstr($_POST['keypaste'], "BEGIN PRIVATE KEY") && !strstr($_POST['keypaste'], "BEGIN EC PRIVATE KEY")) || 
237
			    (strstr($_POST['keypaste'], "BEGIN PRIVATE KEY") && !strstr($_POST['keypaste'], "END PRIVATE KEY")) ||
238
			    (strstr($_POST['keypaste'], "BEGIN EC PRIVATE KEY") && !strstr($_POST['keypaste'], "END EC PRIVATE KEY")))) {
239
				$input_errors[] = gettext("This private does not appear to be valid.");
240
				$input_errors[] = gettext("Key data field should be blank, or a valid x509 private key");
241
			}
242

    
243
			if ($_POST['lifetime'] > $max_lifetime) {
244
				$input_errors[] = gettext("Lifetime is longer than the maximum allowed value. Use a shorter lifetime.");
245
			}
246
			break;
247
		case 'edit':
248
		case 'import':
249
			$pkcs12_data = '';
250
			if ($_POST['import_type'] == 'x509') {
251
				$reqdfields = explode(" ",
252
					"descr cert");
253
				$reqdfieldsn = array(
254
					gettext("Descriptive name"),
255
					gettext("Certificate data"));
256
				if ($_POST['cert'] && (!strstr($_POST['cert'], "BEGIN CERTIFICATE") || !strstr($_POST['cert'], "END CERTIFICATE"))) {
257
					$input_errors[] = gettext("This certificate does not appear to be valid.");
258
				}
259

    
260
				if ($_POST['key'] && (cert_get_publickey($_POST['cert'], false) != cert_get_publickey($_POST['key'], false, 'prv'))) {
261
					$input_errors[] = gettext("The submitted private key does not match the submitted certificate data.");
262
				}
263
			} else {
264
				$reqdfields = array('descr');
265
				$reqdfieldsn = array(gettext("Descriptive name"));
266
				if (!empty($_FILES['pkcs12_cert']) && is_uploaded_file($_FILES['pkcs12_cert']['tmp_name'])) {
267
					$pkcs12_file = file_get_contents($_FILES['pkcs12_cert']['tmp_name']);
268
					if (!openssl_pkcs12_read($pkcs12_file, $pkcs12_data, $_POST['pkcs12_pass'])) {
269
						$input_errors[] = gettext("The submitted password does not unlock the submitted PKCS #12 certificate.");
270
					}
271
				} else {
272
					$input_errors[] = gettext("A PKCS #12 certificate store was not uploaded.");
273
				}
274
			}
275
			break;
276
		case 'internal':
277
			$reqdfields = explode(" ",
278
				"descr caref keylen ecname keytype type lifetime dn_commonname");
279
			$reqdfieldsn = array(
280
				gettext("Descriptive name"),
281
				gettext("Certificate authority"),
282
				gettext("Key length"),
283
				gettext("Elliptic Curve Name"),
284
				gettext("Key type"),
285
				gettext("Certificate Type"),
286
				gettext("Lifetime"),
287
				gettext("Common Name"));
288
			if ($_POST['lifetime'] > $max_lifetime) {
289
				$input_errors[] = gettext("Lifetime is longer than the maximum allowed value. Use a shorter lifetime.");
290
			}
291
			break;
292
		case 'external':
293
			$reqdfields = explode(" ",
294
				"descr csr_keylen csr_ecname csr_keytype csr_dn_commonname");
295
			$reqdfieldsn = array(
296
				gettext("Descriptive name"),
297
				gettext("Key length"),
298
				gettext("Elliptic Curve Name"),
299
				gettext("Key type"),
300
				gettext("Common Name"));
301
			break;
302
		case 'existing':
303
			$reqdfields = array("certref");
304
			$reqdfieldsn = array(gettext("Existing Certificate Choice"));
305
			break;
306
		default:
307
			break;
308
	}
309

    
310
	$altnames = array();
311
	do_input_validation($_POST, $reqdfields, $reqdfieldsn, $input_errors);
312

    
313
	if (!in_array($pconfig['method'], array('edit', 'import', 'existing'))) {
314
		/* subjectAltNames */
315
		$san_typevar = 'altname_type';
316
		$san_valuevar = 'altname_value';
317
		// This is just the blank alternate name that is added for display purposes. We don't want to validate/save it
318
		if ($_POST["{$san_valuevar}0"] == "") {
319
			unset($_POST["{$san_typevar}0"]);
320
			unset($_POST["{$san_valuevar}0"]);
321
		}
322
		foreach ($_POST as $key => $value) {
323
			$entry = '';
324
			if (!substr_compare($san_typevar, $key, 0, strlen($san_typevar))) {
325
				$entry = substr($key, strlen($san_typevar));
326
				$field = 'type';
327
			} elseif (!substr_compare($san_valuevar, $key, 0, strlen($san_valuevar))) {
328
				$entry = substr($key, strlen($san_valuevar));
329
				$field = 'value';
330
			}
331

    
332
			if (ctype_digit($entry)) {
333
				$entry++;	// Pre-bootstrap code is one-indexed, but the bootstrap code is 0-indexed
334
				$altnames[$entry][$field] = $value;
335
			}
336
		}
337

    
338
		$pconfig['altnames']['item'] = $altnames;
339

    
340
		/* Input validation for subjectAltNames */
341
		foreach ($altnames as $idx => $altname) {
342
			switch ($altname['type']) {
343
				case "DNS":
344
					if (!is_hostname($altname['value'], true) || is_ipaddr($altname['value'])) {
345
						$input_errors[] = gettext("DNS subjectAltName values must be valid hostnames, FQDNs or wildcard domains.");
346
					}
347
					break;
348
				case "IP":
349
					if (!is_ipaddr($altname['value'])) {
350
						$input_errors[] = gettext("IP subjectAltName values must be valid IP Addresses");
351
					}
352
					break;
353
				case "email":
354
					if (empty($altname['value'])) {
355
						$input_errors[] = gettext("An e-mail address must be provided for this type of subjectAltName");
356
					}
357
					if (preg_match("/[\!\#\$\%\^\(\)\~\?\>\<\&\/\\\,\"\']/", $altname['value'])) {
358
						$input_errors[] = gettext("The e-mail provided in a subjectAltName contains invalid characters.");
359
					}
360
					break;
361
				case "URI":
362
					/* Close enough? */
363
					if (!is_URL($altname['value'])) {
364
						$input_errors[] = gettext("URI subjectAltName types must be a valid URI");
365
					}
366
					break;
367
				default:
368
					$input_errors[] = gettext("Unrecognized subjectAltName type.");
369
			}
370
		}
371

    
372
		/* Make sure we do not have invalid characters in the fields for the certificate */
373
		if (preg_match("/[\?\>\<\&\/\\\"\']/", $_POST['descr'])) {
374
			$input_errors[] = gettext("The field 'Descriptive Name' contains invalid characters.");
375
		}
376
		$pattern = '/[^a-zA-Z0-9\ \'\/~`\!@#\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/';
377
		if (!empty($_POST['dn_commonname']) && preg_match($pattern, $_POST['dn_commonname'])) {
378
			$input_errors[] = gettext("The field 'Common Name' contains invalid characters.");
379
		}
380
		if (!empty($_POST['dn_state']) && preg_match($pattern, $_POST['dn_state'])) {
381
			$input_errors[] = gettext("The field 'State or Province' contains invalid characters.");
382
		}
383
		if (!empty($_POST['dn_city']) && preg_match($pattern, $_POST['dn_city'])) {
384
			$input_errors[] = gettext("The field 'City' contains invalid characters.");
385
		}
386
		if (!empty($_POST['dn_organization']) && preg_match($pattern, $_POST['dn_organization'])) {
387
			$input_errors[] = gettext("The field 'Organization' contains invalid characters.");
388
		}
389
		if (!empty($_POST['dn_organizationalunit']) && preg_match($pattern, $_POST['dn_organizationalunit'])) {
390
			$input_errors[] = gettext("The field 'Organizational Unit' contains invalid characters.");
391
		}
392

    
393
		switch ($pconfig['method']) {
394
			case "internal":
395
				if (isset($_POST["keytype"]) && !in_array($_POST["keytype"], $cert_keytypes)) {
396
					$input_errors[] = gettext("Please select a valid Key Type.");
397
				}
398
				if (isset($_POST["keylen"]) && !in_array($_POST["keylen"], $cert_keylens)) {
399
					$input_errors[] = gettext("Please select a valid Key Length.");
400
				}
401
				if (isset($_POST["ecname"]) && !in_array($_POST["ecname"], array_keys($openssl_ecnames))) {
402
					$input_errors[] = gettext("Please select a valid Elliptic Curve Name.");
403
				}
404
				if (!in_array($_POST["digest_alg"], $openssl_digest_algs)) {
405
					$input_errors[] = gettext("Please select a valid Digest Algorithm.");
406
				}
407
				break;
408
			case "external":
409
				if (isset($_POST["csr_keytype"]) && !in_array($_POST["csr_keytype"], $cert_keytypes)) {
410
					$input_errors[] = gettext("Please select a valid Key Type.");
411
				}
412
				if (isset($_POST["csr_keylen"]) && !in_array($_POST["csr_keylen"], $cert_keylens)) {
413
					$input_errors[] = gettext("Please select a valid Key Length.");
414
				}
415
				if (isset($_POST["csr_ecname"]) && !in_array($_POST["csr_ecname"], array_keys($openssl_ecnames))) {
416
					$input_errors[] = gettext("Please select a valid Elliptic Curve Name.");
417
				}
418
				if (!in_array($_POST["csr_digest_alg"], $openssl_digest_algs)) {
419
					$input_errors[] = gettext("Please select a valid Digest Algorithm.");
420
				}
421
				break;
422
			case "sign":
423
				if (!in_array($_POST["csrsign_digest_alg"], $openssl_digest_algs)) {
424
					$input_errors[] = gettext("Please select a valid Digest Algorithm.");
425
				}
426
				break;
427
			default:
428
				break;
429
		}
430
	}
431

    
432
	/* save modifications */
433
	if (!$input_errors) {
434
		$old_err_level = error_reporting(0); /* otherwise openssl_ functions throw warnings directly to a page breaking menu tabs */
435

    
436
		if (isset($id) && $thiscert) {
437
			$cert = $thiscert;
438
		} else {
439
			$cert = array();
440
			$cert['refid'] = uniqid();
441
		}
442

    
443
		$cert['descr'] = $pconfig['descr'];
444

    
445
		switch($pconfig['method']) {
446
			case 'existing':
447
				/* Add an existing certificate to a user */
448
				$ucert = lookup_cert($pconfig['certref']);
449
				if ($ucert && $a_user) {
450
					$a_user[$userid]['cert'][] = $ucert['refid'];
451
					$savemsg = sprintf(gettext("Added certificate %s to user %s"), $ucert['descr'], $a_user[$userid]['name']);
452
				}
453
				unset($cert);
454
				break;
455
			case 'sign':
456
				/* Sign a CSR */
457
				$csrid = lookup_cert($pconfig['csrtosign']);
458
				$ca = & lookup_ca($pconfig['catosignwith']);
459
				// Read the CSR from $config, or if a new one, from the textarea
460
				if ($pconfig['csrtosign'] === "new") {
461
					$csr = $pconfig['csrpaste'];
462
				} else {
463
					$csr = base64_decode($csrid['csr']);
464
				}
465
				if (count($altnames)) {
466
					foreach ($altnames as $altname) {
467
						$altnames_tmp[] = "{$altname['type']}:" . $altname['value'];
468
					}
469
					$altname_str = implode(",", $altnames_tmp);
470
				}
471
				$n509 = csr_sign($csr, $ca, $pconfig['csrsign_lifetime'], $pconfig['type'], $altname_str, $pconfig['csrsign_digest_alg']);
472
				if ($n509) {
473
					// Gather the details required to save the new cert
474
					$newcert = array();
475
					$newcert['refid'] = uniqid();
476
					$newcert['caref'] = $pconfig['catosignwith'];
477
					$newcert['descr'] = $pconfig['descr'];
478
					$newcert['type'] = $pconfig['type'];
479
					$newcert['crt'] = base64_encode($n509);
480
					if ($pconfig['csrtosign'] === "new") {
481
						$newcert['prv'] = base64_encode($pconfig['keypaste']);
482
					} else {
483
						$newcert['prv'] = $csrid['prv'];
484
					}
485
					// Add it to the config file
486
					$config['cert'][] = $newcert;
487
					$savemsg = sprintf(gettext("Signed certificate %s"), $newcert['descr']);
488
				}
489
				unset($cert);
490
				break;
491
			case 'edit':
492
				cert_import($cert, $pconfig['cert'], $pconfig['key']);
493
				$savemsg = sprintf(gettext("Edited certificate %s"), $cert['descr']);
494
				break;
495
			case 'import':
496
				/* Import an external certificate+key */
497
				if ($pkcs12_data) {
498
					$pconfig['cert'] = $pkcs12_data['cert'];
499
					$pconfig['key'] = $pkcs12_data['pkey'];
500
					if ($_POST['pkcs12_intermediate'] && is_array($pkcs12_data['extracerts'])) {
501
						foreach ($pkcs12_data['extracerts'] as $intermediate) {
502
							$int_data = openssl_x509_parse($intermediate);
503
							if (!$int_data) continue;
504
							$cn = $int_data['subject']['CN'];
505
							$int_ca = array('descr' => $cn, 'refid' => uniqid());
506
							if (ca_import($int_ca, $intermediate)) {
507
								$a_ca[] = $int_ca;
508
							}
509
						}
510
					}
511
				}
512
				cert_import($cert, $pconfig['cert'], $pconfig['key']);
513
				$savemsg = sprintf(gettext("Imported certificate %s"), $cert['descr']);
514
				break;
515
			case 'internal':
516
				/* Create an internal certificate */
517
				$dn = array('commonName' => $pconfig['dn_commonname']);
518
				if (!empty($pconfig['dn_country'])) {
519
					$dn['countryName'] = $pconfig['dn_country'];
520
				}
521
				if (!empty($pconfig['dn_state'])) {
522
					$dn['stateOrProvinceName'] = $pconfig['dn_state'];
523
				}
524
				if (!empty($pconfig['dn_city'])) {
525
					$dn['localityName'] = $pconfig['dn_city'];
526
				}
527
				if (!empty($pconfig['dn_organization'])) {
528
					$dn['organizationName'] = $pconfig['dn_organization'];
529
				}
530
				if (!empty($pconfig['dn_organizationalunit'])) {
531
					$dn['organizationalUnitName'] = $pconfig['dn_organizationalunit'];
532
				}
533
				$altnames_tmp = array();
534
				$cn_altname = cert_add_altname_type($pconfig['dn_commonname']);
535
				if (!empty($cn_altname)) {
536
					$altnames_tmp[] = $cn_altname;
537
				}
538
				if (count($altnames)) {
539
					foreach ($altnames as $altname) {
540
						// The CN is added as a SAN automatically, do not add it again.
541
						if ($altname['value'] != $pconfig['dn_commonname']) {
542
							$altnames_tmp[] = "{$altname['type']}:" . $altname['value'];
543
						}
544
					}
545
				}
546
				if (!empty($altnames_tmp)) {
547
					$dn['subjectAltName'] = implode(",", $altnames_tmp);
548
				}
549
				if (!cert_create($cert, $pconfig['caref'], $pconfig['keylen'], $pconfig['lifetime'], $dn, $pconfig['type'], $pconfig['digest_alg'], $pconfig['keytype'], $pconfig['ecname'])) {
550
					$input_errors = array();
551
					while ($ssl_err = openssl_error_string()) {
552
						if (strpos($ssl_err, 'NCONF_get_string:no value') === false) {
553
							$input_errors[] = sprintf(gettext("OpenSSL Library Error: %s"), $ssl_err);
554
						}
555
					}
556
				}
557
				$savemsg = sprintf(gettext("Created internal certificate %s"), $cert['descr']);
558
				break;
559
			case 'external':
560
				/* Create a certificate signing request */
561
				$dn = array('commonName' => $pconfig['csr_dn_commonname']);
562
				if (!empty($pconfig['csr_dn_country'])) {
563
					$dn['countryName'] = $pconfig['csr_dn_country'];
564
				}
565
				if (!empty($pconfig['csr_dn_state'])) {
566
					$dn['stateOrProvinceName'] = $pconfig['csr_dn_state'];
567
				}
568
				if (!empty($pconfig['csr_dn_city'])) {
569
					$dn['localityName'] = $pconfig['csr_dn_city'];
570
				}
571
				if (!empty($pconfig['csr_dn_organization'])) {
572
					$dn['organizationName'] = $pconfig['csr_dn_organization'];
573
				}
574
				if (!empty($pconfig['csr_dn_organizationalunit'])) {
575
					$dn['organizationalUnitName'] = $pconfig['csr_dn_organizationalunit'];
576
				}
577
				$altnames_tmp = array();
578
				$cn_altname = cert_add_altname_type($pconfig['csr_dn_commonname']);
579
				if (!empty($cn_altname)) {
580
					$altnames_tmp[] = $cn_altname;
581
				}
582
				if (count($altnames)) {
583
					foreach ($altnames as $altname) {
584
						// The CN is added as a SAN automatically, do not add it again.
585
						if ($altname['value'] != $pconfig['csr_dn_commonname']) {
586
							$altnames_tmp[] = "{$altname['type']}:" . $altname['value'];
587
						}
588
					}
589
				}
590
				if (!empty($altnames_tmp)) {
591
					$dn['subjectAltName'] = implode(",", $altnames_tmp);
592
				}
593
				if (!csr_generate($cert, $pconfig['csr_keylen'], $dn, $pconfig['type'], $pconfig['csr_digest_alg'], $pconfig['csr_keytype'], $pconfig['csr_ecname'])) {
594
					$input_errors = array();
595
					while ($ssl_err = openssl_error_string()) {
596
						if (strpos($ssl_err, 'NCONF_get_string:no value') === false) {
597
							$input_errors[] = sprintf(gettext("OpenSSL Library Error: %s"), $ssl_err);
598
						}
599
					}
600
				}
601
				$savemsg = sprintf(gettext("Created certificate signing request %s"), $cert['descr']);
602
				break;
603
			default:
604
				break;
605
		}
606
		error_reporting($old_err_level);
607

    
608
		if (isset($id) && $thiscert) {
609
			$thiscert = $cert;
610
		} elseif ($cert) {
611
			$a_cert[] = $cert;
612
		}
613

    
614
		if (isset($a_user) && isset($userid)) {
615
			$a_user[$userid]['cert'][] = $cert['refid'];
616
		}
617

    
618
		if (!$input_errors) {
619
			write_config($savemsg);
620
		}
621

    
622
		if ((isset($userid) && is_numeric($userid)) && !$input_errors) {
623
			post_redirect("system_usermanager.php", array('act' => 'edit', 'userid' => $userid));
624
			exit;
625
		}
626
	}
627
} elseif ($_POST['save'] == gettext("Update")) {
628
	/* Updating a certificate signing request */
629
	unset($input_errors);
630
	$pconfig = $_POST;
631

    
632
	/* input validation */
633
	$reqdfields = explode(" ", "descr cert");
634
	$reqdfieldsn = array(
635
		gettext("Descriptive name"),
636
		gettext("Final Certificate data"));
637

    
638
	do_input_validation($_POST, $reqdfields, $reqdfieldsn, $input_errors);
639

    
640
	if (preg_match("/[\?\>\<\&\/\\\"\']/", $_POST['descr'])) {
641
		$input_errors[] = gettext("The field 'Descriptive Name' contains invalid characters.");
642
	}
643

    
644
	$mod_csr = cert_get_publickey($pconfig['csr'], false, 'csr');
645
	$mod_cert = cert_get_publickey($pconfig['cert'], false);
646

    
647
	if (strcmp($mod_csr, $mod_cert)) {
648
		// simply: if the moduli don't match, then the private key and public key won't match
649
		$input_errors[] = gettext("The certificate public key does not match the signing request public key.");
650
		$subject_mismatch = true;
651
	}
652

    
653
	/* save modifications */
654
	if (!$input_errors) {
655
		$cert = $thiscert;
656
		$cert['descr'] = $pconfig['descr'];
657
		csr_complete($cert, $pconfig['cert']);
658
		$thiscert = $cert;
659
		$savemsg = sprintf(gettext("Updated certificate signing request %s"), $pconfig['descr']);
660
		write_config($savemsg);
661
		pfSenseHeader("system_certmanager.php");
662
	}
663
}
664

    
665
$pgtitle = array(gettext("System"), gettext("Certificate Manager"), gettext("Certificates"));
666
$pglinks = array("", "system_camanager.php", "system_certmanager.php");
667

    
668
if (($act == "new" || ($_POST['save'] == gettext("Save") && $input_errors)) ||
669
    ($act == "csr" || ($_POST['save'] == gettext("Update") && $input_errors))) {
670
	$pgtitle[] = gettext('Edit');
671
	$pglinks[] = "@self";
672
}
673
include("head.inc");
674

    
675
if ($input_errors) {
676
	print_input_errors($input_errors);
677
}
678

    
679
if ($savemsg) {
680
	print_info_box($savemsg, $class);
681
}
682

    
683
$tab_array = array();
684
$tab_array[] = array(gettext("CAs"), false, "system_camanager.php");
685
$tab_array[] = array(gettext("Certificates"), true, "system_certmanager.php");
686
$tab_array[] = array(gettext("Certificate Revocation"), false, "system_crlmanager.php");
687
display_top_tabs($tab_array);
688

    
689
if (in_array($act, array('new', 'edit')) || (($_POST['save'] == gettext("Save")) && $input_errors)) {
690
	$form = new Form();
691
	$form->setAction('system_certmanager.php')->setMultipartEncoding();
692

    
693
	if (isset($userid) && $a_user) {
694
		$form->addGlobal(new Form_Input(
695
			'userid',
696
			null,
697
			'hidden',
698
			$userid
699
		));
700
	}
701

    
702
	if (isset($id) && $thiscert) {
703
		$form->addGlobal(new Form_Input(
704
			'id',
705
			null,
706
			'hidden',
707
			$id
708
		));
709
	}
710

    
711
	switch ($act) {
712
		case 'edit':
713
			$maintitle = gettext('Edit an Existing Certificate');
714
			break;
715
		case 'new':
716
		default:
717
			$maintitle = gettext('Add/Sign a New Certificate');
718
			break;
719
	}
720

    
721
	$section = new Form_Section($maintitle);
722

    
723
	if (!isset($id) || ($act == 'edit')) {
724
		$section->addInput(new Form_Select(
725
			'method',
726
			'*Method',
727
			$pconfig['method'],
728
			$cert_methods
729
		))->toggles();
730
	}
731

    
732
	$section->addInput(new Form_Input(
733
		'descr',
734
		'*Descriptive name',
735
		'text',
736
		($a_user && empty($pconfig['descr'])) ? $a_user[$userid]['name'] : $pconfig['descr']
737
	))->addClass('toggle-internal toggle-import toggle-edit toggle-external toggle-sign toggle-existing collapse');
738

    
739
	if (!empty($pconfig['cert'])) {
740
		$section->addInput(new Form_StaticText(
741
			"Subject",
742
			htmlspecialchars(cert_get_subject($pconfig['cert'], false))
743
		))->addClass('toggle-edit collapse');
744
	}
745

    
746
	$form->add($section);
747

    
748
	$section = new Form_Section('Sign CSR');
749
	$section->addClass('toggle-sign collapse');
750

    
751
	$section->AddInput(new Form_Select(
752
		'catosignwith',
753
		'*CA to sign with',
754
		$pconfig['catosignwith'],
755
		list_cas()
756
	));
757

    
758
	$section->AddInput(new Form_Select(
759
		'csrtosign',
760
		'*CSR to sign',
761
		isset($pconfig['csrtosign']) ? $pconfig['csrtosign'] : 'new',
762
		list_csrs()
763
	));
764

    
765
	$section->addInput(new Form_Textarea(
766
		'csrpaste',
767
		'CSR data',
768
		$pconfig['csrpaste']
769
	))->setHelp('Paste a Certificate Signing Request in X.509 PEM format here.');
770

    
771
	$section->addInput(new Form_Textarea(
772
		'keypaste',
773
		'Key data',
774
		$pconfig['keypaste']
775
	))->setHelp('Optionally paste a private key here. The key will be associated with the newly signed certificate in %1$s', $g['product_label']);
776

    
777
	$section->addInput(new Form_Input(
778
		'csrsign_lifetime',
779
		'*Certificate Lifetime (days)',
780
		'number',
781
		$pconfig['csrsign_lifetime'] ? $pconfig['csrsign_lifetime']:$default_lifetime,
782
		['max' => $max_lifetime]
783
	))->setHelp('The length of time the signed certificate will be valid, in days. %1$s' .
784
		'Server certificates should not have a lifetime over %2$s days or some platforms ' .
785
		'may consider the certificate invalid.', '<br/>', $cert_strict_values['max_server_cert_lifetime']);
786
	$section->addInput(new Form_Select(
787
		'csrsign_digest_alg',
788
		'*Digest Algorithm',
789
		$pconfig['csrsign_digest_alg'],
790
		array_combine($openssl_digest_algs, $openssl_digest_algs)
791
	))->setHelp('The digest method used when the certificate is signed. %1$s' .
792
		'The best practice is to use an algorithm stronger than SHA1. '.
793
		'Some platforms may consider weaker digest algorithms invalid', '<br/>');
794

    
795
	$form->add($section);
796

    
797
	if ($act == 'edit') {
798
		$editimport = gettext("Edit Certificate");
799
	} else {
800
		$editimport = gettext("Import Certificate");
801
	}
802

    
803
	$section = new Form_Section($editimport);
804
	$section->addClass('toggle-import toggle-edit collapse');
805

    
806
	$group = new Form_Group('Certificate Type');
807

    
808
	$group->add(new Form_Checkbox(
809
		'import_type',
810
		'Certificate Type',
811
		'X.509 (PEM)',
812
		(!isset($pconfig['import_type']) || $pconfig['import_type'] == 'x509'),
813
		'x509'
814
	))->displayAsRadio()->addClass('import_type_toggle');
815

    
816
	$group->add(new Form_Checkbox(
817
		'import_type',
818
		'Certificate Type',
819
		'PKCS #12 (PFX)',
820
		(isset($pconfig['import_type']) && $pconfig['import_type'] == 'pkcs12'),
821
		'pkcs12'
822
	))->displayAsRadio()->addClass('import_type_toggle');
823

    
824
	$section->add($group);
825

    
826
	$section->addInput(new Form_Textarea(
827
		'cert',
828
		'*Certificate data',
829
		$pconfig['cert']
830
	))->setHelp('Paste a certificate in X.509 PEM format here.');
831

    
832
	$section->addInput(new Form_Textarea(
833
		'key',
834
		'Private key data',
835
		$pconfig['key']
836
	))->setHelp('Paste a private key in X.509 PEM format here. This field may remain empty in certain cases, such as when the private key is stored on a PKCS#11 token.');
837

    
838
	$section->addInput(new Form_Input(
839
		'pkcs12_cert',
840
		'PKCS #12 certificate',
841
		'file',
842
		$pconfig['pkcs12_cert']
843
	))->setHelp('Select a PKCS #12 certificate store.');
844

    
845
	$section->addInput(new Form_Input(
846
		'pkcs12_pass',
847
		'PKCS #12 certificate password',
848
		'password',
849
		$pconfig['pkcs12_pass']
850
	))->setHelp('Enter the password to unlock the PKCS #12 certificate store.');
851

    
852
	$section->addInput(new Form_Checkbox(
853
		'pkcs12_intermediate',
854
		'Intermediates',
855
		'Import intermediate CAs',
856
		isset($pconfig['pkcs12_intermediate'])
857
	))->setHelp('Import any intermediate certificate authorities found in the PKCS #12 certificate store.');
858

    
859
	if ($act == 'edit') {
860
		$section->addInput(new Form_Input(
861
			'exportpass',
862
			'Export Password',
863
			'password',
864
			null,
865
			['placeholder' => gettext('Export Password'), 'autocomplete' => 'new-password']
866
		))->setHelp('Enter the password to use when using the export buttons below (not stored)')->addClass('toggle-edit collapse');
867
	}
868

    
869
	$form->add($section);
870
	$section = new Form_Section('Internal Certificate');
871
	$section->addClass('toggle-internal collapse');
872

    
873
	if (!$internal_ca_count) {
874
		$section->addInput(new Form_StaticText(
875
			'*Certificate authority',
876
			gettext('No internal Certificate Authorities have been defined. ') .
877
			gettext('An internal CA must be defined in order to create an internal certificate. ') .
878
			sprintf(gettext('%1$sCreate%2$s an internal CA.'), '<a href="system_camanager.php?act=new&amp;method=internal"> ', '</a>')
879
		));
880
	} else {
881
		$allCas = array();
882
		foreach ($a_ca as $ca) {
883
			if (!$ca['prv']) {
884
				continue;
885
			}
886

    
887
			$allCas[ $ca['refid'] ] = $ca['descr'];
888
		}
889

    
890
		$section->addInput(new Form_Select(
891
			'caref',
892
			'*Certificate authority',
893
			$pconfig['caref'],
894
			$allCas
895
		));
896
	}
897

    
898
	$section->addInput(new Form_Select(
899
		'keytype',
900
		'*Key type',
901
		$pconfig['keytype'],
902
		array_combine($cert_keytypes, $cert_keytypes)
903
	));
904

    
905
	$group = new Form_Group($i == 0 ? '*Key length':'');
906
	$group->addClass('rsakeys');
907
	$group->add(new Form_Select(
908
		'keylen',
909
		null,
910
		$pconfig['keylen'],
911
		array_combine($cert_keylens, $cert_keylens)
912
	))->setHelp('The length to use when generating a new RSA key, in bits. %1$s' .
913
		'The Key Length should not be lower than 2048 or some platforms ' .
914
		'may consider the certificate invalid.', '<br/>');
915
	$section->add($group);
916

    
917
	$group = new Form_Group($i == 0 ? '*Elliptic Curve Name':'');
918
	$group->addClass('ecnames');
919
	$group->add(new Form_Select(
920
		'ecname',
921
		null,
922
		$pconfig['ecname'],
923
		$openssl_ecnames
924
	))->setHelp('Curves may not be compatible with all uses. Known compatible curve uses are denoted in brackets.');
925
	$section->add($group);
926

    
927
	$section->addInput(new Form_Select(
928
		'digest_alg',
929
		'*Digest Algorithm',
930
		$pconfig['digest_alg'],
931
		array_combine($openssl_digest_algs, $openssl_digest_algs)
932
	))->setHelp('The digest method used when the certificate is signed. %1$s' .
933
		'The best practice is to use an algorithm stronger than SHA1. '.
934
		'Some platforms may consider weaker digest algorithms invalid', '<br/>');
935

    
936
	$section->addInput(new Form_Input(
937
		'lifetime',
938
		'*Lifetime (days)',
939
		'number',
940
		$pconfig['lifetime'],
941
		['max' => $max_lifetime]
942
	))->setHelp('The length of time the signed certificate will be valid, in days. %1$s' .
943
		'Server certificates should not have a lifetime over %2$s days or some platforms ' .
944
		'may consider the certificate invalid.', '<br/>', $cert_strict_values['max_server_cert_lifetime']);
945

    
946
	$section->addInput(new Form_Input(
947
		'dn_commonname',
948
		'*Common Name',
949
		'text',
950
		$pconfig['dn_commonname'],
951
		['placeholder' => 'e.g. www.example.com']
952
	));
953

    
954
	$section->addInput(new Form_StaticText(
955
		null,
956
		gettext('The following certificate subject components are optional and may be left blank.')
957
	));
958

    
959
	$section->addInput(new Form_Select(
960
		'dn_country',
961
		'Country Code',
962
		$pconfig['dn_country'],
963
		get_cert_country_codes()
964
	));
965

    
966
	$section->addInput(new Form_Input(
967
		'dn_state',
968
		'State or Province',
969
		'text',
970
		$pconfig['dn_state'],
971
		['placeholder' => 'e.g. Texas']
972
	));
973

    
974
	$section->addInput(new Form_Input(
975
		'dn_city',
976
		'City',
977
		'text',
978
		$pconfig['dn_city'],
979
		['placeholder' => 'e.g. Austin']
980
	));
981

    
982
	$section->addInput(new Form_Input(
983
		'dn_organization',
984
		'Organization',
985
		'text',
986
		$pconfig['dn_organization'],
987
		['placeholder' => 'e.g. My Company Inc']
988
	));
989

    
990
	$section->addInput(new Form_Input(
991
		'dn_organizationalunit',
992
		'Organizational Unit',
993
		'text',
994
		$pconfig['dn_organizationalunit'],
995
		['placeholder' => 'e.g. My Department Name (optional)']
996
	));
997

    
998
	$form->add($section);
999
	$section = new Form_Section('External Signing Request');
1000
	$section->addClass('toggle-external collapse');
1001

    
1002
	$section->addInput(new Form_Select(
1003
		'csr_keytype',
1004
		'*Key type',
1005
		$pconfig['csr_keytype'],
1006
		array_combine($cert_keytypes, $cert_keytypes)
1007
	));
1008

    
1009
	$group = new Form_Group($i == 0 ? '*Key length':'');
1010
	$group->addClass('csr_rsakeys');
1011
	$group->add(new Form_Select(
1012
		'csr_keylen',
1013
		null,
1014
		$pconfig['csr_keylen'],
1015
		array_combine($cert_keylens, $cert_keylens)
1016
	))->setHelp('The length to use when generating a new RSA key, in bits. %1$s' .
1017
		'The Key Length should not be lower than 2048 or some platforms ' .
1018
		'may consider the certificate invalid.', '<br/>');
1019
	$section->add($group);
1020

    
1021
	$group = new Form_Group($i == 0 ? '*Elliptic Curve Name':'');
1022
	$group->addClass('csr_ecnames');
1023
	$group->add(new Form_Select(
1024
		'csr_ecname',
1025
		null,
1026
		$pconfig['csr_ecname'],
1027
		$openssl_ecnames
1028
	));
1029
	$section->add($group);
1030

    
1031
	$section->addInput(new Form_Select(
1032
		'csr_digest_alg',
1033
		'*Digest Algorithm',
1034
		$pconfig['csr_digest_alg'],
1035
		array_combine($openssl_digest_algs, $openssl_digest_algs)
1036
	))->setHelp('The digest method used when the certificate is signed. %1$s' .
1037
		'The best practice is to use an algorithm stronger than SHA1. '.
1038
		'Some platforms may consider weaker digest algorithms invalid', '<br/>');
1039

    
1040
	$section->addInput(new Form_Input(
1041
		'csr_dn_commonname',
1042
		'*Common Name',
1043
		'text',
1044
		$pconfig['csr_dn_commonname'],
1045
		['placeholder' => 'e.g. internal-ca']
1046
	));
1047

    
1048
	$section->addInput(new Form_StaticText(
1049
		null,
1050
		gettext('The following certificate subject components are optional and may be left blank.')
1051
	));
1052

    
1053
	$section->addInput(new Form_Select(
1054
		'csr_dn_country',
1055
		'Country Code',
1056
		$pconfig['csr_dn_country'],
1057
		get_cert_country_codes()
1058
	));
1059

    
1060
	$section->addInput(new Form_Input(
1061
		'csr_dn_state',
1062
		'State or Province',
1063
		'text',
1064
		$pconfig['csr_dn_state'],
1065
		['placeholder' => 'e.g. Texas']
1066
	));
1067

    
1068
	$section->addInput(new Form_Input(
1069
		'csr_dn_city',
1070
		'City',
1071
		'text',
1072
		$pconfig['csr_dn_city'],
1073
		['placeholder' => 'e.g. Austin']
1074
	));
1075

    
1076
	$section->addInput(new Form_Input(
1077
		'csr_dn_organization',
1078
		'Organization',
1079
		'text',
1080
		$pconfig['csr_dn_organization'],
1081
		['placeholder' => 'e.g. My Company Inc']
1082
	));
1083

    
1084
	$section->addInput(new Form_Input(
1085
		'csr_dn_organizationalunit',
1086
		'Organizational Unit',
1087
		'text',
1088
		$pconfig['csr_dn_organizationalunit'],
1089
		['placeholder' => 'e.g. My Department Name (optional)']
1090
	));
1091

    
1092
	$form->add($section);
1093
	$section = new Form_Section('Choose an Existing Certificate');
1094
	$section->addClass('toggle-existing collapse');
1095

    
1096
	$existCerts = array();
1097

    
1098
	foreach ($config['cert'] as $cert) {
1099
		if (!is_array($cert) || empty($cert)) {
1100
			continue;
1101
		}
1102
		if (is_array($config['system']['user'][$userid]['cert'])) { // Could be MIA!
1103
			if (isset($userid) && in_array($cert['refid'], $config['system']['user'][$userid]['cert'])) {
1104
				continue;
1105
			}
1106
		}
1107

    
1108
		$ca = lookup_ca($cert['caref']);
1109
		if ($ca) {
1110
			$cert['descr'] .= " (CA: {$ca['descr']})";
1111
		}
1112

    
1113
		if (cert_in_use($cert['refid'])) {
1114
			$cert['descr'] .= " (In Use)";
1115
		}
1116
		if (is_cert_revoked($cert)) {
1117
			$cert['descr'] .= " (Revoked)";
1118
		}
1119

    
1120
		$existCerts[ $cert['refid'] ] = $cert['descr'];
1121
	}
1122

    
1123
	$section->addInput(new Form_Select(
1124
		'certref',
1125
		'*Existing Certificates',
1126
		$pconfig['certref'],
1127
		$existCerts
1128
	));
1129

    
1130
	$form->add($section);
1131

    
1132
	$section = new Form_Section('Certificate Attributes');
1133
	$section->addClass('toggle-external toggle-internal toggle-sign collapse');
1134

    
1135
	$section->addInput(new Form_StaticText(
1136
		gettext('Attribute Notes'),
1137
		'<span class="help-block">'.
1138
		gettext('The following attributes are added to certificates and ' .
1139
		'requests when they are created or signed. These attributes behave ' .
1140
		'differently depending on the selected mode.') .
1141
		'<br/><br/>' .
1142
		'<span class="toggle-internal collapse">' . gettext('For Internal Certificates, these attributes are added directly to the certificate as shown.') . '</span>' .
1143
		'<span class="toggle-external collapse">' .
1144
		gettext('For Certificate Signing Requests, These attributes are added to the request but they may be ignored or changed by the CA that signs the request. ') .
1145
		'<br/><br/>' .
1146
		gettext('If this CSR will be signed using the Certificate Manager on this firewall, set the attributes when signing instead as they cannot be carried over.') . '</span>' .
1147
		'<span class="toggle-sign collapse">' . gettext('When Signing a Certificate Request, existing attributes in the request cannot be copied. The attributes below will be applied to the resulting certificate.') . '</span>' .
1148
		'</span>'
1149
	));
1150

    
1151
	$section->addInput(new Form_Select(
1152
		'type',
1153
		'*Certificate Type',
1154
		$pconfig['type'],
1155
		$cert_types
1156
	))->setHelp('Add type-specific usage attributes to the signed certificate.' .
1157
		' Used for placing usage restrictions on, or granting abilities to, ' .
1158
		'the signed certificate.');
1159

    
1160
	if (empty($pconfig['altnames']['item'])) {
1161
		$pconfig['altnames']['item'] = array(
1162
			array('type' => null, 'value' => null)
1163
		);
1164
	}
1165

    
1166
	$counter = 0;
1167
	$numrows = count($pconfig['altnames']['item']) - 1;
1168

    
1169
	foreach ($pconfig['altnames']['item'] as $item) {
1170

    
1171
		$group = new Form_Group($counter == 0 ? 'Alternative Names':'');
1172

    
1173
		$group->add(new Form_Select(
1174
			'altname_type' . $counter,
1175
			'Type',
1176
			$item['type'],
1177
			$cert_altname_types
1178
		))->setHelp(($counter == $numrows) ? 'Type':null);
1179

    
1180
		$group->add(new Form_Input(
1181
			'altname_value' . $counter,
1182
			null,
1183
			'text',
1184
			$item['value']
1185
		))->setHelp(($counter == $numrows) ? 'Value':null);
1186

    
1187
		$group->add(new Form_Button(
1188
			'deleterow' . $counter,
1189
			'Delete',
1190
			null,
1191
			'fa-trash'
1192
		))->addClass('btn-warning');
1193

    
1194
		$group->addClass('repeatable');
1195

    
1196
		$group->setHelp('Enter additional identifiers for the certificate ' .
1197
			'in this list. The Common Name field is automatically ' .
1198
			'added to the certificate as an Alternative Name. ' .
1199
			'The signing CA may ignore or change these values.');
1200

    
1201
		$section->add($group);
1202

    
1203
		$counter++;
1204
	}
1205

    
1206
	$section->addInput(new Form_Button(
1207
		'addrow',
1208
		'Add',
1209
		null,
1210
		'fa-plus'
1211
	))->addClass('btn-success');
1212

    
1213
	$form->add($section);
1214

    
1215
	if (($act == 'edit') && !empty($pconfig['key'])) {
1216
		$form->addGlobal(new Form_Button(
1217
			'exportpkey',
1218
			'Export Private Key',
1219
			null,
1220
			'fa-key'
1221
		))->addClass('btn-primary');
1222
		$form->addGlobal(new Form_Button(
1223
			'exportp12',
1224
			'Export PKCS#12',
1225
			null,
1226
			'fa-archive'
1227
		))->addClass('btn-primary');
1228
	}
1229

    
1230
	print $form;
1231

    
1232
} elseif ($act == "csr" || (($_POST['save'] == gettext("Update")) && $input_errors)) {
1233
	$form = new Form(false);
1234
	$form->setAction('system_certmanager.php?act=csr');
1235

    
1236
	$section = new Form_Section("Complete Signing Request for " . $pconfig['descr']);
1237

    
1238
	$section->addInput(new Form_Input(
1239
		'descr',
1240
		'*Descriptive name',
1241
		'text',
1242
		$pconfig['descr']
1243
	));
1244

    
1245
	$section->addInput(new Form_Textarea(
1246
		'csr',
1247
		'Signing request data',
1248
		$pconfig['csr']
1249
	))->setReadonly()
1250
	  ->setWidth(7)
1251
	  ->setHelp('Copy the certificate signing data from here and forward it to a certificate authority for signing.');
1252

    
1253
	$section->addInput(new Form_Textarea(
1254
		'cert',
1255
		'*Final certificate data',
1256
		$pconfig['cert']
1257
	))->setWidth(7)
1258
	  ->setHelp('Paste the certificate received from the certificate authority here.');
1259

    
1260
	if (isset($id) && $thiscert) {
1261
		$form->addGlobal(new Form_Input(
1262
			'id',
1263
			null,
1264
			'hidden',
1265
			$id
1266
		));
1267

    
1268
		$form->addGlobal(new Form_Input(
1269
			'act',
1270
			null,
1271
			'hidden',
1272
			'csr'
1273
		));
1274
	}
1275

    
1276
	$form->add($section);
1277

    
1278
	$form->addGlobal(new Form_Button(
1279
		'save',
1280
		'Update',
1281
		null,
1282
		'fa-save'
1283
	))->addClass('btn-primary');
1284

    
1285
	print($form);
1286
} else {
1287
?>
1288
<div class="panel panel-default" id="search-panel">
1289
	<div class="panel-heading">
1290
		<h2 class="panel-title">
1291
			<?=gettext('Search')?>
1292
			<span class="widget-heading-icon pull-right">
1293
				<a data-toggle="collapse" href="#search-panel_panel-body">
1294
					<i class="fa fa-plus-circle"></i>
1295
				</a>
1296
			</span>
1297
		</h2>
1298
	</div>
1299
	<div id="search-panel_panel-body" class="panel-body collapse in">
1300
		<div class="form-group">
1301
			<label class="col-sm-2 control-label">
1302
				<?=gettext("Search term")?>
1303
			</label>
1304
			<div class="col-sm-5"><input class="form-control" name="searchstr" id="searchstr" type="text"/></div>
1305
			<div class="col-sm-2">
1306
				<select id="where" class="form-control">
1307
					<option value="0"><?=gettext("Name")?></option>
1308
					<option value="1"><?=gettext("Distinguished Name")?></option>
1309
					<option value="2" selected><?=gettext("Both")?></option>
1310
				</select>
1311
			</div>
1312
			<div class="col-sm-3">
1313
				<a id="btnsearch" title="<?=gettext("Search")?>" class="btn btn-primary btn-sm"><i class="fa fa-search icon-embed-btn"></i><?=gettext("Search")?></a>
1314
				<a id="btnclear" title="<?=gettext("Clear")?>" class="btn btn-info btn-sm"><i class="fa fa-undo icon-embed-btn"></i><?=gettext("Clear")?></a>
1315
			</div>
1316
			<div class="col-sm-10 col-sm-offset-2">
1317
				<span class="help-block"><?=gettext('Enter a search string or *nix regular expression to search certificate names and distinguished names.')?></span>
1318
			</div>
1319
		</div>
1320
	</div>
1321
</div>
1322
<div class="panel panel-default">
1323
	<div class="panel-heading"><h2 class="panel-title"><?=gettext('Certificates')?></h2></div>
1324
	<div class="panel-body">
1325
		<div class="table-responsive">
1326
		<table class="table table-striped table-hover sortable-theme-bootstrap" data-sortable>
1327
			<thead>
1328
				<tr>
1329
					<th><?=gettext("Name")?></th>
1330
					<th><?=gettext("Issuer")?></th>
1331
					<th><?=gettext("Distinguished Name")?></th>
1332
					<th><?=gettext("In Use")?></th>
1333

    
1334
					<th class="col-sm-2"><?=gettext("Actions")?></th>
1335
				</tr>
1336
			</thead>
1337
			<tbody>
1338
<?php
1339

    
1340
$pluginparams = array();
1341
$pluginparams['type'] = 'certificates';
1342
$pluginparams['event'] = 'used_certificates';
1343
$certificates_used_by_packages = pkg_call_plugins('plugin_certificates', $pluginparams);
1344

    
1345
// Gather the data required to display a certificate table. The array returned includes:
1346
// ['name']
1347
// ['subj']
1348
// ['issuer']
1349
// ['info'] (infoblock contents)
1350
// ['dates']
1351
// ['refid']
1352
// ['csr']
1353
// ['prv']
1354
// ['inuse']
1355
$certs = getCertData();
1356

    
1357
foreach ($certs as $cert):
1358
?>
1359
				<tr>
1360
					<td> <?=$cert['name']; ?> </td>
1361
					<td> <?=$cert['issuer']; ?> </td>
1362
					<td> <?=$cert['subj']; ?> 
1363
						<?php
1364
						if (!empty($cert['info'])) {
1365
							print('<div class="infoblock">');
1366
							print_info_box($cert['info'], 'info', false);
1367
							print("</div>" . $cert['dates']);
1368
						}
1369
						?>
1370

    
1371
					</td>
1372

    
1373
					<td> <?=$cert['inuse']; ?> </td>
1374

    
1375
					<td>
1376
						<?php if (!$cert['csr']): ?>
1377
							<a href="system_certmanager.php?act=edit&amp;id=<?=$cert['refid']?>" class="fa fa-pencil" title="<?=gettext("Edit Certificate")?>"></a>
1378
							<a href="system_certmanager.php?act=exp&amp;id=<?=$cert['refid']?>" class="fa fa-certificate" title="<?=gettext("Export Certificate")?>"></a>
1379
							<?php if ($cert['prv']): ?>
1380
								<a href="system_certmanager.php?act=key&amp;id=<?=$cert['refid']?>" class="fa fa-key" title="<?=gettext("Export Key")?>"></a>
1381
								<a href="system_certmanager.php?act=p12&amp;id=<?=$cert['refid']?>" class="fa fa-archive" title="<?=gettext("Export P12")?>"></a>
1382
							<?php endif?>
1383
							<?php if (is_cert_locally_renewable($cert)): ?>
1384
								<a href="system_certmanager_renew.php?type=cert&amp;refid=<?=$cert['refid']?>" class="fa fa-repeat" title="<?=gettext("Reissue/Renew")?>"></a>
1385
							<?php endif ?>
1386
						<?php else: ?>
1387
							<a href="system_certmanager.php?act=csr&amp;id=<?=$cert['refid']?>" class="fa fa-pencil" title="<?=gettext("Update CSR")?>"></a>
1388
							<a href="system_certmanager.php?act=req&amp;id=<?=$cert['refid']?>" class="fa fa-sign-in" title="<?=gettext("Export Request")?>"></a>
1389
							<a href="system_certmanager.php?act=key&amp;id=<?=$cert['refid']?>" class="fa fa-key" title="<?=gettext("Export Key")?>"></a>
1390
						<?php endif?>
1391
						<?php if (!cert_in_use($cert['refid'])): ?>
1392
							<a href="system_certmanager.php?act=del&amp;id=<?=$cert['refid']?>" class="fa fa-trash" title="<?=gettext("Delete Certificate")?>" usepost></a>
1393
						<?php endif?>
1394
					</td>
1395
				</tr>
1396
<?php
1397
$idx++;
1398
	endforeach; ?>
1399
			</tbody>
1400
		</table>
1401
		</div>
1402
	</div>
1403
</div>
1404

    
1405
<nav class="action-buttons">
1406
	<a href="?act=new" class="btn btn-success btn-sm">
1407
		<i class="fa fa-plus icon-embed-btn"></i>
1408
		<?=gettext("Add/Sign")?>
1409
	</a>
1410
</nav>
1411
<script type="text/javascript">
1412
//<![CDATA[
1413

    
1414
events.push(function() {
1415

    
1416
	// Make these controls plain buttons
1417
	$("#btnsearch").prop('type', 'button');
1418
	$("#btnclear").prop('type', 'button');
1419

    
1420
	// Search for a term in the entry name and/or dn
1421
	$("#btnsearch").click(function() {
1422
		var searchstr = $('#searchstr').val().toLowerCase();
1423
		var table = $("table tbody");
1424
		var where = $('#where').val();
1425

    
1426
		table.find('tr').each(function (i) {
1427
			var $tds = $(this).find('td'),
1428
				shortname = $tds.eq(0).text().trim().toLowerCase(),
1429
				dn = $tds.eq(2).text().trim().toLowerCase();
1430

    
1431
			regexp = new RegExp(searchstr);
1432
			if (searchstr.length > 0) {
1433
				if (!(regexp.test(shortname) && (where != 1)) && !(regexp.test(dn) && (where != 0))) {
1434
					$(this).hide();
1435
				} else {
1436
					$(this).show();
1437
				}
1438
			} else {
1439
				$(this).show();	// A blank search string shows all
1440
			}
1441
		});
1442
	});
1443

    
1444
	// Clear the search term and unhide all rows (that were hidden during a previous search)
1445
	$("#btnclear").click(function() {
1446
		var table = $("table tbody");
1447

    
1448
		$('#searchstr').val("");
1449

    
1450
		table.find('tr').each(function (i) {
1451
			$(this).show();
1452
		});
1453
	});
1454

    
1455
	// Hitting the enter key will do the same as clicking the search button
1456
	$("#searchstr").on("keyup", function (event) {
1457
		if (event.keyCode == 13) {
1458
			$("#btnsearch").get(0).click();
1459
		}
1460
	});
1461
});
1462
//]]>
1463
</script>
1464

    
1465
<?php
1466
	include("foot.inc");
1467
	exit;
1468
}
1469

    
1470

    
1471
?>
1472
<script type="text/javascript">
1473
//<![CDATA[
1474
events.push(function() {
1475

    
1476
	$('.import_type_toggle').click(function() {
1477
		var x509 = (this.value === 'x509');
1478
		hideInput('cert', !x509);
1479
		setRequired('cert', x509);
1480
		hideInput('key', !x509);
1481
		setRequired('key', x509);
1482
		hideInput('pkcs12_cert', x509);
1483
		setRequired('pkcs12_cert', !x509);
1484
		hideInput('pkcs12_pass', x509);
1485
		hideCheckbox('pkcs12_intermediate', x509);
1486
	});
1487
	if ($('input[name=import_type]:checked').val() == 'x509') {
1488
		hideInput('pkcs12_cert', true);
1489
		setRequired('pkcs12_cert', false);
1490
		hideInput('pkcs12_pass', true);
1491
		hideCheckbox('pkcs12_intermediate', true);
1492
		hideInput('cert', false);
1493
		setRequired('cert', true);
1494
		hideInput('key', false);
1495
		setRequired('key', true);
1496
	} else if ($('input[name=import_type]:checked').val() == 'pkcs12') {
1497
		hideInput('cert', true);
1498
		setRequired('cert', false);
1499
		hideInput('key', true);
1500
		setRequired('key', false);
1501
		setRequired('pkcs12_cert', false);
1502
	}
1503

    
1504
<?php if ($internal_ca_count): ?>
1505
	function internalca_change() {
1506

    
1507
		caref = $('#caref').val();
1508

    
1509
		switch (caref) {
1510
<?php
1511
			foreach ($a_ca as $ca):
1512
				if (!$ca['prv']) {
1513
					continue;
1514
				}
1515

    
1516
				$subject = @cert_get_subject_hash($ca['crt']);
1517
				if (!is_array($subject) || empty($subject)) {
1518
					continue;
1519
				}
1520
?>
1521
				case "<?=$ca['refid'];?>":
1522
					$('#dn_country').val(<?=json_encode(cert_escape_x509_chars($subject['C'], true));?>);
1523
					$('#dn_state').val(<?=json_encode(cert_escape_x509_chars($subject['ST'], true));?>);
1524
					$('#dn_city').val(<?=json_encode(cert_escape_x509_chars($subject['L'], true));?>);
1525
					$('#dn_organization').val(<?=json_encode(cert_escape_x509_chars($subject['O'], true));?>);
1526
					$('#dn_organizationalunit').val(<?=json_encode(cert_escape_x509_chars($subject['OU'], true));?>);
1527
					break;
1528
<?php
1529
			endforeach;
1530
?>
1531
		}
1532
	}
1533

    
1534
	function set_csr_ro() {
1535
		var newcsr = ($('#csrtosign').val() == "new");
1536

    
1537
		$('#csrpaste').attr('readonly', !newcsr);
1538
		$('#keypaste').attr('readonly', !newcsr);
1539
		setRequired('csrpaste', newcsr);
1540
	}
1541

    
1542
	function check_lifetime() {
1543
		var maxserverlife = <?= $cert_strict_values['max_server_cert_lifetime'] ?>;
1544
		var ltid = '#lifetime';
1545
		if ($('#method').val() == "sign") {
1546
			ltid = '#csrsign_lifetime';
1547
		}
1548
		if (($('#type').val() == "server") && (parseInt($(ltid).val()) > maxserverlife)) {
1549
			$(ltid).parent().parent().removeClass("text-normal").addClass("text-warning");
1550
			$(ltid).removeClass("text-normal").addClass("text-warning");
1551
		} else {
1552
			$(ltid).parent().parent().removeClass("text-warning").addClass("text-normal");
1553
			$(ltid).removeClass("text-warning").addClass("text-normal");
1554
		}
1555
	}
1556
	function check_keylen() {
1557
		var min_keylen = <?= $cert_strict_values['min_private_key_bits'] ?>;
1558
		var klid = '#keylen';
1559
		if ($('#method').val() == "external") {
1560
			klid = '#csr_keylen';
1561
		}
1562
		/* Color the Parent/Label */
1563
		if (parseInt($(klid).val()) < min_keylen) {
1564
			$(klid).parent().parent().removeClass("text-normal").addClass("text-warning");
1565
		} else {
1566
			$(klid).parent().parent().removeClass("text-warning").addClass("text-normal");
1567
		}
1568
		/* Color individual options */
1569
		$(klid + " option").filter(function() {
1570
			return parseInt($(this).val()) < min_keylen;
1571
		}).removeClass("text-normal").addClass("text-warning").siblings().removeClass("text-warning").addClass("text-normal");
1572
	}
1573

    
1574
	function check_digest() {
1575
		var weak_algs = <?= json_encode($cert_strict_values['digest_blacklist']) ?>;
1576
		var daid = '#digest_alg';
1577
		if ($('#method').val() == "external") {
1578
			daid = '#csr_digest_alg';
1579
		} else if ($('#method').val() == "sign") {
1580
			daid = '#csrsign_digest_alg';
1581
		}
1582
		/* Color the Parent/Label */
1583
		if (jQuery.inArray($(daid).val(), weak_algs) > -1) {
1584
			$(daid).parent().parent().removeClass("text-normal").addClass("text-warning");
1585
		} else {
1586
			$(daid).parent().parent().removeClass("text-warning").addClass("text-normal");
1587
		}
1588
		/* Color individual options */
1589
		$(daid + " option").filter(function() {
1590
			return (jQuery.inArray($(this).val(), weak_algs) > -1);
1591
		}).removeClass("text-normal").addClass("text-warning").siblings().removeClass("text-warning").addClass("text-normal");
1592
	}
1593

    
1594
	// ---------- Click checkbox handlers ---------------------------------------------------------
1595

    
1596
	$('#type').on('change', function() {
1597
		check_lifetime();
1598
	});
1599
	$('#method').on('change', function() {
1600
		check_lifetime();
1601
		check_keylen();
1602
		check_digest();
1603
	});
1604
	$('#lifetime').on('change', function() {
1605
		check_lifetime();
1606
	});
1607
	$('#csrsign_lifetime').on('change', function() {
1608
		check_lifetime();
1609
	});
1610

    
1611
	$('#keylen').on('change', function() {
1612
		check_keylen();
1613
	});
1614
	$('#csr_keylen').on('change', function() {
1615
		check_keylen();
1616
	});
1617

    
1618
	$('#digest_alg').on('change', function() {
1619
		check_digest();
1620
	});
1621
	$('#csr_digest_alg').on('change', function() {
1622
		check_digest();
1623
	});
1624

    
1625
	$('#caref').on('change', function() {
1626
		internalca_change();
1627
	});
1628

    
1629
	$('#csrtosign').change(function () {
1630
		set_csr_ro();
1631
	});
1632

    
1633
	function change_keytype() {
1634
		hideClass('rsakeys', ($('#keytype').val() != 'RSA'));
1635
		hideClass('ecnames', ($('#keytype').val() != 'ECDSA'));
1636
	}
1637

    
1638
	$('#keytype').change(function () {
1639
		change_keytype();
1640
	});
1641

    
1642
	function change_csrkeytype() {
1643
		hideClass('csr_rsakeys', ($('#csr_keytype').val() != 'RSA'));
1644
		hideClass('csr_ecnames', ($('#csr_keytype').val() != 'ECDSA'));
1645
	}
1646

    
1647
	$('#csr_keytype').change(function () {
1648
		change_csrkeytype();
1649
	});
1650

    
1651
	// ---------- On initial page load ------------------------------------------------------------
1652

    
1653
	internalca_change();
1654
	set_csr_ro();
1655
	change_keytype();
1656
	change_csrkeytype();
1657
	check_lifetime();
1658
	check_keylen();
1659
	check_digest();
1660

    
1661
	// Suppress "Delete row" button if there are fewer than two rows
1662
	checkLastRow();
1663

    
1664

    
1665
<?php endif; ?>
1666

    
1667

    
1668
});
1669
//]]>
1670
</script>
1671
<?php
1672
include('foot.inc');
(193-193/227)