Project

General

Profile

Download (54.1 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-2022 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
$cert_methods = array(
37
	"internal" => gettext("Create an internal Certificate"),
38
	"import" => gettext("Import an existing Certificate"),
39
	"external" => gettext("Create a Certificate Signing Request"),
40
	"sign" => gettext("Sign a Certificate Signing Request")
41
);
42

    
43
$cert_keylens = array("1024", "2048", "3072", "4096", "6144", "7680", "8192", "15360", "16384");
44
$cert_keytypes = array("RSA", "ECDSA");
45
$cert_types = array(
46
	"server" => "Server Certificate",
47
	"user" => "User Certificate");
48

    
49
global $cert_altname_types;
50
global $openssl_digest_algs;
51
global $cert_strict_values;
52
global $p12_encryption_levels;
53

    
54
$max_lifetime = cert_get_max_lifetime();
55
$default_lifetime = min(3650, $max_lifetime);
56
$openssl_ecnames = cert_build_curve_list();
57
$class = "success";
58

    
59
if (isset($_REQUEST['userid']) && is_numericint($_REQUEST['userid'])) {
60
	$userid = $_REQUEST['userid'];
61
}
62

    
63
if (isset($userid)) {
64
	$cert_methods["existing"] = gettext("Choose an existing certificate");
65
	init_config_arr(array('system', 'user'));
66
	$a_user =& $config['system']['user'];
67
}
68

    
69
init_config_arr(array('ca'));
70
$a_ca = &$config['ca'];
71

    
72
init_config_arr(array('cert'));
73
$a_cert = &$config['cert'];
74

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

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

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

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

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

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

    
212
if ($_POST['save'] == gettext("Save")) {
213
	/* Creating a new entry */
214
	$input_errors = array();
215
	$pconfig = $_POST;
216

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

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

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

    
239
			if ($_POST['lifetime'] > $max_lifetime) {
240
				$input_errors[] = gettext("Lifetime is longer than the maximum allowed value. Use a shorter lifetime.");
241
			}
242
			break;
243
		case 'edit':
244
		case 'import':
245
			/* Make sure we do not have invalid characters in the fields for the certificate */
246
			if (preg_match("/[\?\>\<\&\/\\\"\']/", $_POST['descr'])) {
247
				$input_errors[] = gettext("The field 'Descriptive Name' contains invalid characters.");
248
			}
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"), htmlspecialchars($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"), htmlspecialchars($newcert['descr']));
488
					unset($act);
489
				}
490
				unset($cert);
491
				break;
492
			case 'edit':
493
				cert_import($cert, $pconfig['cert'], $pconfig['key']);
494
				$savemsg = sprintf(gettext("Edited certificate %s"), htmlspecialchars($cert['descr']));
495
				unset($act);
496
				break;
497
			case 'import':
498
				/* Import an external certificate+key */
499
				if ($pkcs12_data) {
500
					$pconfig['cert'] = $pkcs12_data['cert'];
501
					$pconfig['key'] = $pkcs12_data['pkey'];
502
					if ($_POST['pkcs12_intermediate'] && is_array($pkcs12_data['extracerts'])) {
503
						foreach ($pkcs12_data['extracerts'] as $intermediate) {
504
							$int_data = openssl_x509_parse($intermediate);
505
							if (!$int_data) continue;
506
							$cn = $int_data['subject']['CN'];
507
							$int_ca = array('descr' => $cn, 'refid' => uniqid());
508
							if (ca_import($int_ca, $intermediate)) {
509
								$a_ca[] = $int_ca;
510
							}
511
						}
512
					}
513
				}
514
				cert_import($cert, $pconfig['cert'], $pconfig['key']);
515
				$savemsg = sprintf(gettext("Imported certificate %s"), htmlspecialchars($cert['descr']));
516
				unset($act);
517
				break;
518
			case 'internal':
519
				/* Create an internal certificate */
520
				$dn = array('commonName' => $pconfig['dn_commonname']);
521
				if (!empty($pconfig['dn_country'])) {
522
					$dn['countryName'] = $pconfig['dn_country'];
523
				}
524
				if (!empty($pconfig['dn_state'])) {
525
					$dn['stateOrProvinceName'] = $pconfig['dn_state'];
526
				}
527
				if (!empty($pconfig['dn_city'])) {
528
					$dn['localityName'] = $pconfig['dn_city'];
529
				}
530
				if (!empty($pconfig['dn_organization'])) {
531
					$dn['organizationName'] = $pconfig['dn_organization'];
532
				}
533
				if (!empty($pconfig['dn_organizationalunit'])) {
534
					$dn['organizationalUnitName'] = $pconfig['dn_organizationalunit'];
535
				}
536
				$altnames_tmp = array();
537
				$cn_altname = cert_add_altname_type($pconfig['dn_commonname']);
538
				if (!empty($cn_altname)) {
539
					$altnames_tmp[] = $cn_altname;
540
				}
541
				if (count($altnames)) {
542
					foreach ($altnames as $altname) {
543
						// The CN is added as a SAN automatically, do not add it again.
544
						if ($altname['value'] != $pconfig['dn_commonname']) {
545
							$altnames_tmp[] = "{$altname['type']}:" . $altname['value'];
546
						}
547
					}
548
				}
549
				if (!empty($altnames_tmp)) {
550
					$dn['subjectAltName'] = implode(",", $altnames_tmp);
551
				}
552
				if (!cert_create($cert, $pconfig['caref'], $pconfig['keylen'], $pconfig['lifetime'], $dn, $pconfig['type'], $pconfig['digest_alg'], $pconfig['keytype'], $pconfig['ecname'])) {
553
					$input_errors = array();
554
					while ($ssl_err = openssl_error_string()) {
555
						if (strpos($ssl_err, 'NCONF_get_string:no value') === false) {
556
							$input_errors[] = sprintf(gettext("OpenSSL Library Error: %s"), $ssl_err);
557
						}
558
					}
559
				}
560
				$savemsg = sprintf(gettext("Created internal certificate %s"), htmlspecialchars($cert['descr']));
561
				unset($act);
562
				break;
563
			case 'external':
564
				/* Create a certificate signing request */
565
				$dn = array('commonName' => $pconfig['csr_dn_commonname']);
566
				if (!empty($pconfig['csr_dn_country'])) {
567
					$dn['countryName'] = $pconfig['csr_dn_country'];
568
				}
569
				if (!empty($pconfig['csr_dn_state'])) {
570
					$dn['stateOrProvinceName'] = $pconfig['csr_dn_state'];
571
				}
