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;
 }
Example #2
0
 function checkPair($cert, $key, $passphrase = null)
 {
     if (openssl_pkey_get_private($key, $passphrase) === false) {
         return false;
     }
     return openssl_x509_check_private_key($cert, $key);
 }
Example #3
0
 function check_privatekey_match_certificate()
 {
     $this->clear_debug_buffer();
     $ok = openssl_x509_check_private_key($this->certificate_resource, $this->privatekey_resource);
     $this->debug("check_privatekey_match_certificate");
     return $ok;
 }
Example #4
0
 /**
  * Verify if SSL key and certificate match
  * @param $key
  * @param $cert
  * @return bool
  */
 public static function checkSSLKey($key, $cert)
 {
     if (openssl_x509_check_private_key(clean_input($cert), clean_input($key))) {
         return true;
     } else {
         return false;
     }
 }
 /**
  * @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 = [];
     $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 = ['certificate' => $sslCert, 'key' => $sslPrivateKey, 'chain' => $chain];
     return true;
 }
Example #6
0
 public static function curlContactCert($url, $key, $cert, $keypw = false, $postData = null)
 {
     if (is_null($key) || is_null($cert) || $key === "" || $cert === "") {
         throw new ConfusaGenException("Empty key or certificate received " . "when using curlContactCert(). " . "Aborting curl-transfer to url: {$url}");
     }
     if (is_null($postData) || !is_array($postData) || count($postData) == 0) {
         return false;
     }
     /* Do basic URL filtering */
     $curlurl = Input::sanitizeURL($url);
     if (is_null($curlurl) || $curlurl === "" || filter_var($curlurl, FILTER_VALIDATE_URL) === false) {
         Logger::log_event(LOG_NOTICE, "invalid URL (" . $curlurl . "), aborting curl-fetch.");
         return false;
     }
     Logger::log_event(LOG_DEBUG, "Contacting {$curlurl} using cert AuthN");
     /* key should be encrypted, if not, do not use it (not safe!) */
     $start = "-----BEGIN ENCRYPTED PRIVATE KEY-----";
     if (substr($key, 0, strlen($start)) !== $start) {
         Logger::log_event(LOG_NOTICE, "Trying to use curlContactCert with unecrypted private key, aborting.");
         return false;
     }
     $rkey = openssl_pkey_get_private($key, $keypw);
     if ($rkey === false) {
         Logger::log_event(LOG_NOTICE, "Could not parse private key for CurlContactCert, aborting");
         return false;
     }
     if (!openssl_x509_check_private_key($cert, $rkey)) {
         Logger::log_event(LOG_NOTICE, "Provided key and certificate is not a pair, cannot continue.");
         /* throw exception? */
         return false;
     }
     $rcert = new Certificate($cert);
     if (!$rcert->isValid()) {
         $logline = "Certificate (" . $rcert->getHash() . ") has expired, cannot use this. Aborting curl.";
         Logger::log_event(LOG_NOTICE, $logline);
         return false;
     }
     if (!file_exists("/tmp/" . $rcert->getHash() . ".key") || !file_exists("/tmp/" . $rcert->getHash() . ".crt")) {
         if (file_put_contents("/tmp/" . $rcert->getHash() . ".key", $key) === false) {
             Logger::log_event(LOG_NOTICE, "Could not write key to file");
         }
         if (file_put_contents("/tmp/" . $rcert->getHash() . ".crt", $cert) === false) {
             Logger::log_event(LOG_NOTICE, "Could not write cert to file");
         }
     }
     $options = array(CURLOPT_URL => $curlurl, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => 2, CURLOPT_SSLKEY => "/tmp/" . $rcert->getHash() . ".key", CURLOPT_SSLCERT => "/tmp/" . $rcert->getHash() . ".crt", CURLOPT_SSLKEYPASSWD => $keypw, CURLOPT_HEADER => false, CURLOPT_FOLLOWLOCATION => true, CURLOPT_RETURNTRANSFER => 1, CURLOPT_CONNECTTIMEOUT => 15);
     $channel = curl_init();
     curl_setopt_array($channel, $options);
     $data = curl_exec($channel);
     $status = curl_errno($channel);
     curl_close($channel);
     if ($status !== 0) {
         throw new ConfusaGenException("Could not connect properly to remote " . "endpoint {$curlurl} using cert-based authN! " . "Maybe the Confusa instance is misconfigured? " . "Please contact an administrator!");
     }
     return $data;
 }
 /**
  * esPaypalButton::setCertificate()
  *
  * @param mixed $certificateFilename - The path to the client certificate
  * @param mixed $privateKeyFilename - The path to the private key corresponding to the certificate
  * @return boolean TRUE if the private key matches the certificate.
  */
 public function setCertificate($certificateFilename, $privateKeyFilename)
 {
     if (is_readable($certificateFilename) && is_readable($privateKeyFilename)) {
         $certificate = openssl_x509_read(file_get_contents($certificateFilename));
         $privateKey = openssl_get_privatekey(file_get_contents($privateKeyFilename));
         if ($certificate !== FALSE && $privateKey !== FALSE && openssl_x509_check_private_key($certificate, $privateKey)) {
             $this->certificate = $certificate;
             $this->certificateFile = $certificateFilename;
             $this->privateKey = $privateKey;
             $this->privateKeyFile = $privateKeyFilename;
             return true;
         }
     }
     return false;
 }
Example #8
0
 /**
  * Set our public certificate and private key.
  *
  * @param  string $public_cert
  * @param  string $private_key
  * @return self
  */
 public function set_certificate($public_cert, $private_key)
 {
     // Parse the certificate
     $this->public_cert = openssl_x509_read($public_cert);
     // Parse our private key
     $this->private_key = openssl_get_privatekey($private_key);
     // Validate our certificate & private key
     if (!$this->public_cert || !$this->private_key) {
         throw new SecurityException('Invalid public certificate');
     }
     // Validate that our private key corresponds with our public certificate
     if (!openssl_x509_check_private_key($this->public_cert, $this->private_key)) {
         throw new SecurityException('Your private key does not correspond with your public certificate');
     }
     return $this;
 }
Example #9
0
 function encrypt($certificate_id)
 {
     # since this is a shared class, but certs are site-specific, go through include_paths to find realpath
     foreach (explode(':', ini_get('include_path')) as $path) {
         if (file_exists($path . '/paypal/paypal.cert')) {
             $public_file = realpath($path . '/paypal/public.cert');
             $private_file = realpath($path . '/paypal/private.cert');
             $paypal_file = realpath($path . '/paypal/paypal.cert');
             $public_cert = openssl_x509_read(file_get_contents($public_file));
             $private_cert = openssl_get_privatekey(file_get_contents($private_file));
             if (openssl_x509_check_private_key($public_cert, $private_cert) === false) {
                 return false;
             }
             $paypal_cert = openssl_x509_read(file_get_contents($paypal_file));
             break;
         }
     }
     $clear_text = 'cert_id=' . $certificate_id;
     foreach ($this->postvars() as $k => $v) {
         $clear_text .= "\n" . $k . '=' . $v;
     }
     $clear_file = tempnam('/tmp/', 'clear_');
     # alt: sys_get_temp_dir()
     $signed_file = preg_replace('/clear/', 'signed', $clear_file);
     $encrypted_file = preg_replace('/clear/', 'encrypted', $clear_file);
     file_put_contents($clear_file, $clear_text);
     if (!openssl_pkcs7_sign($clear_file, $signed_file, $public_cert, $private_cert, array(), PKCS7_BINARY)) {
         return false;
     }
     list($x, $signed_text) = explode("\n\n", file_get_contents($signed_file));
     #?
     file_put_contents($signed_file, base64_decode($signed_text));
     if (!openssl_pkcs7_encrypt($signed_file, $encrypted_file, $paypal_cert, array(), PKCS7_BINARY)) {
         return false;
     }
     list($x, $encrypted_text) = explode("\n\n", file_get_contents($encrypted_file));
     #?
     $this->encrypted = "\n-----BEGIN PKCS7-----\n{$encrypted_text}\n-----END PKCS7-----\n";
     @unlink($clear_file);
     @unlink($signed_file);
     @unlink($encrypted_file);
 }
