certs.inc 14.9 KB
Newer Older
Ad Schellevis's avatar
Ad Schellevis committed
1
<?php
2

Ad Schellevis's avatar
Ad Schellevis committed
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
/*
	Copyright (C) 2008 Shrew Soft Inc
	Copyright (C) 2010 Jim Pingle <jimp@pfsense.org>
	All rights reserved.

        Redistribution and use in source and binary forms, with or without
        modification, are permitted provided that the following conditions are met:

        1. Redistributions of source code must retain the above copyright notice,
           this list of conditions and the following disclaimer.

        2. Redistributions in binary form must reproduce the above copyright
           notice, this list of conditions and the following disclaimer in the
           documentation and/or other materials provided with the distribution.

        THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
        INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
        AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
        AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
        OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
        SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
        INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
        CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
        ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
        POSSIBILITY OF SUCH DAMAGE.
*/

global $openssl_digest_algs;
$openssl_digest_algs = array("sha1", "sha224", "sha256", "sha384", "sha512");

global $openssl_crl_status;
$openssl_crl_status = array(
	OCSP_REVOKED_STATUS_NOSTATUS              => "No Status (default)",
	OCSP_REVOKED_STATUS_UNSPECIFIED           => "Unspecified",
	OCSP_REVOKED_STATUS_KEYCOMPROMISE         => "Key Compromise",
	OCSP_REVOKED_STATUS_CACOMPROMISE          => "CA Compromise",
	OCSP_REVOKED_STATUS_AFFILIATIONCHANGED    => "Affiliation Changed",
	OCSP_REVOKED_STATUS_SUPERSEDED            => "Superseded",
	OCSP_REVOKED_STATUS_CESSATIONOFOPERATION  => "Cessation of Operation",
	OCSP_REVOKED_STATUS_CERTIFICATEHOLD       => "Certificate Hold"
);

function & lookup_ca($refid) {
	global $config;
47
	$false = false;
Ad Schellevis's avatar
Ad Schellevis committed
48 49 50 51 52

	if (is_array($config['ca']))
		foreach ($config['ca'] as & $ca)
			if ($ca['refid'] == $refid)
				return $ca;
53
	return $false;
Ad Schellevis's avatar
Ad Schellevis committed
54 55 56 57
}

function & lookup_ca_by_subject($subject) {
	global $config;
58
	$false = false;
Ad Schellevis's avatar
Ad Schellevis committed
59 60 61 62 63 64 65 66 67

	if (is_array($config['ca']))
		foreach ($config['ca'] as & $ca)
		{
			$ca_subject = cert_get_subject($ca['crt']);
			if ($ca_subject == $subject)
				return $ca;
		}

68
	return $false;
Ad Schellevis's avatar
Ad Schellevis committed
69 70 71 72
}

function & lookup_cert($refid) {
	global $config;
73
	$false = false;
Ad Schellevis's avatar
Ad Schellevis committed
74 75 76 77 78 79

	if (is_array($config['cert']))
		foreach ($config['cert'] as & $cert)
			if ($cert['refid'] == $refid)
				return $cert;

80
	return $false;
Ad Schellevis's avatar
Ad Schellevis committed
81 82 83 84
}

function & lookup_crl($refid) {
	global $config;
85
	$false = false;
Ad Schellevis's avatar
Ad Schellevis committed
86 87 88 89 90 91

	if (is_array($config['crl']))
		foreach ($config['crl'] as & $crl)
			if ($crl['refid'] == $refid)
				return $crl;

92
	return $false;
Ad Schellevis's avatar
Ad Schellevis committed
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
}

function ca_chain_array(& $cert) {
	if($cert['caref']) {
		$chain = array();
		$crt = lookup_ca($cert['caref']);
		$chain[] = $crt;
		while ($crt) {
			$caref = $crt['caref'];
			if($caref)
				$crt = lookup_ca($caref);
			else
				$crt = false;
			if($crt)
				$chain[] = $crt;
		}
		return $chain;
	}
	return false;
}

function ca_chain(& $cert) {
115
	if(isset($cert['caref'])) {
Ad Schellevis's avatar
Ad Schellevis committed
116 117 118 119 120 121 122 123 124 125 126 127 128
		$ca = "";
		$cas = ca_chain_array($cert);
		if (is_array($cas))
			foreach ($cas as & $ca_cert)
			{
				$ca .= base64_decode($ca_cert['crt']);
				$ca .= "\n";
			}
		return $ca;
	}
	return "";
}