572
				if (!empty($pconfig['csr_dn_city'])) {
573
					$dn['localityName'] = $pconfig['csr_dn_city'];
574
				}
575
				if (!empty($pconfig['csr_dn_organization'])) {
576
					$dn['organizationName'] = $pconfig['csr_dn_organization'];
577
				}
578
				if (!empty($pconfig['csr_dn_organizationalunit'])) {
579
					$dn['organizationalUnitName'] = $pconfig['csr_dn_organizationalunit'];
580
				}
581
				$altnames_tmp = array();
582
				$cn_altname = cert_add_altname_type($pconfig['csr_dn_commonname']);
583
				if (!empty($cn_altname)) {
584
					$altnames_tmp[] = $cn_altname;
585
				}
586
				if (count($altnames)) {
587
					foreach ($altnames as $altname) {
588
						// The CN is added as a SAN automatically, do not add it again.
589
						if ($altname['value'] != $pconfig['csr_dn_commonname']) {
590
							$altnames_tmp[] = "{$altname['type']}:" . $altname['value'];
591
						}
592
					}
593
				}
594
				if (!empty($altnames_tmp)) {
595
					$dn['subjectAltName'] = implode(",", $altnames_tmp);
596
				}
597
				if (!csr_generate($cert, $pconfig['csr_keylen'], $dn, $pconfig['type'], $pconfig['csr_digest_alg'], $pconfig['csr_keytype'], $pconfig['csr_ecname'])) {
598
					$input_errors = array();
599
					while ($ssl_err = openssl_error_string()) {
600
						if (strpos($ssl_err, 'NCONF_get_string:no value') === false) {
601
							$input_errors[] = sprintf(gettext("OpenSSL Library Error: %s"), $ssl_err);
602
						}
603
					}
604
				}
605
				$savemsg = sprintf(gettext("Created certificate signing request %s"), htmlspecialchars($cert['descr']));
606
				unset($act);
607
				break;
608
			default:
609
				break;
610
		}
611
		error_reporting($old_err_level);
612

    
613
		if (isset($id) && $thiscert) {
614
			$thiscert = $cert;
615
		} elseif ($cert) {
616
			$a_cert[] = $cert;
617
		}
618

    
619
		if (isset($a_user) && isset($userid)) {
620
			$a_user[$userid]['cert'][] = $cert['refid'];
621
		}
622

    
623
		if (!$input_errors) {
624
			write_config($savemsg);
625
		}
626

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

    
637
	/* input validation */
638
	$reqdfields = explode(" ", "descr cert");
639
	$reqdfieldsn = array(
640
		gettext("Descriptive name"),
641
		gettext("Final Certificate data"));
642

    
643
	do_input_validation($_POST, $reqdfields, $reqdfieldsn, $input_errors);
644

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

    
649
	$mod_csr = cert_get_publickey($pconfig['csr'], false, 'csr');
650
	$mod_cert = cert_get_publickey($pconfig['cert'], false);
651

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

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

    
670
$pgtitle = array(gettext("System"), gettext("Certificate Manager"), gettext("Certificates"));
671
$pglinks = array("", "system_camanager.php", "system_certmanager.php");
672

    
673
if (($act == "new" || ($_POST['save'] == gettext("Save") && $input_errors)) ||
674
    ($act == "csr" || ($_POST['save'] == gettext("Update") && $input_errors))) {
675
	$pgtitle[] = gettext('Edit');
676
	$pglinks[] = "@self";
677
}
678
include("head.inc");
679

    
680
if ($input_errors) {
681
	print_input_errors($input_errors);
682
}
683

    
684
if ($savemsg) {
685
	print_info_box($savemsg, $class);
686
}
687

    
688
$tab_array = array();
689
$tab_array[] = array(gettext("CAs"), false, "system_camanager.php");
690
$tab_array[] = array(gettext("Certificates"), true, "system_certmanager.php");
691
$tab_array[] = array(gettext("Certificate Revocation"), false, "system_crlmanager.php");
692
display_top_tabs($tab_array);
693

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

    
698
	if (isset($userid) && $a_user) {
699
		$form->addGlobal(new Form_Input(
700
			'userid',
701
			null,
702
			'hidden',
703
			$userid
704
		));
705
	}
706

    
707
	if (isset($id) && $thiscert) {
708
		$form->addGlobal(new Form_Input(
709
			'id',
710
			null,
711
			'hidden',
712
			$id
713
		));
714
	}
715

    
716
	if ($act) {
717
		$form->addGlobal(new Form_Input(
718
			'act',
719
			null,
720
			'hidden',
721
			$act
722
		));
723
	}
724

    
725
	switch ($act) {
726
		case 'edit':
727
			$maintitle = gettext('Edit an Existing Certificate');
728
			break;
729
		case 'new':
730
		default:
731
			$maintitle = gettext('Add/Sign a New Certificate');
732
			break;
733
	}
734

    
735
	$section = new Form_Section($maintitle);
736

    
737
	if (!isset($id) || ($act == 'edit')) {
738
		$section->addInput(new Form_Select(
739
			'method',
740
			'*Method',
741
			$pconfig['method'],
742
			$cert_methods
743
		))->toggles();
744
	}
745

    
746
	$section->addInput(new Form_Input(
747
		'descr',
748
		'*Descriptive name',
749
		'text',
750
		($a_user && empty($pconfig['descr'])) ? $a_user[$userid]['name'] : $pconfig['descr']
751
	))->addClass('toggle-internal toggle-import toggle-edit toggle-external toggle-sign toggle-existing collapse');
752

    
753
	if (!empty($pconfig['cert'])) {
754
		$section->addInput(new Form_StaticText(
755
			"Subject",
756
			htmlspecialchars(cert_get_subject($pconfig['cert'], false))
757
		))->addClass('toggle-edit collapse');
758
	}
759

    
760
	$form->add($section);
761

    
762
	// Return an array containing the IDs od all CAs
763
	function list_cas() {
764
		global $a_ca;
765
		$allCas = array();
766

    
767
		foreach ($a_ca as $ca) {
768
			if ($ca['prv']) {
769
				$allCas[$ca['refid']] = $ca['descr'];
770
			}
771
		}
772

    
773
		return $allCas;
774
	}
775

    
776
	// Return an array containing the IDs od all CSRs
777
	function list_csrs() {
778
		global $config;
779
		$allCsrs = array();
780

    
781
		foreach ($config['cert'] as $cert) {
782
			if ($cert['csr']) {
783
				$allCsrs[$cert['refid']] = $cert['descr'];
784
			}
785
		}
786

    
787
		return ['new' => gettext('New CSR (Paste below)')] + $allCsrs;
788
	}