Example #10
0
function update_ssl_data()
{
    // Get a reference to the Config object
    $cfg = EasySCP_Registry::get('Config');
    // Gets a reference to the EasySCP_ConfigHandler_Db instance
    $db_cfg = EasySCP_Registry::get('Db_Config');
    $db_cfg->resetQueriesCounter('update');
    $sslkey = clean_input(filter_input(INPUT_POST, 'ssl_key'));
    $sslcert = clean_input(filter_input(INPUT_POST, 'ssl_cert'));
    $sslcacert = clean_input(filter_input(INPUT_POST, 'ssl_cacert'));
    $sslstatus = clean_input(filter_input(INPUT_POST, 'ssl_status'));
    if (openssl_x509_check_private_key($sslcert, $sslkey)) {
        // update the ssl related values
        $db_cfg->SSL_KEY = $sslkey;
        $db_cfg->SSL_CERT = $sslcert;
        $db_cfg->SSL_CACERT = $sslcacert;
        $db_cfg->SSL_STATUS = $sslstatus;
        $cfg->replaceWith($db_cfg);
        /*
        $data = array (
        	'SSL_KEY'	=> $sslkey,
        	'SSL_CERT'	=> $sslcert,
        	'SSL_STATUS'=> $sslstatus
        );
        */
        $data = array('SSL_STATUS' => $sslstatus);
        EasyConfig::Save($data);
        write_log(get_session('user_logged') . ": Updated SSL configuration!");
        // get number of updates
        $update_count = $db_cfg->countQueries('update');
        if ($update_count == 0) {
            set_page_message(tr("SSL configuration unchanged"), 'info');
        } elseif ($update_count > 0) {
            set_page_message(tr('SSL configuration updated!'), 'success');
        }
    } else {
        set_page_message(tr("SSL key/cert don't match"), 'Warning');
        write_log(get_session('user_logged') . ": Update of SSL configuration failed!");
    }
    send_request('110 DOMAIN master');
    user_goto('tools_config_ssl.php');
}
Example #11
0
 /**
  * Set the client certificate and private key pair.
  *
  * @param string $certificateFilename The path to the client certificate
  * @param string $privateKeyFilename The path to the private key corresponding to the certificate
  * @return bool TRUE if the private key matches the certificate.
  */
 public function setCertificate($certificateFilename, $privateKeyFilename)
 {
     $result = false;
     if (is_readable($certificateFilename) && is_readable($privateKeyFilename)) {
         $certificate = null;
         $handle = fopen($certificateFilename, "r");
         $size = filesize($certificateFilename);
         $certificate = fread($handle, $size);
         fclose($handle);
         $privateKey = null;
         $handle = fopen($privateKeyFilename, "r");
         $size = filesize($privateKeyFilename);
         $privateKey = fread($handle, $size);
         fclose($handle);
         if ($certificate !== false && $privateKey !== false && openssl_x509_check_private_key($certificate, $privateKey)) {
             $this->certificate = $certificate;
             $this->certificateFile = $certificateFilename;
             $this->privateKey = $privateKey;
             $this->privateKeyFile = $privateKeyFilename;
             $result = true;
         }
     }
     return $result;
 }
Example #12
0
 /**
  *   Create encrypted buttons.
  *
  *   Requires that the plugin is configured to do so, and that the key files
  *   are set up correctly.  If an error is encountered, an empty string
  *   is returned so the caller can proceed with an un-encrypted button.
  *
  *   @since  version 0.4.0
  *   @param  array   $fields     Array of data to encrypt into buttons
  *   @return string              Encrypted_value, or empty string on error
  */
 private function _encButton($fields)
 {
     global $_CONF, $_PP_CONF;
     // Make sure button encryption is enabled and needed values are set
     if ($this->config['encrypt'] != 1 || empty($this->config['prv_key']) || empty($this->config['pub_key']) || empty($this->config['pp_cert']) || $this->cert_id == '') {
         return '';
     }
     // Now check that the files exist and can be read
     foreach (array('prv_key', 'pub_key', 'pp_cert') as $idx => $name) {
         if (!is_file($this->config[$name]) || !is_readable($this->config[$name])) {
             return '';
         }
     }
     // Create a temporary file to begin storing our data.  If this fails,
     // then return.
     $dataFile = tempnam($_PP_CONF['tmpdir'], 'data');
     if (!is_writable($dataFile)) {
         return '';
     }
     $plainText = '';
     $signedText = array();
     $encText = '';
     $pub_key = @openssl_x509_read(file_get_contents($this->config['pub_key']));
     if (!$pub_key) {
         COM_errorLog("Failed reading public key from {$this->config['pub_key']}", 1);
         return '';
     }
     $prv_key = @openssl_get_privatekey(file_get_contents($this->config['prv_key']));
     if (!$prv_key) {
         COM_errorLog("Failed reading private key from {$this->config['prv_key']}", 1);
         return '';
     }
     $pp_cert = @openssl_x509_read(file_get_contents($this->config['pp_cert']));
     if (!$pp_cert) {
         COM_errorLog("Failed reading PayPal certificate from {$this->config['pp_cert']}", 1);
         return '';
     }
     //  Make sure this key and certificate belong together
     if (!openssl_x509_check_private_key($pub_key, $prv_key)) {
         COM_errorLog("Mismatched private & public keys", 1);
         return '';
     }
     //  Start off the form data with the PayPal certificate ID
     $plainText .= "cert_id=" . $this->cert_id;
     //  Create the form data by separating each value set by a new line
     //  Make sure that required fields are available.  We assume that the
     //  item_number, item_name and amount are in.
     if (!isset($fields['business'])) {
         $fields['business'] = $this->receiver_email;
     }
     if (!isset($fields['currency_code'])) {
         $fields['currency_code'] = $this->currency_code;
     }
     foreach ($fields as $key => $value) {
         $plainText .= "\n{$key}={$value}";
     }
     //  First create a file for storing the plain text values
     $fh = fopen($dataFile . '_plain.txt', 'wb');
     if ($fh) {
         fwrite($fh, $plainText);
     } else {
         return '';
     }
     @fclose($fh);
     // Now sign the plaintext values into the signed file
     //$fh = fopen($dataFile . "_signed.txt", "w+");
     if (!openssl_pkcs7_sign($dataFile . '_plain.txt', $dataFile . '_signed.txt', $pub_key, $prv_key, array(), PKCS7_BINARY)) {
         return '';
     }
     //  Parse the signed file between the header and content
     $signedText = explode("\n\n", file_get_contents($dataFile . '_signed.txt'));
     //  Save only the content but base64 decode it first
     $fh = fopen($dataFile . '_signed.txt', 'wb');
     if ($fh) {
         fwrite($fh, base64_decode($signedText[1]));
     } else {
         return '';
     }
     @fclose($fh);
     // Now encrypt the signed file we just wrote
     if (!openssl_pkcs7_encrypt($dataFile . '_signed.txt', $dataFile . '_enc.txt', $pp_cert, array(), PKCS7_BINARY)) {
         return '';
     }
     // Parse the encrypted file between header and content
     $encryptedData = explode("\n\n", file_get_contents($dataFile . "_enc.txt"));
     $encText = $encryptedData[1];
     // Delete all of our temporary files
     @unlink($dataFile);
     @unlink($dataFile . "_plain.txt");
     @unlink($dataFile . "_signed.txt");
     @unlink($dataFile . "_enc.txt");
     //  Return the now-encrypted form content
     return "-----BEGIN PKCS7-----\n" . $encText . "\n-----END PKCS7-----";
 }
