public static function setUpBeforeClass() { self::$pKey = openssl_pkey_new(); $csr = openssl_csr_new([], self::$pKey); $x509 = openssl_csr_sign($csr, null, self::$pKey, 1); openssl_x509_export($x509, self::$certificate); openssl_x509_free($x509); }
/** * @param string $certificate * * @throws \InvalidArgumentException * * @return array */ public static function loadKeyFromCertificate($certificate) { try { $res = openssl_x509_read($certificate); } catch (\Exception $e) { $certificate = self::convertDerToPem($certificate); $res = openssl_x509_read($certificate); } if (false === $res) { throw new \InvalidArgumentException('Unable to load the certificate'); } $values = self::loadKeyFromX509Resource($res); openssl_x509_free($res); return $values; }
public static function getIssuer($cert) { if ($cert == NULL) { return 'http://schemas.xmlsoap.org/ws/2005/05/identity/issuer/self'; } else { $resource = file_get_contents($cert); $check_cert = openssl_x509_read($resource); $array = openssl_x509_parse($check_cert); openssl_x509_free($check_cert); $schema = $array['name']; $pattern = '/.*CN=/'; $replacement = ''; $CN = preg_replace($pattern, $replacement, $schema); return $CN; } }
function calculate_RP_PPID_Seed_2_2007($certs) { $check_cert = openssl_x509_read(file_get_contents($certs[0])); $array = openssl_x509_parse($check_cert); openssl_x509_free($check_cert); $OrgIdString = '|O="' . $array['subject']['O'] . '"|L="' . $array['subject']['L'] . '"|S="' . $array['subject']['ST'] . '"|C="' . $array['subject']['C'] . '"|'; $numcerts = sizeof($certs); for ($i = 1; $i < $numcerts; $i++) { $check_cert = openssl_x509_read(file_get_contents($certs[$i])); $array = openssl_x509_parse($check_cert); openssl_x509_free($check_cert); $tmpstring = '|ChainElement="CN=' . $array['subject']['CN'] . ', OU=' . $array['subject']['OU'] . ', O=' . $array['subject']['O'] . ', L=' . $array['subject']['L'] . ', S=' . $array['subject']['ST'] . ', C=' . $array['subject']['C'] . '"'; $OrgIdString = $tmpstring . $OrgIdString; } $OrgIdBytes = iconv("UTF-8", "UTF-16LE", $OrgIdString); $RPPPIDSeed = hash('sha256', $OrgIdBytes, TRUE); return $RPPPIDSeed; }
protected function validateSslOptions() { // Get the contents. $sslCertFile = file_exists($this->certPath) ? trim(file_get_contents($this->certPath)) : ''; $sslKeyFile = file_exists($this->keyPath) ? trim(file_get_contents($this->keyPath)) : ''; $sslChainFiles = $this->assembleChainFiles($this->chainPaths); // Do a bit of validation. // @todo: Cert first. $certResource = openssl_x509_read($sslCertFile); if (!$certResource) { throw new \Exception("The provided certificate is either not a valid X509 certificate or could not be read."); } // Then the key. Does it match? $keyResource = openssl_pkey_get_private($sslKeyFile); if (!$keyResource) { throw new \Exception("The provided private key is either not a valid RSA private key or could not be read."); } $keyMatch = openssl_x509_check_private_key($certResource, $keyResource); if (!$keyMatch) { throw new \Exception("The provided certificate does not match the provided private key."); } // Each chain needs to be a valid cert. foreach ($sslChainFiles as $chainFile) { $chainResource = openssl_x509_read($chainFile); if (!$chainResource) { throw new \Exception("One of the provided certificates in the chain is not a valid X509 certificate."); } else { openssl_x509_free($chainResource); } } // Yay we win. $this->sslOptions = array('certificate' => $sslCertFile, 'key' => $sslKeyFile, 'chain' => $sslChainFiles); return true; }
/** * @param array $x5c * @param array $additional_values * * @return \Jose\Object\JWKInterface */ public static function createFromX5C(array $x5c, array $additional_values = []) { $certificate = null; $last_issuer = null; $last_subject = null; foreach ($x5c as $cert) { $current_cert = "-----BEGIN CERTIFICATE-----\n{$cert}\n-----END CERTIFICATE-----"; $x509 = openssl_x509_read($current_cert); if (false === $x509) { $last_issuer = null; $last_subject = null; break; } $parsed = openssl_x509_parse($x509); openssl_x509_free($x509); if (false === $parsed) { $last_issuer = null; $last_subject = null; break; } if (null === $last_subject) { $last_subject = $parsed['subject']; $last_issuer = $parsed['issuer']; $certificate = $current_cert; } else { if (json_encode($last_issuer) === json_encode($parsed['subject'])) { $last_subject = $parsed['subject']; $last_issuer = $parsed['issuer']; } else { $last_issuer = null; $last_subject = null; break; } } } if (null === $last_issuer || json_encode($last_issuer) !== json_encode($last_subject)) { throw new \InvalidArgumentException('Invalid certificate chain.'); } return self::createFromCertificate($certificate, $additional_values); }
/** * Generate public/private keys and store in the config table * * Use the distinguished name provided to create a CSR, and then sign that CSR * with the same credentials. Store the keypair you create in the config table. * If a distinguished name is not provided, create one using the fullname of * 'the course with ID 1' as your organization name, and your hostname (as * detailed in $CFG->wwwroot). * * @param array $dn The distinguished name of the server * @return string The signature over that text */ function mnet_generate_keypair($dn = null, $days = 28) { global $CFG, $USER; // check if lifetime has been overriden if (!empty($CFG->mnetkeylifetime)) { $days = $CFG->mnetkeylifetime; } $host = strtolower($CFG->wwwroot); $host = ereg_replace("^http(s)?://", '', $host); $break = strpos($host . '/', '/'); $host = substr($host, 0, $break); if ($result = get_record_select('course', " id ='" . SITEID . "' ")) { $organization = $result->fullname; } else { $organization = 'None'; } $keypair = array(); $country = 'NZ'; $province = 'Wellington'; $locality = 'Wellington'; $email = $CFG->noreplyaddress; if (!empty($USER->country)) { $country = $USER->country; } if (!empty($USER->city)) { $province = $USER->city; $locality = $USER->city; } if (!empty($USER->email)) { $email = $USER->email; } if (is_null($dn)) { $dn = array("countryName" => $country, "stateOrProvinceName" => $province, "localityName" => $locality, "organizationName" => $organization, "organizationalUnitName" => 'Moodle', "commonName" => $CFG->wwwroot, "emailAddress" => $email); } $dnlimits = array('countryName' => 2, 'stateOrProvinceName' => 128, 'localityName' => 128, 'organizationName' => 64, 'organizationalUnitName' => 64, 'commonName' => 64, 'emailAddress' => 128); foreach ($dnlimits as $key => $length) { $dn[$key] = substr($dn[$key], 0, $length); } // ensure we remove trailing slashes $dn["commonName"] = preg_replace(':/$:', '', $dn["commonName"]); if (!empty($CFG->opensslcnf)) { //allow specification of openssl.cnf especially for Windows installs $new_key = openssl_pkey_new(array("config" => $CFG->opensslcnf)); $csr_rsc = openssl_csr_new($dn, $new_key, array("config" => $CFG->opensslcnf)); $selfSignedCert = openssl_csr_sign($csr_rsc, null, $new_key, $days, array("config" => $CFG->opensslcnf)); } else { $new_key = openssl_pkey_new(); $csr_rsc = openssl_csr_new($dn, $new_key, array('private_key_bits', 2048)); $selfSignedCert = openssl_csr_sign($csr_rsc, null, $new_key, $days); } unset($csr_rsc); // Free up the resource // We export our self-signed certificate to a string. openssl_x509_export($selfSignedCert, $keypair['certificate']); openssl_x509_free($selfSignedCert); // Export your public/private key pair as a PEM encoded string. You // can protect it with an optional passphrase if you wish. if (!empty($CFG->opensslcnf)) { //allow specification of openssl.cnf especially for Windows installs $export = openssl_pkey_export($new_key, $keypair['keypair_PEM'], null, array("config" => $CFG->opensslcnf)); } else { $export = openssl_pkey_export($new_key, $keypair['keypair_PEM']); } openssl_pkey_free($new_key); unset($new_key); // Free up the resource return $keypair; }
function test_openssl_x509_free() { $fcert = file_get_contents(__DIR__ . "/test_x509.crt"); $cert = openssl_x509_read($fcert); VERIFY($cert != null); openssl_x509_free($cert); }
/** * Destructor * */ public function __destruct() { if (is_resource($this->_res)) { openssl_x509_free($this->_res); } }
/** * Verifies the signature of the document and that the signing certificate * stems from a trusted root CA. * * Returns the CN of the signing certificate if valid. * * @param str $xml XML doc to verify * @param str $signature_value Base64 encoded signature to verify against. * @returns str */ function verify($xml, $signature_value) { $doc = $this->parse_doc($xml); $xp = $this->get_xpath($doc); $valid = $this->validate_xml($xp); $certs = $this->parse_certificates($xp); $cert = openssl_x509_read($certs[0]); $parsed_certificate = openssl_x509_parse($cert); $pubkey = openssl_pkey_get_public($cert); $valid = openssl_verify($xml, base64_decode($signature_value), $pubkey); openssl_pkey_free($pubkey); openssl_x509_free($cert); $signed_by = null; if (!$valid) { throw new GApps_Discovery_Exception("Signature verification failed."); } $trusted = $this->validate_chain($certs); if (!$trusted) { throw new GApps_Discovery_Exception("Can not verify trust chain."); } $subject = $parsed_certificate["subject"]; $signed_by = strtolower($subject["CN"]); return $signed_by; }
/** * Add or update an SSL certificate * * @throws iMSCP_Exception * @throws iMSCP_Exception_Database * @param int $domainId domain unique identifier * @param string $domainType Domain type (dmn|als|sub|alssub) * @return void */ function client_addSslCert($domainId, $domainType) { $config = iMSCP_Registry::get('config'); $domainName = _client_getDomainName($domainId, $domainType); $selfSigned = isset($_POST['selfsigned']); if ($domainName === false) { showBadRequestErrorPage(); } if ($selfSigned && !client_generateSelfSignedCert($domainName)) { set_page_message(tr('Could not generate SSL certificate. An unexpected error occurred.'), 'error'); return; } if (!isset($_POST['passphrase']) || !isset($_POST['private_key']) || !isset($_POST['certificate']) || !isset($_POST['ca_bundle']) || !isset($_POST['cert_id'])) { showBadRequestErrorPage(); } $passPhrase = clean_input($_POST['passphrase']); $privateKey = clean_input($_POST['private_key']); $certificate = clean_input($_POST['certificate']); $caBundle = clean_input($_POST['ca_bundle']); $certId = intval($_POST['cert_id']); if (!$selfSigned) { // Validate SSL certificate (private key, SSL certificate and certificate chain) $privateKey = @openssl_pkey_get_private($privateKey, $passPhrase); if (!is_resource($privateKey)) { set_page_message(tr('Invalid private key or passphrase.'), 'error'); return; } $certificateStr = $certificate; $certificate = @openssl_x509_read($certificate); if (!is_resource($certificate)) { set_page_message(tr('Invalid SSL certificate.'), 'error'); return; } if (!@openssl_x509_check_private_key($certificate, $privateKey)) { set_page_message(tr("The private key doesn't belong to the provided SSL certificate."), 'error'); return; } if (!($tmpfname = @tempnam(sys_get_temp_dir(), intval($_SESSION['user_id']) . 'ssl-ca'))) { write_log('Could not create temporary file for CA bundle..', E_USER_ERROR); set_page_message(tr('Could not add/update SSL certificate. An unexpected error occurred.'), 'error'); return; } register_shutdown_function(function ($file) { @unlink($file); }, $tmpfname); if ($caBundle !== '') { if (!@file_put_contents($tmpfname, $caBundle)) { write_log('Could not export customer CA bundle in temporary file.', E_USER_ERROR); set_page_message(tr('Could not add/update SSL certificate. An unexpected error occurred.'), 'error'); return; } // Note: Here we also add the CA bundle in the trusted chain to support self-signed certificates if (@openssl_x509_checkpurpose($certificate, X509_PURPOSE_SSL_SERVER, array($config['DISTRO_CA_BUNDLE'], $tmpfname), $tmpfname)) { set_page_message(tr('At least one intermediate certificate is invalid or missing.'), 'error'); return; } } else { @file_put_contents($tmpfname, $certificateStr); // Note: Here we also add the certificate in the trusted chain to support self-signed certificates if (!@openssl_x509_checkpurpose($certificate, X509_PURPOSE_SSL_SERVER, array($config['DISTRO_CA_BUNDLE'], $tmpfname))) { set_page_message(tr('At least one intermediate certificate is invalid or missing.'), 'error'); return; } } } // Preparing data for insertion in database if (!$selfSigned) { if (!@openssl_pkey_export($privateKey, $privateKeyStr)) { write_log('Could not export private key.', E_USER_ERROR); set_page_message(tr('Could not add/update SSL certificate. An unexpected error occurred.'), 'error'); return; } @openssl_pkey_free($privateKey); if (!@openssl_x509_export($certificate, $certificateStr)) { write_log('Could not export SSL certificate.', E_USER_ERROR); set_page_message(tr('Could not add/update SSL certificate. An unexpected error occurred.'), 'error'); return; } @openssl_x509_free($certificate); $caBundleStr = str_replace("\r\n", "\n", $caBundle); } else { $privateKeyStr = $privateKey; $certificateStr = $certificate; $caBundleStr = $caBundle; } $db = iMSCP_Database::getInstance(); try { $db->beginTransaction(); if ($certId == 0) { // Add new certificate exec_query(' INSERT INTO ssl_certs ( domain_id, domain_type, private_key, certificate, ca_bundle, status ) VALUES ( ?, ?, ?, ?, ?, ? ) ', array($domainId, $domainType, $privateKeyStr, $certificateStr, $caBundleStr, 'toadd')); } else { // Update existing certificate exec_query(' UPDATE ssl_certs SET private_key = ?, certificate = ?, ca_bundle = ?, status = ? WHERE cert_id = ? AND domain_id = ? AND domain_type = ? ', array($privateKeyStr, $certificateStr, $caBundleStr, 'tochange', $certId, $domainId, $domainType)); } _client_updateDomainStatus($domainType, $domainId); $db->commit(); send_request(); if (!$certId) { set_page_message(tr('SSL certificate successfully scheduled for addition.'), 'success'); write_log(sprintf('%s added a new SSL certificate for the %s domain', decode_idna($_SESSION['user_logged']), decode_idna($domainName)), E_USER_NOTICE); } else { set_page_message(tr('SSL certificate successfully scheduled for update.'), 'success'); write_log(sprintf('%s updated an SSL certificate for the %s domain', decode_idna($_SESSION['user_logged']), $domainName), E_USER_NOTICE); } redirectTo("cert_view.php?domain_id={$domainId}&domain_type={$domainType}"); } catch (iMSCP_Exception_Database $e) { $db->rollBack(); write_log('Unable to add/update SSL certificate in database', E_USER_ERROR); set_page_message('An unexpected error occurred. Please contact your reseller.'); } }
headerFunction("../general/login.php?msg=logout"); } $auth = returnGlobal('auth', 'GET'); $loginForm = returnGlobal('loginForm', 'POST'); $passwordForm = returnGlobal('passwordForm', 'POST'); $match = false; $ssl = false; if (!empty($SSL_CLIENT_CERT) && !$logout && $auth != "test") { $auth = "on"; $ssl = true; if (function_exists("openssl_x509_read")) { $x509 = openssl_x509_read($SSL_CLIENT_CERT); $cert_array = openssl_x509_parse($x509, true); $subject_array = $cert_array["subject"]; $ssl_email = $subject_array["Email"]; openssl_x509_free($x509); } else { $ssl_email = `echo "{$SSL_CLIENT_CERT}" | {$pathToOpenssl} x509 -noout -email`; } } else { //test blank fields in form if ($auth == "test") { if ($loginForm == "" && $passwordForm == "") { $error = $strings["login_username"] . "<br/>" . $strings["login_password"]; } else { if ($loginForm == "") { $error = $strings["login_username"]; } else { if ($passwordForm == "") { $error = $strings["login_password"]; } else {
protected function getSignature($stringToSign) { // Generate a new Certificate Signing Request and public/private keypair $csr = openssl_csr_new(array(), $keypair); // Create the self-signed certificate $x509 = openssl_csr_sign($csr, null, $keypair, 1); openssl_x509_export($x509, $certificate); // Create the signature $privateKey = openssl_get_privatekey($keypair); openssl_sign($stringToSign, $signature, $privateKey); // Free the openssl resources used openssl_pkey_free($keypair); openssl_x509_free($x509); return array(base64_encode($signature), $certificate); }
public function __destruct() { openssl_x509_free($this->x509Cert); }
public function __destruct() { if ($this->certResource) { openssl_x509_free($this->certResource); } $this->certResource = null; $this->publicKey = null; $this->clearText = null; }
/** * @param array $x5c * * @return array */ public static function loadFromX5C(array $x5c) { $certificate = null; $last_issuer = null; $last_subject = null; foreach ($x5c as $cert) { $current_cert = '-----BEGIN CERTIFICATE-----' . PHP_EOL . $cert . PHP_EOL . '-----END CERTIFICATE-----'; $x509 = openssl_x509_read($current_cert); if (false === $x509) { $last_issuer = null; $last_subject = null; break; } $parsed = openssl_x509_parse($x509); openssl_x509_free($x509); if (false === $parsed) { $last_issuer = null; $last_subject = null; break; } if (null === $last_subject) { $last_subject = $parsed['subject']; $last_issuer = $parsed['issuer']; $certificate = $current_cert; } else { if (json_encode($last_issuer) === json_encode($parsed['subject'])) { $last_subject = $parsed['subject']; $last_issuer = $parsed['issuer']; } else { $last_issuer = null; $last_subject = null; break; } } } Assertion::false(null === $last_issuer || json_encode($last_issuer) !== json_encode($last_subject), 'Invalid certificate chain.'); return self::loadKeyFromCertificate($certificate); }
$a = fread($fp, 8192); fclose($fp); $b = "file://" . dirname(__FILE__) . "/cert.crt"; $c = "invalid cert"; $d = openssl_x509_read($a); $e = array(); $f = array($b); var_dump($res = openssl_x509_read($a)); // read cert as a string openssl_x509_free($res); var_dump($res); var_dump($res = openssl_x509_read($b)); // read cert as a filename string openssl_x509_free($res); var_dump($res); var_dump($res = openssl_x509_read($c)); // read an invalid cert, fails openssl_x509_free($res); var_dump($res); var_dump($res = openssl_x509_read($d)); // read cert from a resource openssl_x509_free($res); var_dump($res); var_dump($res = openssl_x509_read($e)); // read an array openssl_x509_free($res); var_dump($res); var_dump($res = openssl_x509_read($f)); // read an array with the filename openssl_x509_free($res); var_dump($res);
/** * Generate public/private keys and store in the config table * * Use the distinguished name provided to create a CSR, and then sign that CSR * with the same credentials. Store the keypair you create in the config table. * If a distinguished name is not provided, create one using the fullname of * 'the course with ID 1' as your organization name, and your hostname (as * detailed in $CFG->wwwroot). * * @param array $dn The distinguished name of the server * @return string The signature over that text */ private function generate_keypair() { $host = get_hostname_from_uri(get_config('wwwroot')); $organization = get_config('sitename'); $email = get_config('noreplyaddress'); $country = get_config('country'); $province = get_config('province'); $locality = get_config('locality'); //TODO: Create additional fields on site setup and read those from // config. Then remove the next 3 linez if (empty($country)) { $country = 'NZ'; } if (empty($province)) { $province = 'Wellington'; } if (empty($locality)) { $locality = 'Te Aro'; } $dn = array("countryName" => $country, "stateOrProvinceName" => $province, "localityName" => $locality, "organizationName" => $organization, "organizationalUnitName" => 'Mahara', "commonName" => get_config('wwwroot'), "emailAddress" => $email); // ensure we remove trailing slashes $dn["commonName"] = preg_replace(':/$:', '', $dn["commonName"]); $config = array(); $opensslcnf = get_config('opensslcnf'); if ($opensslcnf) { $config['config'] = $opensslcnf; } else { $config = null; } if (!($new_key = openssl_pkey_new($config))) { throw new ConfigException(get_string('errorcouldnotgeneratenewsslkey', 'auth')); } if (!($csr_rsc = openssl_csr_new($dn, $new_key, $config))) { // This behaviour has been observed once before, on an ubuntu hardy box. // The php5-openssl package was installed but somehow openssl // wasn't. throw new ConfigException(get_string('errorcouldnotgeneratenewsslkey', 'auth')); } $selfSignedCert = openssl_csr_sign($csr_rsc, null, $new_key, 365, $config); unset($csr_rsc); // Free up the resource // We export our self-signed certificate to a string. openssl_x509_export($selfSignedCert, $this->keypair['certificate']); openssl_x509_free($selfSignedCert); // Export your public/private key pair as a PEM encoded string. You // can protect it with an optional passphrase if you wish. $export = openssl_pkey_export($new_key, $this->keypair['keypair_PEM'], null, $config); openssl_pkey_free($new_key); unset($new_key); // Free up the resource // Calculate fingerprints $this->calculate_fingerprints(); return $this; }
/** * Generate public/private keys and store in the config table * * Use the distinguished name provided to create a CSR, and then sign that CSR * with the same credentials. Store the keypair you create in the config table. * If a distinguished name is not provided, create one using the fullname of * 'the course with ID 1' as your organization name, and your hostname (as * detailed in $CFG->wwwroot). * * @param array $dn The distinguished name of the server * @return string The signature over that text */ function mnet_generate_keypair($dn = null, $days = 28) { global $CFG, $USER, $DB; // check if lifetime has been overriden if (!empty($CFG->mnetkeylifetime)) { $days = $CFG->mnetkeylifetime; } $host = strtolower($CFG->wwwroot); $host = preg_replace("~^http(s)?://~", '', $host); $break = strpos($host . '/', '/'); $host = substr($host, 0, $break); $site = get_site(); $organization = $site->fullname; $keypair = array(); $country = 'NZ'; $province = 'Wellington'; $locality = 'Wellington'; $email = !empty($CFG->noreplyaddress) ? $CFG->noreplyaddress : 'noreply@' . $_SERVER['HTTP_HOST']; if (!empty($USER->country)) { $country = $USER->country; } if (!empty($USER->city)) { $province = $USER->city; $locality = $USER->city; } if (!empty($USER->email)) { $email = $USER->email; } if (is_null($dn)) { $dn = array("countryName" => $country, "stateOrProvinceName" => $province, "localityName" => $locality, "organizationName" => $organization, "organizationalUnitName" => 'Moodle', "commonName" => substr($CFG->wwwroot, 0, 64), "subjectAltName" => $CFG->wwwroot, "emailAddress" => $email); } // ensure we remove trailing slashes $dn["commonName"] = preg_replace(':/$:', '', $dn["commonName"]); $new_key = openssl_pkey_new(); if ($new_key === false) { // can not generate keys - missing openssl.cnf?? return null; } $csr_rsc = openssl_csr_new($dn, $new_key, array('private_key_bits', 2048)); $selfSignedCert = openssl_csr_sign($csr_rsc, null, $new_key, $days); unset($csr_rsc); // Free up the resource // We export our self-signed certificate to a string. openssl_x509_export($selfSignedCert, $keypair['certificate']); openssl_x509_free($selfSignedCert); // Export your public/private key pair as a PEM encoded string. You // can protect it with an optional passphrase if you wish. $export = openssl_pkey_export($new_key, $keypair['keypair_PEM']); openssl_pkey_free($new_key); unset($new_key); // Free up the resource return $keypair; }
/** * Returns the type of this certificate. For this implementation, the type * will be one of the OpenSSL certificate types: * <ul> * <li>OPENSSL_KEYTYPE_RSA,</li> * <li>OPENSSL_KEYTYPE_DSA,</li> * <li>OPENSSL_KEYTYPE_DH</li> * <li>OPENSSL_KEYTYPE_EC, or</li> * <li>-1, meaning unknown</li> * </ul> * * @return string the type of this certificate. */ public function getType() { $keyType = null; $certRes = openssl_x509_read($this->_rawCert); if ($certRes != false) { $keyRes = openssl_pkey_get_public($certRes); if ($keyRes != false) { $keyData = openssl_pkey_get_details($keyRes); if ($keyData != false) { $keyType = $keyData['type']; } } openssl_free_key($keyRes); } openssl_x509_free($certRes); return $keyType; }
/** * @fn string _load_signed_file(string $filename) * @brief A function which loads the data from SMIME siggned file. * * This function loads the data from SMIME (PKCS7) signed file, verify file sign for validity of * SmartPPC6 system. * * @param $filename a string which contains name of the SMIME signed file. * @return a string which contains contents of SMIME signed file if sign is valid and sign was made * with valid SmartPPC6 cerificate or FALSE on failures. */ function _load_signed_file($filename) { if (!file_exists($filename)) { return false; } // check CA certificate for validity of smartppc6 $x509 = $this->_load_CA(); if ($x509 === false) { return false; } openssl_x509_free($x509); // check signer certificate for validity of smartppc6 $x509 = $this->_load_cert(); if ($x509 === false) { return false; } openssl_x509_free($x509); $signer_cert_out = tempnam('/tmp', 'smartppc6'); $content_out = tempnam('/tmp', 'smartppc6'); $result_content = false; $phpversion = phpversion(); if (version_compare($phpversion, "5.1.0", "<")) { $cmd = sprintf('openssl smime -signer %s -verify -in %s -nointern -nochain -CAfile %s -certfile %s -out %s 2> /dev/null', escapeshellcmd($signer_cert_out), escapeshellcmd($filename), escapeshellcmd(SSL_CA_FILE), escapeshellcmd(SSL_CERT_FILE), escapeshellcmd($content_out)); system($cmd, $retval); if ($retval == 0) { $result = true; } } else { $result = openssl_pkcs7_verify($filename, PKCS7_NOVERIFY, $signer_cert_out, array(SSL_CA_FILE), SSL_CERT_FILE, $content_out); } if ($result === true) { $result_content = file_get_contents($content_out); } if (file_exists($signer_cert_out)) { unlink($signer_cert_out); } if (file_exists($content_out)) { unlink($content_out); } return $result_content; }
/** * Cleans SSL resources and calls parent's destructor * * @return void */ public function __destruct() { // Free cert resources if ($this->sslCert !== NULL) { @openssl_x509_free($this->sslCert); } unset($this->sslCert); $this->sslCert = NULL; $this->sslCertData = NULL; $this->sslCN = NULL; parent::__destruct(); }
/** * Automatic authentication: checks if the username is set in the * configured header. * * @return boolean Whether or not the client is allowed. */ public function transparent() { if (!is_callable('openssl_x509_parse')) { throw new Horde_Auth_Exception('SSL not enabled on server.'); } if (empty($_SERVER[$this->_params['username_field']]) || empty($_SERVER[$this->_params['certificate_field']])) { return false; } // Valid for client auth? $cert = openssl_x509_read($_SERVER[$this->_params['certificate_field']]); if (!$this->_params['ignore_purpose'] && !openssl_x509_checkpurpose($cert, X509_PURPOSE_SSL_CLIENT) && !openssl_x509_checkpurpose($cert, X509_PURPOSE_ANY)) { return false; } $c_parsed = openssl_x509_parse($cert); foreach ($this->_params['filter'] as $key => $value) { $keys = explode(':', $key); $c = $c_parsed; foreach ($keys as $k) { $c = $c[$k]; } if ($c != $value) { return false; } } // Handle any custom validation added by sub classes. if (!$this->_validate($cert)) { return false; } // Free resources. openssl_x509_free($cert); // Set credentials $this->setCredential('userId', $_SERVER[$this->_params['username_field']]); $cred = array('certificate_id' => $c_parsed['hash']); if (!empty($this->_params['password'])) { $cred['password'] = $this->_params['password']; } $this->setCredential('credentials', $cred); return true; }
/** * Verifies the signature of the document and that the signing certificate * stems from a trusted root CA. * * Returns the CN of the signing certificate if valid. * * @param str $xml XML doc to verify * @param str $signature_value Base64 encoded signature to verify against. * @returns str */ function verify($xml, $signature_value) { $doc = $this->parse_doc($xml); $xp = $this->get_xpath($doc); $certs = $this->parse_certificates($xp); if ($signature_value == null && empty($certs)) { // Doc unsigned and no signature expected return null; } $valid = $this->validate_xml($xp); $cert = openssl_x509_read($certs[0]); $parsed_certificate = openssl_x509_parse($cert); if ($pubkey = openssl_pkey_get_public($cert)) { $valid = openssl_verify($xml, base64_decode($signature_value), $pubkey); openssl_pkey_free($pubkey); openssl_x509_free($cert); $cert = null; $signed_by = null; if (!$valid) { throw new GApps_Discovery_Exception("Signature verification failed."); } } else { error_log('/lib/openid/Auth/OpenID/google_discovery.php: error getting certificate public key.'); } $trusted = $this->validate_chain($certs); if (!empty($cert)) { openssl_x509_free($cert); } if (!$trusted) { throw new GApps_Discovery_Exception("Can not verify trust chain."); } $subject = $parsed_certificate["subject"]; $signed_by = strtolower($subject["CN"]); return $signed_by; }
/** * @return bool */ protected function validateSslOptions() { // Get the contents. if (!is_readable($this->certPath)) { $this->stdErr->writeln("The certificate file could not be read: " . $this->certPath); return false; } $sslCert = trim(file_get_contents($this->certPath)); // Do a bit of validation. $certResource = openssl_x509_read($sslCert); if (!$certResource) { $this->stdErr->writeln("The certificate file is not a valid X509 certificate: " . $this->certPath); return false; } // Then the key. Does it match? if (!is_readable($this->keyPath)) { $this->stdErr->writeln("The private key file could not be read: " . $this->keyPath); return false; } $sslPrivateKey = trim(file_get_contents($this->keyPath)); $keyResource = openssl_pkey_get_private($sslPrivateKey); if (!$keyResource) { $this->stdErr->writeln("Private key not valid, or passphrase-protected: " . $this->keyPath); return false; } $keyMatch = openssl_x509_check_private_key($certResource, $keyResource); if (!$keyMatch) { $this->stdErr->writeln("The provided certificate does not match the provided private key."); return false; } // Each chain needs to contain one or more valid certificates. $chainFileContents = $this->readChainFiles($this->chainPaths); foreach ($chainFileContents as $filePath => $data) { $chainResource = openssl_x509_read($data); if (!$chainResource) { $this->stdErr->writeln("File contains an invalid X509 certificate: " . $filePath); return false; } openssl_x509_free($chainResource); } // Split up the chain file contents. $chain = array(); $begin = '-----BEGIN CERTIFICATE-----'; foreach ($chainFileContents as $data) { if (substr_count($data, $begin) > 1) { foreach (explode($begin, $data) as $cert) { $chain[] = $begin . $cert; } } else { $chain[] = $data; } } // Yay we win. $this->sslOptions = array('certificate' => $sslCert, 'key' => $sslPrivateKey, 'chain' => $chain); return true; }
function __destruct() { if ($this->publicKey) { openssl_x509_free($this->publicKey); } }
public function __destruct() { $handle = $this->getHandle(); if (!self::isCertificateResource($handle)) { return FALSE; } openssl_x509_free($handle); }