789

    
790
	$section = new Form_Section('Sign CSR');
791
	$section->addClass('toggle-sign collapse');
792

    
793
	$section->AddInput(new Form_Select(
794
		'catosignwith',
795
		'*CA to sign with',
796
		$pconfig['catosignwith'],
797
		list_cas()
798
	));
799

    
800
	$section->AddInput(new Form_Select(
801
		'csrtosign',
802
		'*CSR to sign',
803
		isset($pconfig['csrtosign']) ? $pconfig['csrtosign'] : 'new',
804
		list_csrs()
805
	));
806

    
807
	$section->addInput(new Form_Textarea(
808
		'csrpaste',
809
		'CSR data',
810
		$pconfig['csrpaste']
811
	))->setHelp('Paste a Certificate Signing Request in X.509 PEM format here.');
812

    
813
	$section->addInput(new Form_Textarea(
814
		'keypaste',
815
		'Key data',
816
		$pconfig['keypaste']
817
	))->setHelp('Optionally paste a private key here. The key will be associated with the newly signed certificate in %1$s', $g['product_label']);
818

    
819
	$section->addInput(new Form_Input(
820
		'csrsign_lifetime',
821
		'*Certificate Lifetime (days)',
822
		'number',
823
		$pconfig['csrsign_lifetime'] ? $pconfig['csrsign_lifetime']:$default_lifetime,
824
		['max' => $max_lifetime]
825
	))->setHelp('The length of time the signed certificate will be valid, in days. %1$s' .
826
		'Server certificates should not have a lifetime over %2$s days or some platforms ' .
827
		'may consider the certificate invalid.', '<br/>', $cert_strict_values['max_server_cert_lifetime']);
828
	$section->addInput(new Form_Select(
829
		'csrsign_digest_alg',
830
		'*Digest Algorithm',
831
		$pconfig['csrsign_digest_alg'],
832
		array_combine($openssl_digest_algs, $openssl_digest_algs)
833
	))->setHelp('The digest method used when the certificate is signed. %1$s' .
834
		'The best practice is to use an algorithm stronger than SHA1. '.
835
		'Some platforms may consider weaker digest algorithms invalid', '<br/>');
836

    
837
	$form->add($section);
838

    
839
	if ($act == 'edit') {
840
		$editimport = gettext("Edit Certificate");
841
	} else {
842
		$editimport = gettext("Import Certificate");
843
	}
844

    
845
	$section = new Form_Section($editimport);
846
	$section->addClass('toggle-import toggle-edit collapse');
847

    
848
	$group = new Form_Group('Certificate Type');
849

    
850
	$group->add(new Form_Checkbox(
851
		'import_type',
852
		'Certificate Type',
853
		'X.509 (PEM)',
854
		(!isset($pconfig['import_type']) || $pconfig['import_type'] == 'x509'),
855
		'x509'
856
	))->displayAsRadio()->addClass('import_type_toggle');
857

    
858
	$group->add(new Form_Checkbox(
859
		'import_type',
860
		'Certificate Type',
861
		'PKCS #12 (PFX)',
862
		(isset($pconfig['import_type']) && $pconfig['import_type'] == 'pkcs12'),
863
		'pkcs12'
864
	))->displayAsRadio()->addClass('import_type_toggle');
865

    
866
	$section->add($group);
867

    
868
	$section->addInput(new Form_Textarea(
869
		'cert',
870
		'*Certificate data',
871
		$pconfig['cert']
872
	))->setHelp('Paste a certificate in X.509 PEM format here.');
873

    
874
	$section->addInput(new Form_Textarea(
875
		'key',
876
		'Private key data',
877
		$pconfig['key']
878
	))->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.');
879

    
880
	$section->addInput(new Form_Input(
881
		'pkcs12_cert',
882
		'PKCS #12 certificate',
883
		'file',
884
		$pconfig['pkcs12_cert']
885
	))->setHelp('Select a PKCS #12 certificate store.');
886

    
887
	$section->addInput(new Form_Input(
888
		'pkcs12_pass',
889
		'PKCS #12 certificate password',
890
		'password',
891
		$pconfig['pkcs12_pass']
892
	))->setHelp('Enter the password to unlock the PKCS #12 certificate store.');
893

    
894
	$section->addInput(new Form_Checkbox(
895
		'pkcs12_intermediate',
896
		'Intermediates',
897
		'Import intermediate CAs',
898
		isset($pconfig['pkcs12_intermediate'])
899
	))->setHelp('Import any intermediate certificate authorities found in the PKCS #12 certificate store.');
900

    
901
	if ($act == 'edit') {
902
		$section->addInput(new Form_Input(
903
			'exportpass',
904
			'Export Password',
905
			'password',
906
			null,
907
			['placeholder' => gettext('Export Password'), 'autocomplete' => 'new-password']
908
		))->setHelp('Enter the password to use when using the export buttons below (not stored)')->addClass('toggle-edit collapse');
909
		$section->addInput(new Form_Select(
910
		'p12encryption',
911
		'PKCS#12 Encryption',
912
		'high',
913
		$p12_encryption_levels
914
		))->setHelp('Select the level of encryption to use when exporting a PKCS#12 archive. ' .
915
				'Encryption support varies by Operating System and program');
916
	}
917

    
918
	$form->add($section);
919
	$section = new Form_Section('Internal Certificate');
920
	$section->addClass('toggle-internal collapse');
921

    
922
	if (!$internal_ca_count) {
923
		$section->addInput(new Form_StaticText(
924
			'*Certificate authority',
925
			gettext('No internal Certificate Authorities have been defined. ') .
926
			gettext('An internal CA must be defined in order to create an internal certificate. ') .
927
			sprintf(gettext('%1$sCreate%2$s an internal CA.'), '<a href="system_camanager.php?act=new&amp;method=internal"> ', '</a>')
928
		));
929
	} else {
930
		$allCas = array();
931
		foreach ($a_ca as $ca) {
932
			if (!$ca['prv']) {
933
				continue;
934
			}
935

    
936
			$allCas[ $ca['refid'] ] = $ca['descr'];
937
		}
938

    
939
		$section->addInput(new Form_Select(
940
			'caref',
941
			'*Certificate authority',
942
			$pconfig['caref'],
943
			$allCas
944
		));
945
	}
946

    
947
	$section->addInput(new Form_Select(
948
		'keytype',
949
		'*Key type',
950
		$pconfig['keytype'],
951
		array_combine($cert_keytypes, $cert_keytypes)
952
	));