Example #13
0
 /**
  * Import a server cert
  * @param string $cert - PEM encoded certificate - required
  * @param string $privKey - PEM encoded private key - optional
  * @param string $passPhrase - optional
  * @param string $certRequest - PEM encoded CSR - optional
  * @return bool true on success
  * @return string error message on failures
  */
 public function actionServerImport($pemCert = null, $privKey = null, $passPhrase = null, $certRequest = null)
 {
     $this->moduleRequired('ca,cert,server');
     // check arguments
     if (!is_string($pemCert) or strlen($pemCert) < 1) {
         return 'Must provide a valid PEM encoded CA certificate.';
     }
     // normalize arguments
     $privKey = (is_string($privKey) and strlen($privKey) > 0) ? $privKey : false;
     $passPhrase = (is_string($passPhrase) and strlen($passPhrase) > 0) ? $passPhrase : '';
     $certRequest = (is_string($certRequest) and strlen($certRequest) > 0) ? $certRequest : false;
     // parse the cert
     $pc = $this->cert->parseCert($pemCert);
     if (!is_array($pc)) {
         return 'Failed to parse certificate.';
     }
     $rc = $this->server->meetsImportRequirements($pc);
     if (!($rc === true)) {
         return 'Cert does not meet import requirements: ' . $rc;
     }
     // no self-signed certs
     $isSelfSigned = $this->cert->isCertSigner($pemCert, $pemCert);
     if ($isSelfSigned === true) {
         return 'Will not import self-signed certificates.';
     }
     $rc = $this->cert->parsedCertIsSslServer($pc);
     if (!($rc === true)) {
         return 'The specified cert is not a SSL server certificate.';
     }
     if (!is_numeric($pc['certificate']['serialNumber'])) {
         return 'Invalid certificate serial number.';
     } else {
         $serialNumber = $pc['certificate']['serialNumber'];
     }
     $validFrom = gmdate('Y-m-d H:i:s', $pc['certificate']['validity']['notbefore']);
     if ($validFrom === false) {
         return 'Failed to determine validFrom date.';
     }
     $validTo = gmdate('Y-m-d H:i:s', $pc['certificate']['validity']['notafter']);
     if ($validTo === false) {
         return 'Failed to determine validTo date.';
     }
     // extract needed public key objects
     $pubKeyRes = openssl_pkey_get_public($pemCert);
     if ($pubKeyRes === false) {
         return 'Failed to extract public key.';
     }
     $ar = openssl_pkey_get_details($pubKeyRes);
     if (!is_array($ar) or !isset($ar['key'])) {
         return 'Failed to obtain PEM formatted public key.';
     } else {
         $pubKey = $ar['key'];
     }
     // Locate issuer
     $ca = $this->getSignerId($pemCert);
     if (!is_array($ca) or count($ca) < 1) {
         $issuer = $pc['certificate']['issuer'];
         $m = 'The CA cert that signed this certificate could not be ' . 'located.  Import the CA Certificate that matches the ' . 'information listed below and try again.';
         $out = print_r($issuer, true);
         $m .= '<P><PRE>' . $out . '</PRE></P>';
         return $m;
     }
     if (count($ca) > 1) {
         $m = 'This certificate cannot be imported because multiple possible ' . 'signers exist.';
         return $m;
     }
     $caId = isset($ca[0]['Id']) ? $ca[0]['Id'] : false;
     if (!is_numeric($caId) or $caId < 1) {
         return 'Failed to locate issuing CA id.';
     }
     // Validate expiration date of CA cert.  Only warn if the expiration dates
     // don't jive.
     $this->ca->resetProperties();
     if ($this->ca->populateFromDb($caId) === false) {
         return 'Failed to locate issuer information.';
     }
     $caValidTo = $this->ca->getProperty('ValidTo');
     if (substr($validTo, 0, 10) > substr($caValidTo, 0, 10)) {
         $m = 'WARNING: The certificate expiration date is invalid, the issuer ' . 'certficate expires ' . $caValidTo . ', this certificate expires ' . $validTo . '.';
         $this->html->errorMsgSet($m);
     }
     // Determine the last serial number issued by the ca in case the
     // serial number of the current certificate is higher and we need
     // to bump the ca last serial issued.
     $caLastSerial = $this->ca->getLastSerialIssued($caId);
     if ($caLastSerial === false or !is_numeric($caLastSerial)) {
         return 'Failed to determine CA last serial issued.';
     }
     // Validate the private key
     if (is_string($privKey)) {
         $pKey = openssl_pkey_get_private($privKey, $passPhrase);
         if ($pKey === false) {
             return 'Private key or password is invalid.';
         }
         if (!openssl_x509_check_private_key($pemCert, $pKey)) {
             return 'Private key does not belong to cert.';
         }
     }
     // Did they include a csr?
     if (is_string($certRequest)) {
         $csrPubKey = openssl_csr_get_public_key($certRequest);
         if ($csrPubKey === false) {
             return 'Failed to extract public key from CSR.';
         }
         if (openssl_pkey_get_details($pubKeyRes) !== openssl_pkey_get_details($csrPubKey)) {
             return 'CSR and cert do not match.';
         }
     }
     // Import the cert into the database
     $this->server->resetProperties();
     // required properties
     $this->server->setProperty('Certificate', $pemCert);
     $this->server->setProperty('CommonName', implode("\n", $pc['certificate']['subject']['CommonName']));
     $this->server->setProperty('CreateDate', 'now()');
     $this->server->setProperty('Description', 'imported');
     $this->server->setProperty('FingerprintMD5', $pc['fingerprints']['md5']);
     $this->server->setProperty('FingerprintSHA1', $pc['fingerprints']['sha1']);
     $this->server->setProperty('ParentId', $caId);
     $this->server->setProperty('PrivateKey', $privKey);
     $this->server->setProperty('PublicKey', $pubKey);
     $this->server->setProperty('SerialNumber', $serialNumber);
     $this->server->setProperty('ValidFrom', $validFrom);
     $this->server->setProperty('ValidTo', $validTo);
     // optional properties
     if (is_string($certRequest)) {
         $this->server->setProperty('CSR', $certRequest);
     }
     // optional subject properties
     $sub = $pc['certificate']['subject'];
     if (isset($sub['Country'])) {
         $val = $sub['Country'];
         if (is_array($val) and count($val) > 0) {
             $this->server->setProperty('CountryName', implode("\n", $val));
         }
     }
     if (isset($sub['emailAddress'])) {
         $val = $sub['emailAddress'];
         if (is_array($val) and count($val) > 0) {
             $this->server->setProperty('EmailAddress', implode("\n", $val));
         }
     }
     if (isset($sub['Location'])) {
         $val = $sub['Location'];
         if (is_array($val) and count($val) > 0) {
             $this->server->setProperty('LocalityName', implode("\n", $val));
         }
     }
     if (isset($sub['Organization'])) {
         $val = $sub['Organization'];
         if (is_array($val) and count($val) > 0) {
             $this->server->setProperty('OrgName', implode("\n", $val));
         }
     }
     if (isset($sub['OrganizationalUnit'])) {
         $val = $sub['OrganizationalUnit'];
         if (is_array($val) and count($val) > 0) {
             $this->server->setProperty('OrgUnitName', implode("\n", $val));
         }
     }
     if (isset($sub['stateOrProvinceName'])) {
         $val = $sub['stateOrProvinceName'];
         if (is_array($val) and count($val) > 0) {
             $this->server->setProperty('StateName', implode("\n", $val));
         }
     }
     // Do the deed...
     $this->server->populated = true;
     $rc = $this->server->add();
     if (!($rc === true)) {
         return 'Import Failed: ' . $rc;
     }
     // Do we need to bump the CA's last serial issued?
     if ($serialNumber > $caLastSerial) {
         if (!($this->ca->updateSerialByCaId($caId, $serialNumber) === true)) {
             return $m;
         }
     }
     return true;
 }
Example #14
0
  </tr>
  <tr>
    <th scope="row">&nbsp;</th>
    <td>
      <input type="checkbox" name="auto_cert" value="auto_cert" onclick="jQuery('.manual_cert').toggle('300');"/>&nbsp;&nbsp;Generate a new certificate and private key for me<br/>
    </td>
  </tr>
  <tr valign="top" class="manual_cert">
    <th scope="row"><label for="certificate">Signing Certificate</label></th>
    <?php 