129 130
function ca_create(&$ca, $keylen, $lifetime, $dn, $digest_alg = 'sha256')
{
Ad Schellevis's avatar
Ad Schellevis committed
131
	$args = array(
132 133 134 135 136 137 138
		'config' => '/usr/local/etc/ssl/opnsense.cnf',
		'private_key_type' => OPENSSL_KEYTYPE_RSA,
		'private_key_bits' => (int)$keylen,
		'x509_extensions' => 'v3_ca',
		'digest_alg' => $digest_alg,
		'encrypt_key' => false
	);
Ad Schellevis's avatar
Ad Schellevis committed
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172

	// generate a new key pair
	$res_key = openssl_pkey_new($args);
	if (!$res_key) return false;

	// generate a certificate signing request
	$res_csr = openssl_csr_new($dn, $res_key, $args);
	if (!$res_csr) return false;

	// self sign the certificate
	$res_crt = openssl_csr_sign($res_csr, null, $res_key, $lifetime, $args);
	if (!$res_crt) return false;

	// export our certificate data
	if (!openssl_pkey_export($res_key, $str_key) ||
	    !openssl_x509_export($res_crt, $str_crt))
		return false;

	// return our ca information
	$ca['crt'] = base64_encode($str_crt);
	$ca['prv'] = base64_encode($str_key);
	$ca['serial'] = 0;

	return true;
}


function cert_import(& $cert, $crt_str, $key_str) {

	$cert['crt'] = base64_encode($crt_str);
	$cert['prv'] = base64_encode($key_str);

	$subject = cert_get_subject($crt_str, false);
	$issuer = cert_get_issuer($crt_str, false);
173

Ad Schellevis's avatar
Ad Schellevis committed
174 175 176 177 178 179 180 181 182
	// Find my issuer unless self-signed
	if($issuer <> $subject) {
		$issuer_crt =& lookup_ca_by_subject($issuer);
		if($issuer_crt)
			$cert['caref'] = $issuer_crt['refid'];
	}
	return true;
}

183 184 185 186
function cert_create(&$cert, $caref, $keylen, $lifetime, $dn, $digest_alg = 'sha256')
{
	$ca = &lookup_ca($caref);
	if (!$ca) {
Ad Schellevis's avatar
Ad Schellevis committed
187
		return false;
188
	}
Ad Schellevis's avatar
Ad Schellevis committed
189 190 191 192 193

	$ca_str_crt = base64_decode($ca['crt']);
	$ca_str_key = base64_decode($ca['prv']);
	$ca_res_crt = openssl_x509_read($ca_str_crt);
	$ca_res_key = openssl_pkey_get_private(array(0 => $ca_str_key, 1 => ""));
194 195 196
	if (!$ca_res_key) {
		return false;
	}
Ad Schellevis's avatar
Ad Schellevis committed
197 198
	$ca_serial = ++$ca['serial'];

199
	/* subjectAltName can be set _only_ via configuration file */
Ad Schellevis's avatar
Ad Schellevis committed
200
	if ($dn['subjectAltName']) {
201 202
		/* TODO: currently disabled */
		putenv("SAN={$dn['subjectAltName']}");
Ad Schellevis's avatar
Ad Schellevis committed
203 204 205 206 207
		$cert_type .= '_san';
		unset($dn['subjectAltName']);
	}

	$args = array(
208 209 210 211 212 213 214
		'config' => '/usr/local/etc/ssl/opnsense.cnf',
		'private_key_type' => OPENSSL_KEYTYPE_RSA,
		'private_key_bits' => (int)$keylen,
		'x509_extensions' => 'usr_cert',
		'digest_alg' => $digest_alg,
		'encrypt_key' => false
	);
Ad Schellevis's avatar
Ad Schellevis committed
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281

	// generate a new key pair
	$res_key = openssl_pkey_new($args);
	if(!$res_key) return false;

	// generate a certificate signing request
	$res_csr = openssl_csr_new($dn, $res_key, $args);
	if(!$res_csr) return false;

	// self sign the certificate
	$res_crt = openssl_csr_sign($res_csr, $ca_res_crt, $ca_res_key, $lifetime,
				 $args, $ca_serial);
	if(!$res_crt) return false;

	// export our certificate data
	if (!openssl_pkey_export($res_key, $str_key) ||
	    !openssl_x509_export($res_crt, $str_crt))
		return false;

	// return our certificate information
	$cert['caref'] = $caref;
	$cert['crt'] = base64_encode($str_crt);
	$cert['prv'] = base64_encode($str_key);

	return true;
}