953

    
954
	$group = new Form_Group($i == 0 ? '*Key length':'');
955
	$group->addClass('rsakeys');
956
	$group->add(new Form_Select(
957
		'keylen',
958
		null,
959
		$pconfig['keylen'],
960
		array_combine($cert_keylens, $cert_keylens)
961
	))->setHelp('The length to use when generating a new RSA key, in bits. %1$s' .
962
		'The Key Length should not be lower than 2048 or some platforms ' .
963
		'may consider the certificate invalid.', '<br/>');
964
	$section->add($group);
965

    
966
	$group = new Form_Group($i == 0 ? '*Elliptic Curve Name':'');
967
	$group->addClass('ecnames');
968
	$group->add(new Form_Select(
969
		'ecname',
970
		null,
971
		$pconfig['ecname'],
972
		$openssl_ecnames
973
	))->setHelp('Curves may not be compatible with all uses. Known compatible curve uses are denoted in brackets.');
974
	$section->add($group);
975

    
976
	$section->addInput(new Form_Select(
977
		'digest_alg',
978
		'*Digest Algorithm',
979
		$pconfig['digest_alg'],
980
		array_combine($openssl_digest_algs, $openssl_digest_algs)
981
	))->setHelp('The digest method used when the certificate is signed. %1$s' .
982
		'The best practice is to use an algorithm stronger than SHA1. '.
983
		'Some platforms may consider weaker digest algorithms invalid', '<br/>');
984

    
985
	$section->addInput(new Form_Input(
986
		'lifetime',
987
		'*Lifetime (days)',
988
		'number',
989
		$pconfig['lifetime'],
990
		['max' => $max_lifetime]
991
	))->setHelp('The length of time the signed certificate will be valid, in days. %1$s' .
992
		'Server certificates should not have a lifetime over %2$s days or some platforms ' .
993
		'may consider the certificate invalid.', '<br/>', $cert_strict_values['max_server_cert_lifetime']);
994

    
995
	$section->addInput(new Form_Input(
996
		'dn_commonname',
997
		'*Common Name',
998
		'text',
999
		$pconfig['dn_commonname'],
1000
		['placeholder' => 'e.g. www.example.com']
1001
	));
1002

    
1003
	$section->addInput(new Form_StaticText(
1004
		null,
1005
		gettext('The following certificate subject components are optional and may be left blank.')
1006
	));
1007

    
1008
	$section->addInput(new Form_Select(
1009
		'dn_country',
1010
		'Country Code',
1011
		$pconfig['dn_country'],
1012
		get_cert_country_codes()
1013
	));
1014

    
1015
	$section->addInput(new Form_Input(
1016
		'dn_state',
1017
		'State or Province',
1018
		'text',
1019
		$pconfig['dn_state'],
1020
		['placeholder' => 'e.g. Texas']
1021
	));
1022

    
1023
	$section->addInput(new Form_Input(
1024
		'dn_city',
1025
		'City',
1026
		'text',
1027
		$pconfig['dn_city'],
1028
		['placeholder' => 'e.g. Austin']
1029
	));
1030

    
1031
	$section->addInput(new Form_Input(
1032
		'dn_organization',
1033
		'Organization',
1034
		'text',
1035
		$pconfig['dn_organization'],
1036
		['placeholder' => 'e.g. My Company Inc']
1037
	));
1038

    
1039
	$section->addInput(new Form_Input(
1040
		'dn_organizationalunit',
1041
		'Organizational Unit',
1042
		'text',
1043
		$pconfig['dn_organizationalunit'],
1044
		['placeholder' => 'e.g. My Department Name (optional)']
1045
	));
1046

    
1047
	$form->add($section);
1048
	$section = new Form_Section('External Signing Request');
1049
	$section->addClass('toggle-external collapse');
1050

    
1051
	$section->addInput(new Form_Select(
1052
		'csr_keytype',
1053
		'*Key type',
1054
		$pconfig['csr_keytype'],
1055
		array_combine($cert_keytypes, $cert_keytypes)
1056
	));
1057

    
1058
	$group = new Form_Group($i == 0 ? '*Key length':'');
1059
	$group->addClass('csr_rsakeys');
1060
	$group->add(new Form_Select(
1061
		'csr_keylen',
1062
		null,
1063
		$pconfig['csr_keylen'],
1064
		array_combine($cert_keylens, $cert_keylens)
1065
	))->setHelp('The length to use when generating a new RSA key, in bits. %1$s' .
1066
		'The Key Length should not be lower than 2048 or some platforms ' .
1067
		'may consider the certificate invalid.', '<br/>');
1068
	$section->add($group);
1069

    
1070
	$group = new Form_Group($i == 0 ? '*Elliptic Curve Name':'');
1071
	$group->addClass('csr_ecnames');
1072
	$group->add(new Form_Select(
1073
		'csr_ecname',
1074
		null,
1075
		$pconfig['csr_ecname'],
1076
		$openssl_ecnames
1077
	));
1078
	$section->add($group);
1079

    
1080
	$section->addInput(new Form_Select(
1081
		'csr_digest_alg',
1082
		'*Digest Algorithm',
1083
		$pconfig['csr_digest_alg'],
1084
		array_combine($openssl_digest_algs, $openssl_digest_algs)
1085
	))->setHelp('The digest method used when the certificate is signed. %1$s' .
1086
		'The best practice is to use an algorithm stronger than SHA1. '.
1087
		'Some platforms may consider weaker digest algorithms invalid', '<br/>');
1088

    
1089
	$section->addInput(new Form_Input(
1090
		'csr_dn_commonname',
1091
		'*Common Name',
1092
		'text',
1093
		$pconfig['csr_dn_commonname'],
1094
		['placeholder' => 'e.g. internal-ca']
1095
	));
1096

    
1097
	$section->addInput(new Form_StaticText(
1098
		null,
1099
		gettext('The following certificate subject components are optional and may be left blank.')
1100
	));
1101

    
1102
	$section->addInput(new Form_Select(
1103
		'csr_dn_country',
1104
		'Country Code',
1105
		$pconfig['csr_dn_country'],
1106
		get_cert_country_codes()
1107
	));
1108

    
1109
	$section->addInput(new Form_Input(
1110
		'csr_dn_state',
1111
		'State or Province',
1112
		'text',
1113
		$pconfig['csr_dn_state'],
1114
		['placeholder' => 'e.g. Texas']
1115
	));
1116

    
1117
	$section->addInput(new Form_Input(
1118
		'csr_dn_city',
1119
		'City',
1120
		'text',
1121
		$pconfig['csr_dn_city'],
1122
		['placeholder' => 'e.g. Austin']
1123
	));