if (file_exists(constant('SAMLAUTH_CONF') . '/certs/' . get_current_blog_id() . '/' . get_current_blog_id() . '.cer') && file_exists(constant('SAMLAUTH_CONF') . '/certs/' . get_current_blog_id() . '/' . get_current_blog_id() . '.key')) {
    $certificate = file_get_contents(constant('SAMLAUTH_CONF') . '/certs/' . get_current_blog_id() . '/' . get_current_blog_id() . '.cer');
    $certificate_cn = openssl_x509_parse($certificate);
    $certificate_cn = $certificate_cn['subject']['CN'];
    $privatekey = file_get_contents(constant('SAMLAUTH_CONF') . '/certs/' . get_current_blog_id() . '/' . get_current_blog_id() . '.key');
    $privatekey_match = openssl_x509_check_private_key($certificate, $privatekey);
} else {
    $certificate = false;
    $privatekey = false;
    $privatekey_match = false;
}
?>
    <td><input type="file" name="certificate" id="certificate" /><?php 
if ($certificate !== false) {
    echo '&nbsp;<span class="green">Using certificate: <strong>' . $certificate_cn . '</strong>.</span> <a href="' . constant('SAMLAUTH_CONF_URL') . '/certs/' . get_current_blog_id() . '/' . get_current_blog_id() . '.cer' . '" target="_blank">[download]</a>';
}
?>
    <br/>
    <span class="setting-description">This doesn't have to be the certificate used to secure your website, it can just be self-signed.</span>
    </td>
  </tr>
Example #15
0
function check_pair($cert, $priv)
{
    $msg = openssl_x509_check_private_key($cert, $priv) ? '+Ok, Match' : '-Err, Not Match';
    echo $msg . "\n\n";
}
	/**
	 * Encrypts and signs the request to paypal
	 *
	 * To generate a keypair:
	 * openssl genrsa -des3 -out privkey.pem 2048
	 * openssl req -new -x509 -key privkey.pem -out cacert.pem -days 3650
	 * 
	 * To encrypt and sign (that's what we do here):
	 * openssl smime -sign -signer cacert.pem -inkey privkey.pem -outform der -nodetach -binary -passin pass:1234 | openssl smime -encrypt -des3 -binary -outform pem paypal_cert_pem.txt
	 *
	 * @param  string        $cleartext  Cleartext to encrypt and sign
	 * @return string                    Encrypted text or FALSE
	 */
	private function _paypalEncrypt( $cleartext )
	{
		$return							=	false;

		$paypal_openssl_path			=	$this->params->get( 'openssl_exec_path', '/usr/bin/openssl' );
		$paypal_public_certificate_path	=	$this->getAccountParam( 'paypal_public_certificate_path' );
		$paypal_private_key_path		=	$this->getAccountParam( 'paypal_private_key_path' );
		$paypal_public_key_path			=	$this->getAccountParam( 'paypal_public_key_path' );
		$paypal_private_key_password	=	$this->getAccountParam( 'paypal_private_key_password' );

		$tmpDir							=	$this->findATmpDir();
		if ( ( $tmpDir === null ) || ( ! is_dir( $tmpDir ) ) || ! is_writable( $tmpDir ) ) {
			$this->_setLogErrorMSG( 3, $this->account, 'paypal openssl', 'did not find a writable temporary directory (' . $tmpDir . '). Please make sure that your cachepath global CMS setting is a writable directory.' );
			$tmpDir						=	null;
		}

		$h = @getenv('HOME') . "\n";
		if ( ! is_writable( $h ) ) {
			@putenv("HOME=/tmp");		// try avoiding unable to write 'random state'		( http://www.paypaldeveloper.com/pdn/board/message?board.id=ewp&thread.id=110&view=by_date_ascending&page=2 )
		} else {
			$h			=	null;
		}

		if ( extension_loaded( 'openssl' ) && defined( 'OPENSSL_VERSION_TEXT' ) && ( $tmpDir !== null ) ) {

			$clearFile					=	tempnam($tmpDir, 'clr_');
			$signedFile					=	tempnam($tmpDir, 'sign_');
			$encryptedFile				=	tempnam($tmpDir, 'encr_');

			if ( is_readable( $paypal_public_key_path ) && is_readable( $paypal_private_key_path ) && is_readable( $paypal_public_certificate_path ) ) {
				$certificate			=	openssl_x509_read( file_get_contents( $paypal_public_key_path ) );
				$privateKey				=	openssl_pkey_get_private( file_get_contents( $paypal_private_key_path ), $paypal_private_key_password );
				$paypalcert				=	openssl_x509_read( file_get_contents( $paypal_public_certificate_path ) );
				if ( ( $certificate !== false ) && ( $privateKey !== false ) && ( $paypalcert !== false ) ) {
					$privOk				=	openssl_x509_check_private_key( $certificate, $privateKey );
					if ( $privOk ) {
						$out			=	fopen( $clearFile, 'wb' );
						if ( $out !== false ) {
							fwrite( $out, $cleartext );
							fclose( $out );
	
							if ( openssl_pkcs7_sign( $clearFile, $signedFile, $certificate, $privateKey, array(), PKCS7_BINARY ) ) {
								@unlink( $clearFile );
			
								$signedData		=	explode( "\n\n", file_get_contents( $signedFile ) );
				
								$out			=	fopen($signedFile, 'wb');
								if ( $out !== false ) {
									fwrite( $out, base64_decode( $signedData[1] ) );
									fclose( $out );
				
									if ( openssl_pkcs7_encrypt( $signedFile, $encryptedFile, $paypalcert, array(), PKCS7_BINARY ) ) {
										@unlink( $signedFile );
										$encryptedData	=	explode("\n\n", file_get_contents( $encryptedFile ), 2 );
										@unlink( $encryptedFile );

										$return	=	"-----BEGIN PKCS7-----\n"
												.	trim( $encryptedData[1] )
												.	"\n-----END PKCS7-----";
									} else {
										$this->_setLogErrorMSG( 3, $this->account, 'paypal openssl_pkcs7_encrypt(signedFile,paypal_public_cer) ', 'returns an error on signature.' );
									}
								} else {
									$this->_setLogErrorMSG( 3, $this->account, 'paypal openssl open ', $signedFile . ' returns an error creating it.' );
								}
							} else {
								$this->_setLogErrorMSG( 3, $this->account, 'paypal openssl_pkcs7_sign(message,your_private_key)', 'returns an error.' );
							}
						} else {
							$this->_setLogErrorMSG( 3, $this->account, 'paypal openssl open ', $clearFile . ' returns an error creating it.' );
						}	
					} else {
						$this->_setLogErrorMSG( 3, $this->account, 'paypal openssl_pkcs7_sign(message,your_private_key)', 'returns an error.' );
					}
				} else {
					if ( $certificate === false ) {
						$this->_setLogErrorMSG( 3, $this->account, 'paypal openssl_x509_read(your_public_key)', 'returns an error.' );
					}
					if ( $privateKey === false ) {
						$this->_setLogErrorMSG( 3, $this->account, 'paypal openssl_pkey_get_private(your_private_key)', 'returns an error. Maybe wrong password for private key ?' );
					}
					if ( $paypalcert === false ) {
						$this->_setLogErrorMSG( 3, $this->account, 'paypal openssl_x509_read(paypal_public_certificate)', 'returns an error.' );
					}
				}
			} else {
				$this->_setLogErrorMSG( 3, $this->account, 'paypal openssl tempnam()', 'returns unwritable filepaths (' . $clearFile . ')' );
			}

		}
		if ( $return === false ) {
			if ( function_exists( 'is_executable' ) ) {
				$configPath	=	$this->params->get( 'openssl_exec_path', '/usr/bin/openssl' );
				$paths = array( '/usr/bin/openssl', '/usr/local/bin/openssl', 'openssl' );
				if ( $configPath ) {
					array_unshift( $paths, $configPath );
				}
				foreach ($paths as $path) {
					if ( @is_executable( $path ) ) {
						// openssl found:
						$paypal_openssl_path	=	$path;
						break;
					}
				}
			}

			if ( @is_executable( $paypal_openssl_path ) ) {

				$openssl_cmd	=	$paypal_openssl_path . ' smime -sign -signer ' .$paypal_public_key_path
								.	' -inkey ' . $paypal_private_key_path
								.	' -outform der -nodetach -binary -passin pass:'******' | '
								.	$paypal_openssl_path . ' smime -encrypt -des3 -binary -outform pem ' . $paypal_public_certificate_path;

				$descriptors	=	array(	0 => array('pipe', 'r'),
											1 => array('pipe', 'w'),
											2 => array('pipe', 'w') );

				$pipes			=	null;
				$process		=	@proc_open( $openssl_cmd, $descriptors, $pipes );				// PHP 4.3.0 required for paypal encryption !

				if (is_resource($process)) {
					@fwrite( $pipes[0], $cleartext );
					@fflush( $pipes[0] );
					@fclose( $pipes[0] );
		
					$output		=	'';
					while ( ! feof( $pipes[1] ) ) {
						$output	.=	@fgets( $pipes[1] );
					}
					$error		=	'';
					while ( ! feof( $pipes[2] ) ) {
						$error	.=	@fgets( $pipes[2] );
					}
					$error		=	trim( $error );
	
					@fclose( $pipes[1] );
					@fclose( $pipes[2] );
					@proc_close( $process );
					
					if ( $error ) {
						$this->_setLogErrorMSG( 3, $this->account, 'paypal openssl executable error', $error );
					}
					$return		=	trim( $output );
				} else {
					$this->_setLogErrorMSG( 5, $this->account, 'paypal openssl executable', 'could not start with proc_open' );
				}
			}
		}

		if ( $h ) {
			@putenv( "HOME=" . $h );
		}
		return $return;
	}