function csr_get_subject($str_crt, $decode = true) {

	if ($decode)
		$str_crt = base64_decode($str_crt);

	$components = openssl_csr_get_subject($str_crt);

	if (empty($components) || !is_array($components))
		return "unknown";

	ksort($components);
	foreach ($components as $a => $v) {
		if (!strlen($subject))
			$subject = "{$a}={$v}";
		else
			$subject = "{$a}={$v}, {$subject}";
	}

	return $subject;
}

function cert_get_subject($str_crt, $decode = true) {

	if ($decode)
		$str_crt = base64_decode($str_crt);

	$inf_crt = openssl_x509_parse($str_crt);
	$components = $inf_crt['subject'];

	if (empty($components) || !is_array($components))
		return "unknown";

	ksort($components);
	foreach ($components as $a => $v) {
		if (is_array($v)) {
			ksort($v);
			foreach ($v as $w) {
				$asubject = "{$a}={$w}";
282
				$subject = (isset($subject)) ? "{$asubject}, {$subject}" : $asubject;
Ad Schellevis's avatar
Ad Schellevis committed
283 284 285
			}
		} else {
			$asubject = "{$a}={$v}";
286
			$subject = (isset($subject)) ? "{$asubject}, {$subject}" : $asubject;
Ad Schellevis's avatar
Ad Schellevis committed
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
		}
	}

	return $subject;
}

function cert_get_subject_array($crt) {
	$str_crt = base64_decode($crt);
	$inf_crt = openssl_x509_parse($str_crt);
	$components = $inf_crt['subject'];

	if (!is_array($components))
		return;

	$subject_array = array();

	foreach($components as $a => $v)
		$subject_array[] = array('a' => $a, 'v' => $v);

	return $subject_array;
}


function cert_get_issuer($str_crt, $decode = true) {

	if ($decode)
		$str_crt = base64_decode($str_crt);

	$inf_crt = openssl_x509_parse($str_crt);
	$components = $inf_crt['issuer'];
317

Ad Schellevis's avatar
Ad Schellevis committed
318 319 320 321 322 323 324 325 326
	if (empty($components) || !is_array($components))
		return "unknown";

	ksort($components);
	foreach ($components as $a => $v) {
		if (is_array($v)) {
			ksort($v);
			foreach ($v as $w) {
				$aissuer = "{$a}={$w}";
327
				$issuer = (isset($issuer)) ? "{$aissuer}, {$issuer}" : $aissuer;
Ad Schellevis's avatar
Ad Schellevis committed
328 329 330
			}
		} else {
			$aissuer = "{$a}={$v}";
331
			$issuer = (isset($issuer)) ? "{$aissuer}, {$issuer}" : $aissuer;
Ad Schellevis's avatar
Ad Schellevis committed
332 333 334 335 336 337 338
		}
	}

	return $issuer;
}

/* this function works on x509 (crt), rsa key (prv), and req(csr) */
339 340 341 342 343 344 345
function cert_get_modulus($str_crt, $decode = true, $type = 'crt')
{
	$type_list = array('crt', 'prv', 'csr');
	$type_cmd = array('x509', 'rsa', 'req');
	$modulus = '';

	if ($decode) {
Ad Schellevis's avatar
Ad Schellevis committed
346
		$str_crt = base64_decode($str_crt);
347
	}
Ad Schellevis's avatar
Ad Schellevis committed
348

349 350 351
	if (in_array($type, $type_list)) {
		$type = str_replace($type_list, $type_cmd, $type);
		$modulus = exec(sprintf(
352
			'echo %s | /usr/local/bin/openssl %s -noout -modulus',
353 354 355
			escapeshellarg($str_crt),
			escapeshellarg($type)
		));
Ad Schellevis's avatar
Ad Schellevis committed
356
	}
357

Ad Schellevis's avatar
Ad Schellevis committed
358 359
	return $modulus;
}
360

Ad Schellevis's avatar
Ad Schellevis committed
361 362 363 364 365 366 367

function cert_get_purpose($str_crt, $decode = true) {
	if ($decode)
		$str_crt = base64_decode($str_crt);
	$crt_details = openssl_x509_parse($str_crt);
	$purpose = array();
	$purpose['ca'] = (stristr($crt_details['extensions']['basicConstraints'], 'CA:TRUE') === false) ? 'No': 'Yes';
368 369 370 371 372
	if (isset($crt_details['extensions']['nsCertType']) && $crt_details['extensions']['nsCertType'] == "SSL Server") {
		$purpose['server'] = 'Yes';
	} else {
		$purpose['server'] = 'No';
	}
Ad Schellevis's avatar
Ad Schellevis committed
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
	return $purpose;
}