1124

    
1125
	$section->addInput(new Form_Input(
1126
		'csr_dn_organization',
1127
		'Organization',
1128
		'text',
1129
		$pconfig['csr_dn_organization'],
1130
		['placeholder' => 'e.g. My Company Inc']
1131
	));
1132

    
1133
	$section->addInput(new Form_Input(
1134
		'csr_dn_organizationalunit',
1135
		'Organizational Unit',
1136
		'text',
1137
		$pconfig['csr_dn_organizationalunit'],
1138
		['placeholder' => 'e.g. My Department Name (optional)']
1139
	));
1140

    
1141
	$form->add($section);
1142
	$section = new Form_Section('Choose an Existing Certificate');
1143
	$section->addClass('toggle-existing collapse');
1144

    
1145
	$existCerts = array();
1146

    
1147
	foreach ($config['cert'] as $cert) {
1148
		if (!is_array($cert) || empty($cert)) {
1149
			continue;
1150
		}
1151

    
1152
		if (isset($userid) &&
1153
		    in_array($cert['refid'], config_get_path("system/user/{$userid}/cert", []))) {
1154
			continue;
1155
		}
1156

    
1157
		$ca = lookup_ca($cert['caref']);
1158
		if ($ca) {
1159
			$cert['descr'] .= " (CA: {$ca['descr']})";
1160
		}
1161

    
1162
		if (cert_in_use($cert['refid'])) {
1163
			$cert['descr'] .= " (In Use)";
1164
		}
1165
		if (is_cert_revoked($cert)) {
1166
			$cert['descr'] .= " (Revoked)";
1167
		}
1168

    
1169
		$existCerts[ $cert['refid'] ] = $cert['descr'];
1170
	}
1171

    
1172
	$section->addInput(new Form_Select(
1173
		'certref',
1174
		'*Existing Certificates',
1175
		$pconfig['certref'],
1176
		$existCerts
1177
	));
1178

    
1179
	$form->add($section);
1180

    
1181
	$section = new Form_Section('Certificate Attributes');
1182
	$section->addClass('toggle-external toggle-internal toggle-sign collapse');
1183

    
1184
	$section->addInput(new Form_StaticText(
1185
		gettext('Attribute Notes'),
1186
		'<span class="help-block">'.
1187
		gettext('The following attributes are added to certificates and ' .
1188
		'requests when they are created or signed. These attributes behave ' .
1189
		'differently depending on the selected mode.') .
1190
		'<br/><br/>' .
1191
		'<span class="toggle-internal collapse">' . gettext('For Internal Certificates, these attributes are added directly to the certificate as shown.') . '</span>' .
1192
		'<span class="toggle-external collapse">' .
1193
		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. ') .
1194
		'<br/><br/>' .
1195
		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>' .
1196
		'<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>' .
1197
		'</span>'
1198
	));
1199

    
1200
	$section->addInput(new Form_Select(
1201
		'type',
1202
		'*Certificate Type',
1203
		$pconfig['type'],
1204
		$cert_types
1205
	))->setHelp('Add type-specific usage attributes to the signed certificate.' .
1206
		' Used for placing usage restrictions on, or granting abilities to, ' .
1207
		'the signed certificate.');
1208

    
1209
	if (empty($pconfig['altnames']['item'])) {
1210
		$pconfig['altnames']['item'] = array(
1211
			array('type' => null, 'value' => null)
1212
		);
1213
	}
1214

    
1215
	$counter = 0;
1216
	$numrows = count($pconfig['altnames']['item']) - 1;
1217

    
1218
	foreach ($pconfig['altnames']['item'] as $item) {
1219

    
1220
		$group = new Form_Group($counter == 0 ? 'Alternative Names':'');
1221

    
1222
		$group->add(new Form_Select(
1223
			'altname_type' . $counter,
1224
			'Type',
1225
			$item['type'],
1226
			$cert_altname_types
1227
		))->setHelp(($counter == $numrows) ? 'Type':null);
1228

    
1229
		$group->add(new Form_Input(
1230
			'altname_value' . $counter,
1231
			null,
1232
			'text',
1233
			$item['value']
1234
		))->setHelp(($counter == $numrows) ? 'Value':null);
1235

    
1236
		$group->add(new Form_Button(
1237
			'deleterow' . $counter,
1238
			'Delete',
1239
			null,
1240
			'fa-trash'
1241
		))->addClass('btn-warning');
1242

    
1243
		$group->addClass('repeatable');
1244

    
1245
		$group->setHelp('Enter additional identifiers for the certificate ' .
1246
			'in this list. The Common Name field is automatically ' .
1247
			'added to the certificate as an Alternative Name. ' .
1248
			'The signing CA may ignore or change these values.');
1249

    
1250
		$section->add($group);
1251

    
1252
		$counter++;
1253
	}
1254

    
1255
	$section->addInput(new Form_Button(
1256
		'addrow',
1257
		'Add',
1258
		null,
1259
		'fa-plus'
1260
	))->addClass('btn-success');
1261

    
1262
	$form->add($section);
1263

    
1264
	if (($act == 'edit') && !empty($pconfig['key'])) {
1265
		$form->addGlobal(new Form_Button(
1266
			'exportpkey',
1267
			'Export Private Key',
1268
			null,
1269
			'fa-key'
1270
		))->addClass('btn-primary');
1271
		$form->addGlobal(new Form_Button(
1272
			'exportp12',
1273
			'Export PKCS#12',
1274
			null,
1275
			'fa-archive'
1276
		))->addClass('btn-primary');
1277
	}
1278

    
1279
	print $form;
1280

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

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

    
1287
	$section->addInput(new Form_Input(
1288
		'descr',
1289
		'*Descriptive name',
1290
		'text',
1291
		$pconfig['descr']
1292
	));
1293

    
1294
	$section->addInput(new Form_Textarea(
1295
		'csr',
1296
		'Signing request data',
1297
		$pconfig['csr']
1298
	))->setReadonly()
1299
	  ->setWidth(7)
1300
	  ->setHelp('Copy the certificate signing data from here and forward it to a certificate authority for signing.');
1301

    
1302
	$section->addInput(new Form_Textarea(
1303
		'cert',
1304
		'*Final certificate data',
1305
		$pconfig['cert']
1306
	))->setWidth(7)
1307
	  ->setHelp('Paste the certificate received from the certificate authority here.');