Example #17
0
 /**
  * Set the client certificate and private key pair.
  *
  * @param string $certificateFilename The path to the client
  * (public) certificate
  * @param string $privateKeyFilename The path to the private key
  * corresponding to the certificate
  * @return bool TRUE if the private key matches the certificate,
  * FALSE otherwise
  */
 function setCertificate($certificateFilename, $privateKeyFilename)
 {
     if (is_readable($certificateFilename) and is_readable($privateKeyFilename)) {
         $handle = fopen($certificateFilename, "r");
         if ($handle === false) {
             return false;
         }
         $size = filesize($certificateFilename);
         $certificate = fread($handle, $size);
         @fclose($handle);
         unset($handle);
         $handle = fopen($privateKeyFilename, "r");
         if ($handle === false) {
             return false;
         }
         $size = filesize($privateKeyFilename);
         $privateKey = fread($handle, $size);
         @fclose($handle);
         if ($certificate !== false and $privateKey !== false and openssl_x509_check_private_key($certificate, $privateKey)) {
             $this->certificate = $certificate;
             $this->certificateFile = $certificateFilename;
             $this->privateKey = $privateKey;
             $this->privateKeyFile = $privateKeyFilename;
             return true;
         }
     } else {
         $this->error = 2;
         return false;
     }
 }
Example #18
0
/**
 * 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.');
    }
}
Example #19
0
<?php

$fp = fopen(dirname(__FILE__) . "/cert.crt", "r");
$a = fread($fp, 8192);
fclose($fp);
$fp = fopen(dirname(__FILE__) . "/private.key", "r");
$b = fread($fp, 8192);
fclose($fp);
$cert = "file://" . dirname(__FILE__) . "/cert.crt";
$key = "file://" . dirname(__FILE__) . "/private.key";
var_dump(openssl_x509_check_private_key($cert, $key));
var_dump(openssl_x509_check_private_key("", $key));
var_dump(openssl_x509_check_private_key($cert, ""));
var_dump(openssl_x509_check_private_key("", ""));
var_dump(openssl_x509_check_private_key($a, $b));
/**
 * Hook a ejecutar antes del paso 7 de la instalación
 *
 * @param array &$data  Los datos a utilizar por las plantillas de tipo stepn
 */