function cert_get_dates($str_crt, $decode = true) {
	if ($decode)
		$str_crt = base64_decode($str_crt);
	$crt_details = openssl_x509_parse($str_crt);
	if ($crt_details['validFrom_time_t'] > 0)
		$start = date('r', $crt_details['validFrom_time_t']);
	if ($crt_details['validTo_time_t'] > 0)
		$end = date('r', $crt_details['validTo_time_t']);
	return array($start, $end);
}

function cert_get_serial($str_crt, $decode = true) {
	if ($decode)
		$str_crt = base64_decode($str_crt);
	$crt_details = openssl_x509_parse($str_crt);
	if (isset($crt_details['serialNumber']) && !empty($crt_details['serialNumber']))
		return $crt_details['serialNumber'];
	else
		return NULL;
}

397 398
function is_user_cert($certref)
{
Ad Schellevis's avatar
Ad Schellevis committed
399
	global $config;
400 401

	if (!isset($config['system']['user'])) {
Ad Schellevis's avatar
Ad Schellevis committed
402
		return;
403 404
	}

Ad Schellevis's avatar
Ad Schellevis committed
405
	foreach ($config['system']['user'] as $user) {
406
		if (!isset($user['cert']) || !is_array($user['cert'])) {
Ad Schellevis's avatar
Ad Schellevis committed
407
			continue;
408
		}
Ad Schellevis's avatar
Ad Schellevis committed
409
		foreach ($user['cert'] as $cert) {
410
			if ($certref == $cert) {
Ad Schellevis's avatar
Ad Schellevis committed
411
				return true;
412
			}
Ad Schellevis's avatar
Ad Schellevis committed
413 414
		}
	}
415

Ad Schellevis's avatar
Ad Schellevis committed
416 417 418
	return false;
}

419 420
function is_openvpn_server_cert($certref)
{
Ad Schellevis's avatar
Ad Schellevis committed
421
	global $config;
422 423

	if (!isset($config['openvpn']['openvpn-server'])) {
Ad Schellevis's avatar
Ad Schellevis committed
424
		return;
425 426
	}

Ad Schellevis's avatar
Ad Schellevis committed
427
	foreach ($config['openvpn']['openvpn-server'] as $ovpns) {
428
		if (isset($ovpns['certref']) && $ovpns['certref'] == $certref) {
Ad Schellevis's avatar
Ad Schellevis committed
429
			return true;
430
		}
Ad Schellevis's avatar
Ad Schellevis committed
431
	}
432

Ad Schellevis's avatar
Ad Schellevis committed
433 434 435
	return false;
}

436 437
function is_openvpn_client_cert($certref)
{
Ad Schellevis's avatar
Ad Schellevis committed
438
	global $config;
439 440

	if (!isset($config['openvpn']['openvpn-client'])) {
Ad Schellevis's avatar
Ad Schellevis committed
441
		return;
442 443
	}

Ad Schellevis's avatar
Ad Schellevis committed
444
	foreach ($config['openvpn']['openvpn-client'] as $ovpnc) {
445
		if (isset($ovpnc['certref']) && $ovpnc['certref'] == $certref) {
Ad Schellevis's avatar
Ad Schellevis committed
446
			return true;
447
		}
Ad Schellevis's avatar
Ad Schellevis committed
448
	}
449

Ad Schellevis's avatar
Ad Schellevis committed
450 451 452
	return false;
}

453 454
function is_ipsec_cert($certref)
{
Ad Schellevis's avatar
Ad Schellevis committed
455
	global $config;
456 457

	if (!isset($config['ipsec']['phase1'])) {
Ad Schellevis's avatar
Ad Schellevis committed
458
		return;
459 460
	}

Ad Schellevis's avatar
Ad Schellevis committed
461
	foreach ($config['ipsec']['phase1'] as $ipsec) {
462
		if ($ipsec['certref'] == $certref) {
Ad Schellevis's avatar
Ad Schellevis committed
463
			return true;
464
		}
Ad Schellevis's avatar
Ad Schellevis committed
465
	}
466

Ad Schellevis's avatar
Ad Schellevis committed
467 468 469
	return false;
}

470 471
function is_webgui_cert($certref)
{
Ad Schellevis's avatar
Ad Schellevis committed
472
	global $config;
473 474 475

	return $config['system']['webgui']['ssl-certref'] == $certref &&
		$config['system']['webgui']['protocol'] != 'http';
Ad Schellevis's avatar
Ad Schellevis committed
476 477 478 479 480 481 482
}