1308

    
1309
	if (isset($id) && $thiscert) {
1310
		$form->addGlobal(new Form_Input(
1311
			'id',
1312
			null,
1313
			'hidden',
1314
			$id
1315
		));
1316

    
1317
		$form->addGlobal(new Form_Input(
1318
			'act',
1319
			null,
1320
			'hidden',
1321
			'csr'
1322
		));
1323
	}
1324

    
1325
	$form->add($section);
1326

    
1327
	$form->addGlobal(new Form_Button(
1328
		'save',
1329
		'Update',
1330
		null,
1331
		'fa-save'
1332
	))->addClass('btn-primary');
1333

    
1334
	print($form);
1335
} else {
1336
?>
1337
<div class="panel panel-default" id="search-panel">
1338
	<div class="panel-heading">
1339
		<h2 class="panel-title">
1340
			<?=gettext('Search')?>
1341
			<span class="widget-heading-icon pull-right">
1342
				<a data-toggle="collapse" href="#search-panel_panel-body">
1343
					<i class="fa fa-plus-circle"></i>
1344
				</a>
1345
			</span>
1346
		</h2>
1347
	</div>
1348
	<div id="search-panel_panel-body" class="panel-body collapse in">
1349
		<div class="form-group">
1350
			<label class="col-sm-2 control-label">
1351
				<?=gettext("Search term")?>
1352
			</label>
1353
			<div class="col-sm-5"><input class="form-control" name="searchstr" id="searchstr" type="text"/></div>
1354
			<div class="col-sm-2">
1355
				<select id="where" class="form-control">
1356
					<option value="0"><?=gettext("Name")?></option>
1357
					<option value="1"><?=gettext("Distinguished Name")?></option>
1358
					<option value="2" selected><?=gettext("Both")?></option>
1359
				</select>
1360
			</div>
1361
			<div class="col-sm-3">
1362
				<a id="btnsearch" title="<?=gettext("Search")?>" class="btn btn-primary btn-sm"><i class="fa fa-search icon-embed-btn"></i><?=gettext("Search")?></a>
1363
				<a id="btnclear" title="<?=gettext("Clear")?>" class="btn btn-info btn-sm"><i class="fa fa-undo icon-embed-btn"></i><?=gettext("Clear")?></a>
1364
			</div>
1365
			<div class="col-sm-10 col-sm-offset-2">
1366
				<span class="help-block"><?=gettext('Enter a search string or *nix regular expression to search certificate names and distinguished names.')?></span>
1367
			</div>
1368
		</div>
1369
	</div>
1370
</div>
1371
<div class="panel panel-default">
1372
	<div class="panel-heading"><h2 class="panel-title"><?=gettext('Certificates')?></h2></div>
1373
	<div class="panel-body">
1374
		<div class="table-responsive">
1375
		<table class="table table-striped table-hover sortable-theme-bootstrap" data-sortable>
1376
			<thead>
1377
				<tr>
1378
					<th><?=gettext("Name")?></th>
1379
					<th><?=gettext("Issuer")?></th>
1380
					<th><?=gettext("Distinguished Name")?></th>
1381
					<th><?=gettext("In Use")?></th>
1382

    
1383
					<th class="col-sm-2"><?=gettext("Actions")?></th>
1384
				</tr>
1385
			</thead>
1386
			<tbody>
1387
<?php
1388

    
1389
$pluginparams = array();
1390
$pluginparams['type'] = 'certificates';
1391
$pluginparams['event'] = 'used_certificates';
1392
$certificates_used_by_packages = pkg_call_plugins('plugin_certificates', $pluginparams);
1393
foreach ($a_cert as $cert):
1394
	if (!is_array($cert) || empty($cert)) {
1395
		continue;
1396
	}
1397
	$name = htmlspecialchars($cert['descr']);
1398
	if ($cert['crt']) {
1399
		$subj = cert_get_subject($cert['crt']);
1400
		$issuer = cert_get_issuer($cert['crt']);
1401
		$purpose = cert_get_purpose($cert['crt']);
1402

    
1403
		if ($subj == $issuer) {
1404
			$caname = '<i>'. gettext("self-signed") .'</i>';
1405
		} else {
1406
			$caname = '<i>'. gettext("external").'</i>';
1407
		}
1408

    
1409
		$subj = htmlspecialchars(cert_escape_x509_chars($subj, true));
1410
	} else {
1411
		$subj = "";
1412
		$issuer = "";
1413
		$purpose = "";
1414
		$startdate = "";
1415
		$enddate = "";
1416
		$caname = "<em>" . gettext("private key only") . "</em>";
1417
	}
1418

    
1419
	if ($cert['csr']) {
1420
		$subj = htmlspecialchars(cert_escape_x509_chars(csr_get_subject($cert['csr']), true));
1421
		$caname = "<em>" . gettext("external - signature pending") . "</em>";
1422
	}
1423

    
1424
	$ca = lookup_ca($cert['caref']);
1425
	if ($ca) {
1426
		$caname = htmlspecialchars($ca['descr']);
1427
	}
1428
?>
1429
				<tr>
1430
					<td>
1431
						<?=$name?><br />
1432
						<?php if ($cert['type']): ?>
1433
							<i><?=$cert_types[$cert['type']]?></i><br />
1434
						<?php endif?>
1435
						<?php if (is_array($purpose)): ?>
1436
							CA: <b><?=$purpose['ca']?></b><br/>
1437
							<?=gettext("Server")?>: <b><?=$purpose['server']?></b><br/>
1438
						<?php endif?>
1439
					</td>
1440
					<td><?=$caname?></td>
1441
					<td>
1442
						<?=$subj?>
1443
						<?= cert_print_infoblock($cert); ?>
1444
						<?php cert_print_dates($cert);?>
1445
					</td>
1446
					<td>
1447
						<?php if (is_cert_revoked($cert)): ?>
1448
							<i><?=gettext("Revoked")?></i>
1449
						<?php endif?>
1450
						<?php if (is_webgui_cert($cert['refid'])): ?>
1451
							<?=gettext("webConfigurator")?>
1452
						<?php endif?>
1453
						<?php if (is_user_cert($cert['refid'])): ?>
1454
							<?=gettext("User Cert")?>
1455
						<?php endif?>
1456
						<?php if (is_openvpn_server_cert($cert['refid'])): ?>
1457
							<?=gettext("OpenVPN Server")?>
1458
						<?php endif?>
1459
						<?php if (is_openvpn_client_cert($cert['refid'])): ?>
1460
							<?=gettext("OpenVPN Client")?>
1461
						<?php endif?>
1462
						<?php if (is_ipsec_cert($cert['refid'])): ?>
1463
							<?=gettext("IPsec Tunnel")?>
1464
						<?php endif?>
1465
						<?php if (is_captiveportal_cert($cert['refid'])): ?>
1466
							<?=gettext("Captive Portal")?>
1467
						<?php endif?>
1468
						<?php if (is_unbound_cert($cert['refid'])): ?>
1469
							<?=gettext("DNS Resolver")?>
1470
						<?php endif?>
1471
						<?php echo cert_usedby_description($cert['refid'], $certificates_used_by_packages); ?>
1472
					</td>
1473
					<td>
1474
						<?php if (!$cert['csr']): ?>
1475
							<a href="system_certmanager.php?act=edit&amp;id=<?=$cert['refid']?>" class="fa fa-pencil" title="<?=gettext("Edit Certificate")?>"></a>
1476
							<a href="system_certmanager.php?act=exp&amp;id=<?=$cert['refid']?>" class="fa fa-certificate" title="<?=gettext("Export Certificate")?>"></a>
1477
							<?php if ($cert['prv']): ?>
1478
								<a href="system_certmanager.php?act=key&amp;id=<?=$cert['refid']?>" class="fa fa-key" title="<?=gettext("Export Key")?>"></a>
1479
								<a href="system_certmanager.php?act=p12&amp;id=<?=$cert['refid']?>" class="fa fa-archive" title="<?=gettext("Export PCKS#12 Archive without Encryption")?>"></a>
1480
							<?php endif?>
1481
							<?php if (is_cert_locally_renewable($cert)): ?>
1482
								<a href="system_certmanager_renew.php?type=cert&amp;refid=<?=$cert['refid']?>" class="fa fa-repeat" title="<?=gettext("Reissue/Renew")?>"></a>
1483
							<?php endif ?>
1484
						<?php else: ?>
1485
							<a href="system_certmanager.php?act=csr&amp;id=<?=$cert['refid']?>" class="fa fa-pencil" title="<?=gettext("Update CSR")?>"></a>
1486
							<a href="system_certmanager.php?act=req&amp;id=<?=$cert['refid']?>" class="fa fa-sign-in" title="<?=gettext("Export Request")?>"></a>
1487
							<a href="system_certmanager.php?act=key&amp;id=<?=$cert['refid']?>" class="fa fa-key" title="<?=gettext("Export Key")?>"></a>
1488
						<?php endif?>
1489
						<?php if (!cert_in_use($cert['refid'])): ?>
1490
							<a href="system_certmanager.php?act=del&amp;id=<?=$cert['refid']?>" class="fa fa-trash" title="<?=gettext("Delete Certificate")?>" usepost></a>
1491
						<?php endif?>
1492
					</td>
1493
				</tr>
1494
<?php
1495
	endforeach; ?>
1496
			</tbody>
1497
		</table>
1498
		</div>
1499
	</div>
1500
</div>
1501

    
1502
<nav class="action-buttons">
1503
	<a href="?act=new" class="btn btn-success btn-sm">
1504
		<i class="fa fa-plus icon-embed-btn"></i>
1505
		<?=gettext("Add/Sign")?>
1506
	</a>
1507
</nav>
1508
<script type="text/javascript">
1509
//<![CDATA[
1510

    
1511
events.push(function() {
1512

    
1513
	// Make these controls plain buttons
1514
	$("#btnsearch").prop('type', 'button');
1515
	$("#btnclear").prop('type', 'button');
1516

    
1517
	// Search for a term in the entry name and/or dn
1518
	$("#btnsearch").click(function() {
1519
		var searchstr = $('#searchstr').val().toLowerCase();
1520
		var table = $("table tbody");
1521
		var where = $('#where').val();
1522

    
1523
		table.find('tr').each(function (i) {
1524
			var $tds = $(this).find('td'),
1525
				shortname = $tds.eq(0).text().trim().toLowerCase(),
1526
				dn = $tds.eq(2).text().trim().toLowerCase();
1527

    
1528
			regexp = new RegExp(searchstr);
1529
			if (searchstr.length > 0) {
1530
				if (!(regexp.test(shortname) && (where != 1)) && !(regexp.test(dn) && (where != 0))) {
1531
					$(this).hide();
1532
				} else {
1533
					$(this).show();
1534
				}
1535
			} else {
1536
				$(this).show();	// A blank search string shows all
1537
			}
1538
		});
1539
	});
1540

    
1541
	// Clear the search term and unhide all rows (that were hidden during a previous search)
1542
	$("#btnclear").click(function() {
1543
		var table = $("table tbody");
1544

    
1545
		$('#searchstr').val("");
1546

    
1547
		table.find('tr').each(function (i) {
1548
			$(this).show();
1549
		});
1550
	});
1551

    
1552
	// Hitting the enter key will do the same as clicking the search button
1553
	$("#searchstr").on("keyup", function (event) {
1554
		if (event.keyCode == 13) {
1555
			$("#btnsearch").get(0).click();
1556
		}
1557
	});
1558
});
1559
//]]>
1560
</script>
1561
<?php
1562
	include("foot.inc");
1563
	exit;
1564
}
1565

    
1566

    
1567
?>
1568
<script type="text/javascript">
1569
//<![CDATA[
1570
events.push(function() {
1571

    
1572
	$('.import_type_toggle').click(function() {
1573
		var x509 = (this.value === 'x509');
1574
		hideInput('cert', !x509);
1575
		setRequired('cert', x509);
1576
		hideInput('key', !x509);
1577
		setRequired('key', x509);
1578
		hideInput('pkcs12_cert', x509);
1579
		setRequired('pkcs12_cert', !x509);
1580
		hideInput('pkcs12_pass', x509);
1581
		hideCheckbox('pkcs12_intermediate', x509);
1582
	});
1583
	if ($('input[name=import_type]:checked').val() == 'x509') {
1584
		hideInput('pkcs12_cert', true);
1585
		setRequired('pkcs12_cert', false);
1586
		hideInput('pkcs12_pass', true);
1587
		hideCheckbox('pkcs12_intermediate', true);
1588
		hideInput('cert', false);
1589
		setRequired('cert', true);
1590
		hideInput('key', false);
1591
		setRequired('key', true);
1592
	} else if ($('input[name=import_type]:checked').val() == 'pkcs12') {
1593
		hideInput('cert', true);
1594
		setRequired('cert', false);
1595
		hideInput('key', true);
1596
		setRequired('key', false);
1597
		setRequired('pkcs12_cert', false);
1598
	}
1599

    
1600
<?php if ($internal_ca_count): ?>
1601
	function internalca_change() {
1602

    
1603
		caref = $('#caref').val();
1604

    
1605
		switch (caref) {
1606
<?php
1607
			foreach ($a_ca as $ca):
1608
				if (!$ca['prv']) {
1609
					continue;
1610
				}
1611

    
1612
				$subject = @cert_get_subject_hash($ca['crt']);
1613
				if (!is_array($subject) || empty($subject)) {
1614
					continue;
1615
				}
1616
?>
1617
				case "<?=$ca['refid'];?>":
1618
					$('#dn_country').val(<?=json_encode(cert_escape_x509_chars($subject['C'], true));?>);
1619
					$('#dn_state').val(<?=json_encode(cert_escape_x509_chars($subject['ST'], true));?>);
1620
					$('#dn_city').val(<?=json_encode(cert_escape_x509_chars($subject['L'], true));?>);
1621
					$('#dn_organization').val(<?=json_encode(cert_escape_x509_chars($subject['O'], true));?>);
1622
					$('#dn_organizationalunit').val(<?=json_encode(cert_escape_x509_chars($subject['OU'], true));?>);
1623
					break;
1624
<?php
1625
			endforeach;
1626
?>
1627
		}
1628
	}
1629

    
1630
	function set_csr_ro() {
1631
		var newcsr = ($('#csrtosign').val() == "new");
1632

    
1633
		$('#csrpaste').attr('readonly', !newcsr);
1634
		$('#keypaste').attr('readonly', !newcsr);
1635
		setRequired('csrpaste', newcsr);
1636
	}
1637

    
1638
	function check_lifetime() {
1639
		var maxserverlife = <?= $cert_strict_values['max_server_cert_lifetime'] ?>;
1640
		var ltid = '#lifetime';
1641
		if ($('#method').val() == "sign") {
1642
			ltid = '#csrsign_lifetime';
1643
		}
1644
		if (($('#type').val() == "server") && (parseInt($(ltid).val()) > maxserverlife)) {
1645
			$(ltid).parent().parent().removeClass("text-normal").addClass("text-warning");
1646
			$(ltid).removeClass("text-normal").addClass("text-warning");
1647
		} else {
1648
			$(ltid).parent().parent().removeClass("text-warning").addClass("text-normal");
1649
			$(ltid).removeClass("text-warning").addClass("text-normal");
1650
		}
1651
	}
1652
	function check_keylen() {
1653
		var min_keylen = <?= $cert_strict_values['min_private_key_bits'] ?>;
1654
		var klid = '#keylen';
1655
		if ($('#method').val() == "external") {
1656
			klid = '#csr_keylen';
1657
		}
1658
		/* Color the Parent/Label */
1659
		if (parseInt($(klid).val()) < min_keylen) {
1660
			$(klid).parent().parent().removeClass("text-normal").addClass("text-warning");
1661
		} else {
1662
			$(klid).parent().parent().removeClass("text-warning").addClass("text-normal");
1663
		}
1664
		/* Color individual options */
1665
		$(klid + " option").filter(function() {
1666
			return parseInt($(this).val()) < min_keylen;
1667
		}).removeClass("text-normal").addClass("text-warning").siblings().removeClass("text-warning").addClass("text-normal");
1668
	}
1669

    
1670
	function check_digest() {
1671
		var weak_algs = <?= json_encode($cert_strict_values['digest_blacklist']) ?>;
1672
		var daid = '#digest_alg';
1673
		if ($('#method').val() == "external") {
1674
			daid = '#csr_digest_alg';
1675
		} else if ($('#method').val() == "sign") {
1676
			daid = '#csrsign_digest_alg';
1677
		}
1678
		/* Color the Parent/Label */
1679
		if (jQuery.inArray($(daid).val(), weak_algs) > -1) {
1680
			$(daid).parent().parent().removeClass("text-normal").addClass("text-warning");
1681
		} else {
1682
			$(daid).parent().parent().removeClass("text-warning").addClass("text-normal");
1683
		}
1684
		/* Color individual options */
1685
		$(daid + " option").filter(function() {
1686
			return (jQuery.inArray($(this).val(), weak_algs) > -1);
1687
		}).removeClass("text-normal").addClass("text-warning").siblings().removeClass("text-warning").addClass("text-normal");
1688
	}
1689

    
1690
	// ---------- Click checkbox handlers ---------------------------------------------------------
1691

    
1692
	$('#type').on('change', function() {
1693
		check_lifetime();
1694
	});
1695
	$('#method').on('change', function() {
1696
		check_lifetime();
1697
		check_keylen();
1698
		check_digest();
1699
	});
1700
	$('#lifetime').on('change', function() {
1701
		check_lifetime();
1702
	});
1703
	$('#csrsign_lifetime').on('change', function() {
1704
		check_lifetime();
1705
	});
1706

    
1707
	$('#keylen').on('change', function() {
1708
		check_keylen();
1709
	});
1710
	$('#csr_keylen').on('change', function() {
1711
		check_keylen();
1712
	});
1713

    
1714
	$('#digest_alg').on('change', function() {
1715
		check_digest();
1716
	});
1717
	$('#csr_digest_alg').on('change', function() {
1718
		check_digest();
1719
	});
1720

    
1721
	$('#caref').on('change', function() {
1722
		internalca_change();
1723
	});
1724

    
1725
	$('#csrtosign').change(function () {
1726
		set_csr_ro();
1727
	});
1728

    
1729
	function change_keytype() {
1730
		hideClass('rsakeys', ($('#keytype').val() != 'RSA'));
1731
		hideClass('ecnames', ($('#keytype').val() != 'ECDSA'));
1732
	}
1733

    
1734
	$('#keytype').change(function () {
1735
		change_keytype();
1736
	});
1737

    
1738
	function change_csrkeytype() {
1739
		hideClass('csr_rsakeys', ($('#csr_keytype').val() != 'RSA'));
1740
		hideClass('csr_ecnames', ($('#csr_keytype').val() != 'ECDSA'));
1741
	}
1742

    
1743
	$('#csr_keytype').change(function () {
1744
		change_csrkeytype();
1745
	});
1746

    
1747
	// ---------- On initial page load ------------------------------------------------------------
1748

    
1749
	internalca_change();
1750
	set_csr_ro();
1751
	change_keytype();
1752
	change_csrkeytype();
1753
	check_lifetime();
1754
	check_keylen();
1755
	check_digest();
1756

    
1757
	// Suppress "Delete row" button if there are fewer than two rows
1758
	checkLastRow();
1759

    
1760

    
1761
<?php endif; ?>
1762

    
1763

    
1764
});
1765
//]]>
1766
</script>
1767
<?php
1768
include('foot.inc');
(193-193/228)