function idpinstaller_hook_step7(&$data)
{
    $hostname = $_SERVER['HTTP_HOST'];
    $pkey_file = $hostname . ".key.pem";
    $cert_file = $hostname . ".crt.pem";
    $new_certificate = isset($_REQUEST['organization_name']) && !empty($_REQUEST['organization_name']);
    $old_certificate = isset($_REQUEST['private_key']) && !empty($_REQUEST['private_key']) && isset($_REQUEST['certificate']) && !empty($_REQUEST['certificate']);
    if ($new_certificate || $old_certificate) {
        $dir_certs = realpath(__DIR__ . "/../../../") . "/cert";
        $org_name = $_REQUEST['organization_name'];
        $crt = $dir_certs . "/" . $cert_file;
        $pem = $dir_certs . "/" . $pkey_file;
        if (!file_exists($dir_certs) && !is_writable($dir_certs . "/../")) {
            $data['errors'][] = $data['ssphpobj']->t('{idpinstaller:idpinstaller:step6_mkdir_cert_error}');
            $data['errors'][] = "<pre>&gt; mkdir {$dir_certs}</pre>";
            return true;
        } else {
            if (!is_dir($dir_certs)) {
                exec("mkdir {$dir_certs}");
            } else {
                if (!is_writable($dir_certs)) {
                    $username = getFileUsername($dir_certs);
                    $groupname = getApacheGroup();
                    $data['errors'][] = $data['ssphpobj']->t('{idpinstaller:idpinstaller:step6_perm_cert_error}');
                    $data['errors'][] = "<pre>&gt; chown -R " . $username . ":" . $groupname . " {$dir_certs}\n&gt; chmod -R g+w " . $dir_certs . "</pre>";
                    return true;
                }
            }
        }
        if ($old_certificate) {
            $priv_key = $_REQUEST['certificate'];
            $cert = $_REQUEST['private_key'];
            if (openssl_x509_check_private_key($cert, $priv_key)) {
                $a1 = openssl_pkey_get_public($cert);
                if ($a1 != null) {
                    $details = openssl_pkey_get_details($a1);
                    if (is_array($details) && array_key_exists("type", $details) && $details["type"] == OPENSSL_KEYTYPE_RSA) {
                        $x = @file_put_contents($pem, $priv_key);
                        $y = @file_put_contents($crt, $cert);
                        if ($x === false || $y === false) {
                            $data['errors'][] = $data['ssphpobj']->t('{idpinstaller:idpinstaller:step6_cert_error}');
                            return true;
                        }
                    } else {
                        $data['errors'][] = $data['ssphpobj']->t('{idpinstaller:idpinstaller:step6_cert_rsa_error}');
                        return true;
                    }
                } else {
                    $data['errors'][] = $data['ssphpobj']->t('{idpinstaller:idpinstaller:step6_cert_rsa_error}');
                    return true;
                }
            } else {
                $data['errors'][] = $data['ssphpobj']->t('{idpinstaller:idpinstaller:step6_cert_error_comparation}');
                return true;
            }
        } else {
            $o_name = str_replace(" ", "\\ ", $org_name);
            $dir_script = realpath(__DIR__) . "/../lib/makeCert.sh";
            //exec("sh $dir_script $dir_certs/$cert_file $pkey_file $o_name $hostname");
            /* Este tratamiento es un poco confuso, pero es la mejor de
             * invocar una  llamada a sistema sin perder el control en PHP
             */
            $cmdToExecute = $dir_script;
            // Ruta al shell script
            $cmdToExecute .= ' ' . $dir_certs . '/' . $cert_file;
            // Ruta absoluta para el certificado a generar
            $cmdToExecute .= ' ' . $dir_certs . '/' . $pkey_file;
            // Ruta absoluta para la clave privada a generar
            $cmdToExecute .= ' ' . $o_name;
            // Nombre de la organización, a utilizar en el RDN O
            $cmdToExecute .= ' ' . $hostname;
            // Nombre del host a utilizar en los RDN DC y CN
            //list($respStdout, $respStderr, $outCode) = execInShell($cmdToExecute, NULL); // Si, el uso del constructor del leguaje list() es un aguarrería pero queda muy descriptivo
            $result = array();
            $result = execInShell($cmdToExecute, NULL);
            $respStdout = $result[0];
            // <= STDOUT
            $respStderr = $result[1];
            // <= STDERR
            $outCode = $result[2];
            // <= Out Code
            // Se procesan los mensajes de salida de errores
            if ($outCode !== 0) {
                $data['errors'][] = $data['ssphpobj']->t('{idpinstaller:idpinstaller:step7_command_error}') . '</br></br><pre>' . $respStderr . '</pre>';
            }
        }
        if (!file_exists($crt) || !file_exists($pem)) {
            $username = getFileUsername($dir_certs);
            $groupname = getApacheGroup();
            $data['errors'][] = $data['ssphpobj']->t('{idpinstaller:idpinstaller:step6_cert_error}');
            if (isset($command)) {
                $data['errors'][] = $data['ssphpobj']->t('{idpinstaller:idpinstaller:step6_cert_error_suggest}');
                $data['errors'][] = $command;
                return true;
            }
        }
        $filename = __DIR__ . '/../../../config/config.php';
        include $filename;
        $config['metadata.sign.enable'] = TRUE;
        $config['metadata.sign.privatekey'] = $pkey_file;
        $config['metadata.sign.privatekey_pass'] = NULL;
        $config['metadata.sign.certificate'] = $cert_file;
        $res = @file_put_contents($filename, '<?php  $config = ' . var_export($config, 1) . "; ?>");
        if (!$res) {
            $data['errors'][] = $data['ssphpobj']->t('{idpinstaller:idpinstaller:step2_contact_save_error}');
            $data['errors'][] = $data['ssphpobj']->t('{idpinstaller:idpinstaller:step2_contact_save_error2}') . " <i>" . realpath($filename) . "</i>";
            return true;
        }
    } else {
        if (!isset($_REQUEST['only_part2']) || empty($_REQUEST['only_part2'])) {
            $data['errors'][] = $data['ssphpobj']->t('{idpinstaller:idpinstaller:step6_org_name_empty_error}');
            return true;
        }
    }
    //Segunda parte del Hook7
    $filename_auths = realpath(__DIR__ . '/../../../config/authsources.php');
    include $filename_auths;
    $filename_hosted = realpath(__DIR__ . '/../../../metadata/saml20-idp-hosted.php');
    $perms_ko = array();
    $file_tmp_name = realpath(__DIR__ . '/../../../cert/') . '/tmp_org_info.php';
    if (file_exists($file_tmp_name)) {
        include $file_tmp_name;
    }
    $org_name = !empty($org_info['name']) && $org_info['name'] !== '' ? $org_info['name'] : "idp-{$hostname}";
    $org_desc = !empty($org_info['info']) && $org_info['info'] !== '' ? $org_info['info'] : "idp-{$hostname}";
    $org_url = !empty($org_info['url']) && $org_info['url'] !== '' ? $org_info['url'] : $hostname;
    if (!is_writable($filename_hosted) || !is_readable($filename_hosted)) {
        array_push($perms_ko, $filename_hosted);
    }
    if (array_key_exists('sql_datasource', $config)) {
        $auth = 'sql_datasource';
    } else {
        if (array_key_exists('ldap_datasource', $config)) {
            $auth = 'ldap_datasource';
        }
    }
    $m = "<?php\n\n\$metadata['idp-{$hostname}'] = array(\n        'UIInfo' => array(\n            'DisplayName' => array(\n                'en' => '{$org_name} ',\n                'es' => '{$org_name} ',\n                'gl' => '{$org_name} ',\n                'eu' => '{$org_name} ',\n                'ca' => '{$org_name} ',\n            ),\n            'Description' => array(\n                'en' => '{$org_desc}',\n                'es' => '{$org_desc}',\n                'gl' => '{$org_desc}',\n                'eu' => '{$org_desc}',\n                'ca' => '{$org_desc}',\n            ),\n            'InformationURL' => array(\n                'en' => '{$org_url}',\n                'es' => '{$org_url}',\n                'gl' => '{$org_url}',\n                'eu' => '{$org_url}',\n                'ca' => '{$org_url}',\n            ),\n        ),\n        'host' => '__DEFAULT__',\n        'privatekey' => '{$pkey_file}',\n        'certificate' => '{$cert_file}',\n        'auth' => '{$auth}',\n        'attributes.NameFormat' => 'urn:oasis:names:tc:SAML:2.0:attrname-format:uri',\n        'attributes' => array(\n                'eduPersonTargetedID',\n                'eduPersonAffiliation',\n                'schacHomeOrganization',\n                'eduPersonEntitlement',\n                'schacPersonalUniqueCode',\n                'uid',\n                'mail',\n                'displayName',\n                'commonName',\n                'eduPersonScopedAffiliation',\n                'eduPersonPrincipalName',\n                'schacHomeOrganizationType',\n        ), \n        'authproc' => array(\n            100 => array('class' => 'core:AttributeMap', 'name2oid'),\n        ),\n        'assertion.encryption' => true\n    );";
    $res = @file_put_contents($filename_hosted, $m);
    unlink($file_tmp_name);
    if (!$res || count($perms_ko) > 0) {
        if (function_exists('posix_getgrnam')) {
            $aux = "<br/>" . $data['ssphpobj']->t('{idpinstaller:idpinstaller:step7_error}');
            $aux .= "<br/>" . $data['ssphpobj']->t('{idpinstaller:idpinstaller:step4_perms_ko}');
            $filename = $perms_ko[0];
            $recursive = is_dir($filename) ? "-R" : "";
            $aux .= "<pre>&gt; chown {$recursive} " . getFileUsername($filename) . ":" . getApacheGroup() . " {$filename}\n&gt; chmod {$recursive} g+rw " . $filename . "</pre>";
        }
        $data['errors2'][] = $aux;
        $data['errors2'][] = $data['ssphpobj']->t("{idpinstaller:idpinstaller:step1_remember_change_perms}");
    }
    if (count($data['errors2']) == 0) {
        $url_meta = 'http://' . $_SERVER['HTTP_HOST'] . substr($_SERVER['SCRIPT_NAME'], 0, -24) . "saml2/idp/metadata.php?output=xhtml";
        $data['info'][] = $data['ssphpobj']->t('{idpinstaller:idpinstaller:step7_all_ok}');
        $data['info'][] = $data['ssphpobj']->t('{idpinstaller:idpinstaller:step7_all_info_extra}') . " <a href='{$url_meta}' target='_blank'>" . $data['ssphpobj']->t('{idpinstaller:idpinstaller:step7_here}') . "</a>";
    } else {
        $data['errors2'][] = $data['ssphpobj']->t('{idpinstaller:idpinstaller:step7_error}');
    }
    return $res;
}
Example #21
0
 if ($ssl_cert_file == '') {
     $ssl_key_file = '';
     $ssl_ca_file = '';
     $ssl_cert_chainfile = '';
     $do_verify = false;
 }
 // verify certificate content
 if ($do_verify) {
     // array openssl_x509_parse ( mixed $x509cert [, bool $shortnames = true ] )
     // openssl_x509_parse() returns information about the supplied x509cert, including fields such as
     // subject name, issuer name, purposes, valid from and valid to dates etc.
     $cert_content = openssl_x509_parse($ssl_cert_file);
     if (is_array($cert_content) && isset($cert_content['subject']) && isset($cert_content['subject']['CN'])) {
         // bool openssl_x509_check_private_key ( mixed $cert , mixed $key )
         // Checks whether the given key is the private key that corresponds to cert.
         if (openssl_x509_check_private_key($ssl_cert_file, $ssl_key_file) === false) {
             standard_error('sslcertificateinvalidcertkeypair');
         }
         // check optional stuff
         if ($ssl_ca_file != '') {
             $ca_content = openssl_x509_parse($ssl_ca_file);
             if (!is_array($ca_content)) {
                 // invalid
                 standard_error('sslcertificateinvalidca');
             }
         }
         if ($ssl_cert_chainfile != '') {
             $chain_content = openssl_x509_parse($ssl_cert_chainfile);
             if (!is_array($chain_content)) {
                 // invalid
                 standard_error('sslcertificateinvalidchain');
 /**
  * Check whether the given private key corresponds
  * to this certificate.
  *
  * @param   security.crypto.PrivateKey privatekey
  * @return  bool
  */
 public function checkPrivateKey($privatekey)
 {
     return openssl_x509_check_private_key($this->_res, $privatekey->getHandle());
 }
Example #23
0
 function setCertificate($certificateFilename, $privateKeyFilename)
 {
     $result = FALSE;
     $certificateFilename = APP . 'paypal' . DS . $certificateFilename;
     $privateKeyFilename = APP . 'paypal' . DS . $privateKeyFilename;
     if (is_readable($certificateFilename) && is_readable($privateKeyFilename)) {
         if ($this->os == 'windows') {
             $certificate = null;
             $handle = fopen($certificateFilename, "r");
             $size = filesize($certificateFilename);
             $certificate = fread($handle, $size);
             fclose($handle);
             $privateKey = null;
             $handle = fopen($privateKeyFilename, "r");
             $size = filesize($privateKeyFilename);
             $privateKey = fread($handle, $size);
             fclose($handle);
             if ($certificate !== false && $privateKey !== false && openssl_x509_check_private_key($certificate, $privateKey)) {
                 $this->certificate = $certificate;
                 $this->certificateFile = $certificateFilename;
                 $this->privateKey = $privateKey;
                 $this->privateKeyFile = $privateKeyFilename;
                 $result = true;
             }
         } else {
             $certificate = @openssl_x509_read(file_get_contents($certificateFilename));
             $privateKey = openssl_get_privatekey(file_get_contents($privateKeyFilename));
             if ($certificate !== FALSE && $privateKey !== FALSE && openssl_x509_check_private_key($certificate, $privateKey)) {
                 $this->certificate = $certificate;
                 $this->certificateFile = $certificateFilename;
                 $this->privateKey = $privateKey;
                 $this->privateKeyFile = $privateKeyFilename;
                 $result = TRUE;
             }
         }
     }
     return $result;
 }
Example #24
0
 /**
  * Compara o certificado de Chave Publica com a Chave Privada
  * @param string $publicCertFilePem
  * @param string $privateCertFileKey
  * @return boolean
  * @throws \Exception
  */
 public function verifyCertificate($publicCertFilePem = null, $privateCertFileKey = null)
 {
     if (empty($publicCertFilePem)) {
         throw new \Exception('Nenhuma chave publica definida!', 500);
     }
     if (!is_file($publicCertFilePem)) {
         throw new \Exception('Arquivo de chave publica não existe!', 500);
     }
     if (empty($privateCertFileKey)) {
         throw new \Exception('Nenhuma chave privada definida!', 500);
     }
     if (!is_file($privateCertFileKey)) {
         throw new \Exception('Arquivo de chave privada não existe!', 500);
     }
     $key = openssl_pkey_get_private(file_get_contents($privateCertFileKey));
     $x509_res = openssl_x509_read(file_get_contents($publicCertFilePem));
     return openssl_x509_check_private_key($x509_res, $key);
 }
 /**
  * View for <param  type="private" class="cbpaidParamsExt" method="checkprivatekey">...
  *
  * @param  string              $value                  Stored Data of Model Value associated with the element
  * @param  ParamsInterface     $pluginParams           Main settigns parameters of the plugin
  * @param  string              $name                   Name attribute
  * @param  CBSimpleXMLElement  $param                  This XML node
  * @param  string              $control_name           Name of the control
  * @param  string              $control_name_name      css id-encode of the names of the controls surrounding this node
  * @param  boolean             $view                   TRUE: view, FALSE: edit
  * @param  cbpaidTable         $modelOfData            Data of the Model corresponding to this View
  * @param  cbpaidTable[]       $modelOfDataRows        Displayed Rows if it is a table
  * @param  int                 $modelOfDataRowsNumber  Total Number of rows
  * @return null|string
  */
 public function checkprivatekey($value, &$pluginParams, $name, &$param, $control_name, $control_name_name, $view, &$modelOfData, &$modelOfDataRows, &$modelOfDataRowsNumber)
 {
     $return = '';
     $default = $param->attributes('default');
     $passphrase_field = $param->attributes('value');
     $public_key_field = $param->attributes('directory');
     $filePath = isset($modelOfData->{$default}) ? $modelOfData->{$default} : null;
     $passphrase = isset($modelOfData->{$passphrase_field}) ? $modelOfData->{$passphrase_field} : null;
     $public_key_path = isset($modelOfData->{$public_key_field}) ? $modelOfData->{$public_key_field} : null;
     $ok = false;
     if ($filePath) {
         $readable = @file_exists($filePath) && @is_readable($filePath);
         if ($readable) {
             $privateKey = openssl_pkey_get_private(file_get_contents($filePath), $passphrase);
             if ($privateKey !== false) {
                 $readableCert = @file_exists($public_key_path) && @is_readable($public_key_path);
                 if ($readableCert) {
                     $certificate = openssl_x509_read(file_get_contents($public_key_path));
                     if ($certificate != false) {
                         $corresponds = openssl_x509_check_private_key($certificate, $privateKey);
                         if ($corresponds) {
                             $return .= "Private and public keys are a pair matching each other.";
                             $ok = true;
                             if (function_exists('openssl_pkey_get_details')) {
                                 $details = openssl_pkey_get_details($privateKey);
                                 if ($details !== false) {
                                     /*
                                     foreach ( $details as $k => $v ) {
                                     	$return	.=	$k . ': ' . $v . '<br />';
                                     }
                                     $return	.=	var_export( $details, true ) . '<br />';
                                     */
                                     $return .= isset($details['bits']) ? '<br />' . "Private key bits: " . $details['bits'] : '';
                                 }
                             }
                         } else {
                             $return = sprintf("Valid Private key File %s is not matching valid Public certificate File %s.", $filePath, $public_key_path);
                         }
                     } else {
                         $return = sprintf("Public certificate File %s is not a X509 certificate, can't check matching with private key.", $public_key_path);
                     }
                 } else {
                     $return = sprintf("Public certificate File %s is not existing or not readable by web server process, can't check matching with private key.", $filePath);
                 }
             } else {
                 $return = sprintf("Private key File %s is either not a private key or the password provided with this key is not valid.", $filePath);
             }
         } else {
             $return = sprintf("Private key File %s is not existing or not readable by web server process.", $filePath);
         }
     } else {
         $return = "Private key file is not defined.";
     }
     return $this->_outputGreenRed('', $ok, $return, $return);
 }
     $dn = array("countryName" => "US", "organizationName" => get_bloginfo('name'), "commonName" => get_bloginfo('name') . " SAML Signing Certificate", "emailAddress" => $current_user->user_email);
     $csr = openssl_csr_new($dn, $pk);
     $crt = openssl_csr_sign($csr, null, $pk, 1825);
     $keyfile = null;
     $certfile = null;
     openssl_pkey_export($pk, $keyfile);
     openssl_x509_export($crt, $certfile);
     //store keys in database
     $this->settings->set_public_key($certfile);
     $this->settings->set_private_key($keyfile);
     //write the private key on save for simple saml parsing
     $key_uploaded = file_put_contents($upload_dir . '/' . get_current_blog_id() . '.key', $keyfile) ? true : false;
 } elseif (isset($_FILES['certificate']) && isset($_FILES['privatekey']) && ($_FILES['certificate']['error'] == 0 && $_FILES['privatekey']['error'] == 0)) {
     $cert = file_get_contents($_FILES['certificate']['tmp_name']);
     $key = file_get_contents($_FILES['privatekey']['tmp_name']);
     if (openssl_x509_check_private_key($cert, $key)) {
         //keys pass openssl key pair check,
         //store keys in database
         $this->settings->set_public_key($cert);
         $this->settings->set_private_key($key);
         //write the private key on save for simple saml parsing
         $key_uploaded = file_put_contents($upload_dir . '/' . get_current_blog_id() . '.key', $key) ? true : false;
     } else {
         echo '<div class="error below-h2"><p>The certificate and private key you provided do not correspond to one another. They were not uploaded.</p></div>' . "\n";
     }
 }
 // Update settings
 $this->settings->enable_cache();
 $this->settings->set_attribute('username', $_POST['username_attribute']);
 $this->settings->set_attribute('firstname', $_POST['firstname_attribute']);
 $this->settings->set_attribute('lastname', $_POST['lastname_attribute']);
Example #27
0
function test_openssl_x509_check_private_key()
{
    $privkey = openssl_pkey_new();
    VERIFY($privkey != null);
    $csr = openssl_csr_new(null, $privkey);
    VERIFY($csr != null);
    $scert = openssl_csr_sign($csr, null, $privkey, 365);
    VERIFY(openssl_x509_check_private_key($scert, $privkey));
}
Example #28
0
 /**
  * Imports a signed-certificate into the key store assigning the alias to
  * the new entry. If the alias is a pre-existing private key, the certificate
  * must be valid and correspond to the private key. Otherwise, an exception
  * is thrown.
  * 
  * @param string $cert     the certificate to import
  * @param string $alias    the alias of the entry to import certificate into
  * @param string $password private key password
  *      
  * @return void          
  */
 public function importCertificate($cert, $alias, $password = false)
 {
     if ($this->containsAlias($alias)) {
         if ($this->isCertificateEntry($alias)) {
             // all right, what kind of entry is this, anyway?
             $entry = $this->getEntry($alias);
             switch ($entry->getEntryType()) {
                 case Crypt_KeyStore_BaseEntry::PRIVATEKEY_TYPE:
                     // replacing existing public key cert with this cert -
                     // check it's validity
                     $this->_log("Getting private key for alias {$alias}");
                     $privkey = $this->_getKey($alias, $password);
                     if ($privkey != null) {
                         $isValid = openssl_x509_check_private_key($cert, $privkey);
                         openssl_free_key($privkey);
                         if ($isValid) {
                             $chain = $entry->getCertificateChain();
                             $chain[0] = $cert;
                             $this->_setKeyEntry($alias, $privkey, $entry->getPrivateKey()->getAlgorithm(), $entry->getPrivateKey()->getSize(), $cert, $chain);
                         } else {
                             throw new Crypt_KeyStore_Exception("Certificate does not match private key");
                         }
                     } else {
                         throw new Crypt_KeyStore_Exception("Failed to get " . "private key");
                     }
                     break;
                 case Crypt_KeyStore_BaseEntry::TRUSTEDCERT_TYPE:
                     // replacing trusted cert with this c ert -
                     // just do it
                     $this->_setCertificateEntry($alias, $cert);
                     break;
                 default:
                     // shouldn't get here, but just in case
                     throw new Crypt_KeyStore_Exception("Alias {$alias} refers to an existing non-certificate entry");
                     break;
             }
         } else {
             // certificates can only be imported into certificate entries
             throw new Crypt_KeyStore_Exception("Alias {$alias} refers to an existing non-certificate entry");
         }
     } else {
         $this->_setEntry($alias, new Crypt_KeyStore_TrustedCertificateEntry($cert));
     }
     return;
 }
Example #29
0
 function diagnostics()
 {
     $testOutput = array();
     if ($this->config['application_type'] == 'Partner') {
         if (!file_get_contents($this->config['curl_ssl_cert'])) {
             $testOutput['ssl_cert_error'] = "Can't read the Xero Entrust cert. You need one for partner API applications. http://developer.xero.com/documentation/getting-started/partner-applications/ \n";
         } else {
             $data = openssl_x509_parse(file_get_contents($this->config['curl_ssl_cert']));
             $validFrom = date('Y-m-d H:i:s', $data['validFrom_time_t']);
             if (time() < $data['validFrom_time_t']) {
                 $testOutput['ssl_cert_error'] = "Xero Entrust cert not yet valid - cert valid from " . $validFrom . "\n";
             }
             $validTo = date('Y-m-d H:i:s', $data['validTo_time_t']);
             if (time() > $data['validTo_time_t']) {
                 $testOutput['ssl_cert_error'] = "Xero Entrust cert expired - cert valid to " . $validFrom . "\n";
             }
         }
     }
     if ($this->config['application_type'] == 'Partner' || $this->config['application_type'] == 'Private') {
         if (!file_exists($this->config['rsa_public_key'])) {
             $testOutput['rsa_cert_error'] = "Can't read the self-signed SSL cert. Private and Partner API applications require a self-signed X509 cert http://developer.xero.com/documentation/advanced-docs/public-private-keypair/ \n";
         }
         if (file_exists($this->config['rsa_public_key'])) {
             $data = openssl_x509_parse(file_get_contents($this->config['rsa_public_key']));
             $validFrom = date('Y-m-d H:i:s', $data['validFrom_time_t']);
             if (time() < $data['validFrom_time_t']) {
                 $testOutput['ssl_cert_error'] = "Application cert not yet valid - cert valid from " . $validFrom . "\n";
             }
             $validTo = date('Y-m-d H:i:s', $data['validTo_time_t']);
             if (time() > $data['validTo_time_t']) {
                 $testOutput['ssl_cert_error'] = "Application cert cert expired - cert valid to " . $validFrom . "\n";
             }
         }
         if (!file_exists($this->config['rsa_private_key'])) {
             $testOutput['rsa_cert_error'] = "Can't read the self-signed cert key. Check your rsa_private_key config variable. Private and Partner API applications require a self-signed X509 cert http://developer.xero.com/documentation/advanced-docs/public-private-keypair/ \n";
         }
         if (file_exists($this->config['rsa_private_key'])) {
             $cert_content = file_get_contents($this->config['rsa_public_key']);
             $priv_key_content = file_get_contents($this->config['rsa_private_key']);
             if (!openssl_x509_check_private_key($cert_content, $priv_key_content)) {
                 $testOutput['rsa_cert_error'] = "Application certificate and key do not match \n";
             }
         }
     }
     return $testOutput;
 }
 /**
  * Import local certificates that are in the keys folder but orphaned
  * @return array Array of processed keys
  */
 public function importLocalCertificates()
 {
     $location = $this->PKCS->getKeysLocation();
     $cas = $this->getAllAuthorityFiles();
     $keys = array();
     $processed = array();
     foreach (glob($location . "/*.key") as $file) {
         $name = basename($file, ".key");
         if (in_array(basename($file), $cas) || $this->checkCertificateName($name)) {
             continue;
         }
         $raw = file_get_contents($file);
         if (empty($raw)) {
             $processed[] = array("status" => false, "error" => _("Key is empty"), "file" => $file);
             continue;
         }
         $key = openssl_pkey_get_private($raw);
         if ($key === false) {
             //key is password protected
             $processed[] = array("status" => false, "error" => _("Key is password protected or malformed"), "file" => $file);
             continue;
         }
         $info = openssl_pkey_get_details($key);
         $keys[] = array("file" => $file, "res" => $key, "raw" => file_get_contents($file));
     }
     foreach (glob($location . "/*.crt") as $file) {
         if (in_array(basename($file), $cas)) {
             continue;
         }
         $raw = file_get_contents($file);
         if (empty($raw)) {
             $processed[] = array("status" => false, "error" => _("Certificate is empty"), "file" => $file);
             continue;
         }
         $info = openssl_x509_read($raw);
         foreach ($keys as $key) {
             if (openssl_x509_check_private_key($info, $key['res'])) {
                 $name = basename($file, ".crt");
                 if (!$this->checkCertificateName($name)) {
                     try {
                         $status = $this->importCertificate($name, $key['raw'], file_get_contents($file));
                     } catch (\Exception $e) {
                         $processed[] = array("status" => false, "error" => $e->getMessage(), "file" => $file);
                         continue;
                     }
                     $this->saveCertificate(null, $name, _("Imported from file system"), 'up');
                     $processed[] = array("status" => true, "file" => $file);
                 }
             }
         }
     }
     return $processed;
 }