function cert_in_use($certref) {
	return (is_webgui_cert($certref) ||
		is_user_cert($certref) ||
		is_openvpn_server_cert($certref) ||
		is_openvpn_client_cert($certref) ||
483
		is_ipsec_cert($certref));
Ad Schellevis's avatar
Ad Schellevis committed
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
}

function crl_update(& $crl) {
	global $config;
	$ca =& lookup_ca($crl['caref']);
	if (!$ca)
		return false;
	// If we have text but no certs, it was imported and cannot be updated.
	if (($crl["method"] != "internal") && (!empty($crl['text']) && empty($crl['cert'])))
		return false;
	$crl['serial']++;
	$ca_str_crt = base64_decode($ca['crt']);
	$ca_str_key = base64_decode($ca['prv']);
	$crl_res = openssl_crl_new($ca_str_crt, $crl['serial'], $crl['lifetime']);
	if (is_array($crl['cert']) && (count($crl['cert']) > 0)) {
		foreach ($crl['cert'] as $cert) {
			openssl_crl_revoke_cert($crl_res, base64_decode($cert["crt"]), $cert["revoke_time"], $cert["reason"]);
		}
	}
	openssl_crl_export($crl_res, $crl_text, $ca_str_key);
	$crl['text'] = base64_encode($crl_text);
	return $crl_res;
}

function cert_revoke($cert, & $crl, $reason=OCSP_REVOKED_STATUS_UNSPECIFIED) {
	global $config;
	if (is_cert_revoked($cert, $crl['refid']))
		return true;
	// If we have text but no certs, it was imported and cannot be updated.
	if (!is_crl_internal($crl))
		return false;
	$cert["reason"] = $reason;
	$cert["revoke_time"] = time();
	$crl["cert"][] = $cert;
	crl_update($crl);
	return true;
}


/* Compare two certificates to see if they match. */
function cert_compare($cert1, $cert2) {
	/* Ensure two certs are identical by first checking that their issuers match, then
		subjects, then serial numbers, and finally the moduli. Anything less strict
		could accidentally count two similar, but different, certificates as
		being identical. */
	$c1 = base64_decode($cert1['crt']);
	$c2 = base64_decode($cert2['crt']);
	if ((cert_get_issuer($c1, false) == cert_get_issuer($c2, false))
		&& (cert_get_subject($c1, false) == cert_get_subject($c2, false))
		&& (cert_get_serial($c1, false) == cert_get_serial($c2, false))
		&& (cert_get_modulus($c1, false) == cert_get_modulus($c2, false)))
		return true;
	return false;
}

function is_cert_revoked($cert, $crlref = "") {
	global $config;
541
	if (!isset($config['crl']) || !is_array($config['crl']))
Ad Schellevis's avatar
Ad Schellevis committed
542 543 544 545
		return false;

	if (!empty($crlref)) {
		$crl = lookup_crl($crlref);
546
		if (!isset($crl['cert']) || !is_array($crl['cert']))
Ad Schellevis's avatar
Ad Schellevis committed
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
			return false;
		foreach ($crl['cert'] as $rcert) {
			if (cert_compare($rcert, $cert))
				return true;
		}
	} else {
		foreach ($config['crl'] as $crl) {
			if (!is_array($crl['cert']))
				continue;
			foreach ($crl['cert'] as $rcert) {
				if (cert_compare($rcert, $cert))
					return true;
			}
		}
	}
	return false;
}

function is_openvpn_server_crl($crlref) {
	global $config;
567
	if (!isset($config['openvpn']['openvpn-server']) || !is_array($config['openvpn']['openvpn-server']))
Ad Schellevis's avatar
Ad Schellevis committed
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
		return;
	foreach ($config['openvpn']['openvpn-server'] as $ovpns) {
		if (!empty($ovpns['crlref']) && ($ovpns['crlref'] == $crlref))
			return true;
	}
	return false;
}


function is_crl_internal($crl) {
	return (!(!empty($crl['text']) && empty($crl['cert'])) || ($crl["method"] == "internal"));
}

function cert_get_cn($crt, $isref = false) {
	/* If this is a certref, not an actual cert, look up the cert first */
	if ($isref) {
		$cert = lookup_cert($crt);
		/* If it's not a valid cert, bail. */
		if (!(is_array($cert) && !empty($cert['crt'])))
			return "";
		$cert = $cert['crt'];
	} else {
		$cert = $crt;
	}
	$sub = cert_get_subject_array($cert);
	if (is_array($sub)) {
		foreach ($sub as $s) {
			if (strtoupper($s['a']) == "CN")
				return $s['v'];
		}
	}
	return "";
}

?>