| Total Complexity | 66 |
| Total Lines | 652 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
Complex classes like SilverbulletCertificate often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use SilverbulletCertificate, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 27 | class SilverbulletCertificate extends EntityWithDBProperties { |
||
| 28 | |||
| 29 | public $username; |
||
| 30 | public $expiry; |
||
| 31 | public $serial; |
||
| 32 | public $dbId; |
||
| 33 | public $invitationId; |
||
| 34 | public $userId; |
||
| 35 | public $profileId; |
||
| 36 | public $issued; |
||
| 37 | public $device; |
||
| 38 | public $revocationStatus; |
||
| 39 | public $revocationTime; |
||
| 40 | public $ocsp; |
||
| 41 | public $ocspTimestamp; |
||
| 42 | public $status; |
||
| 43 | |||
| 44 | const CERTSTATUS_VALID = 1; |
||
| 45 | const CERTSTATUS_EXPIRED = 2; |
||
| 46 | const CERTSTATUS_REVOKED = 3; |
||
| 47 | const CERTSTATUS_INVALID = 4; |
||
| 48 | |||
| 49 | /** |
||
| 50 | * instantiates an existing certificate, identified either by its serial |
||
| 51 | * number or the username. |
||
| 52 | * |
||
| 53 | * Use static issueCertificate() to generate a whole new cert. |
||
| 54 | * |
||
| 55 | * @param int|string $identifier |
||
|
|
|||
| 56 | */ |
||
| 57 | public function __construct($identifier) { |
||
| 58 | $this->databaseType = "INST"; |
||
| 59 | parent::__construct(); |
||
| 60 | $this->username = ""; |
||
| 61 | $this->expiry = "2000-01-01 00:00:00"; |
||
| 62 | $this->serial = -1; |
||
| 63 | $this->dbId = -1; |
||
| 64 | $this->invitationId = -1; |
||
| 65 | $this->userId = -1; |
||
| 66 | $this->profileId = -1; |
||
| 67 | $this->issued = "2000-01-01 00:00:00"; |
||
| 68 | $this->device = NULL; |
||
| 69 | $this->revocationStatus = "REVOKED"; |
||
| 70 | $this->revocationTime = "2000-01-01 00:00:00"; |
||
| 71 | $this->ocsp = NULL; |
||
| 72 | $this->ocspTimestamp = "2000-01-01 00:00:00"; |
||
| 73 | $this->status = SilverbulletCertificate::CERTSTATUS_INVALID; |
||
| 74 | |||
| 75 | $incoming = FALSE; |
||
| 76 | if (is_numeric($identifier)) { |
||
| 77 | $incoming = $this->databaseHandle->exec("SELECT `id`, `profile_id`, `silverbullet_user_id`, `silverbullet_invitation_id`, `serial_number`, `cn` ,`expiry`, `issued`, `device`, `revocation_status`, `revocation_time`, `OCSP`, `OCSP_timestamp` FROM `silverbullet_certificate` WHERE serial_number = ?", "i", $identifier); |
||
| 78 | } else { // it's a string instead |
||
| 79 | $incoming = $this->databaseHandle->exec("SELECT `id`, `profile_id`, `silverbullet_user_id`, `silverbullet_invitation_id`, `serial_number`, `cn` ,`expiry`, `issued`, `device`, `revocation_status`, `revocation_time`, `OCSP`, `OCSP_timestamp` FROM `silverbullet_certificate` WHERE cn = ?", "s", $identifier); |
||
| 80 | } |
||
| 81 | |||
| 82 | // SELECT -> mysqli_resource, not boolean |
||
| 83 | while ($oneResult = mysqli_fetch_object(/** @scrutinizer ignore-type */ $incoming)) { // there is only at most one |
||
| 84 | $this->username = $oneResult->cn; |
||
| 85 | $this->expiry = $oneResult->expiry; |
||
| 86 | $this->serial = $oneResult->serial_number; |
||
| 87 | $this->dbId = $oneResult->id; |
||
| 88 | $this->invitationId = $oneResult->silverbullet_invitation_id; |
||
| 89 | $this->userId = $oneResult->silverbullet_user_id; |
||
| 90 | $this->profileId = $oneResult->profile_id; |
||
| 91 | $this->issued = $oneResult->issued; |
||
| 92 | $this->device = $oneResult->device; |
||
| 93 | $this->revocationStatus = $oneResult->revocation_status; |
||
| 94 | $this->revocationTime = $oneResult->revocation_time; |
||
| 95 | $this->ocsp = $oneResult->OCSP; |
||
| 96 | $this->ocspTimestamp = $oneResult->OCSP_timestamp; |
||
| 97 | // is the cert expired? |
||
| 98 | $now = new \DateTime(); |
||
| 99 | $cert_expiry = new \DateTime($this->expiry); |
||
| 100 | $delta = $now->diff($cert_expiry); |
||
| 101 | $this->status = ($delta->invert == 1 ? SilverbulletCertificate::CERTSTATUS_EXPIRED : SilverbulletCertificate::CERTSTATUS_VALID); |
||
| 102 | // expired is expired; even if it was previously revoked. But do update status for revoked ones... |
||
| 103 | if ($this->status == SilverbulletCertificate::CERTSTATUS_VALID && $this->revocationStatus == "REVOKED") { |
||
| 104 | $this->status = SilverbulletCertificate::CERTSTATUS_REVOKED; |
||
| 105 | } |
||
| 106 | } |
||
| 107 | } |
||
| 108 | |||
| 109 | /** |
||
| 110 | * |
||
| 111 | * @return array of basic certificate details |
||
| 112 | */ |
||
| 113 | public function getBasicInfo() { |
||
| 114 | $returnArray = []; // unnecessary because the iterator below is never empty, but Scrutinizer gets excited nontheless |
||
| 115 | foreach (['status', 'serial', 'username', 'device', 'issued', 'expiry'] as $key) { |
||
| 116 | $returnArray[$key] = $this->$key; |
||
| 117 | } |
||
| 118 | return($returnArray); |
||
| 119 | } |
||
| 120 | |||
| 121 | public function updateFreshness() { |
||
| 122 | // nothing to be done here. |
||
| 123 | } |
||
| 124 | |||
| 125 | /** |
||
| 126 | * issue a certificate based on a token |
||
| 127 | * |
||
| 128 | * @param string $token |
||
| 129 | * @param string $importPassword |
||
| 130 | * @return array |
||
| 131 | */ |
||
| 132 | public static function issueCertificate($token, $importPassword) { |
||
| 133 | $loggerInstance = new common\Logging(); |
||
| 134 | $databaseHandle = DBConnection::handle("INST"); |
||
| 135 | $loggerInstance->debug(5, "generateCertificate() - starting.\n"); |
||
| 136 | $invitationObject = new SilverbulletInvitation($token); |
||
| 137 | $profile = new ProfileSilverbullet($invitationObject->profile); |
||
| 138 | $inst = new IdP($profile->institution); |
||
| 139 | $loggerInstance->debug(5, "tokenStatus: done, got " . $invitationObject->invitationTokenStatus . ", " . $invitationObject->profile . ", " . $invitationObject->userId . ", " . $invitationObject->expiry . ", " . $invitationObject->invitationTokenString . "\n"); |
||
| 140 | if ($invitationObject->invitationTokenStatus != SilverbulletInvitation::SB_TOKENSTATUS_VALID && $invitationObject->invitationTokenStatus != SilverbulletInvitation::SB_TOKENSTATUS_PARTIALLY_REDEEMED) { |
||
| 141 | throw new Exception("Attempt to generate a SilverBullet installer with an invalid/redeemed/expired token. The user should never have gotten that far!"); |
||
| 142 | } |
||
| 143 | |||
| 144 | // SQL query to find the expiry date of the *user* to find the correct ValidUntil for the cert |
||
| 145 | $user = $invitationObject->userId; |
||
| 146 | $userrow = $databaseHandle->exec("SELECT expiry FROM silverbullet_user WHERE id = ?", "i", $user); |
||
| 147 | // SELECT -> resource, not boolean |
||
| 148 | if ($userrow->num_rows != 1) { |
||
| 149 | throw new Exception("Despite a valid token, the corresponding user was not found in database or database query error!"); |
||
| 150 | } |
||
| 151 | $expiryObject = mysqli_fetch_object(/** @scrutinizer ignore-type */ $userrow); |
||
| 152 | $loggerInstance->debug(5, "EXP: " . $expiryObject->expiry . "\n"); |
||
| 153 | $expiryDateObject = date_create_from_format("Y-m-d H:i:s", $expiryObject->expiry); |
||
| 154 | if ($expiryDateObject === FALSE) { |
||
| 155 | throw new Exception("The expiry date we got from the DB is bogus!"); |
||
| 156 | } |
||
| 157 | $loggerInstance->debug(5, $expiryDateObject->format("Y-m-d H:i:s") . "\n"); |
||
| 158 | // date_create with no parameters can't fail, i.e. is never FALSE |
||
| 159 | $validity = date_diff(/** @scrutinizer ignore-type */ date_create(), $expiryDateObject); |
||
| 160 | $expiryDays = $validity->days + 1; |
||
| 161 | if ($validity->invert == 1) { // negative! That should not be possible |
||
| 162 | throw new Exception("Attempt to generate a certificate for a user which is already expired!"); |
||
| 163 | } |
||
| 164 | |||
| 165 | $privateKey = openssl_pkey_new(['private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA, 'encrypt_key' => FALSE]); |
||
| 166 | |||
| 167 | $csr = SilverbulletCertificate::generateCsr($privateKey, strtoupper($inst->federation), $profile->getAttributes("internal:realm")[0]['value']); |
||
| 168 | |||
| 169 | $loggerInstance->debug(5, "generateCertificate: proceeding to sign cert.\n"); |
||
| 170 | |||
| 171 | $certMeta = SilverbulletCertificate::signCsr($csr, $expiryDays); |
||
| 172 | $cert = $certMeta["CERT"]; |
||
| 173 | $issuingCaPem = $certMeta["ISSUER"]; |
||
| 174 | $rootCaPem = $certMeta["ROOT"]; |
||
| 175 | $serial = $certMeta["SERIAL"]; |
||
| 176 | |||
| 177 | $loggerInstance->debug(5, "generateCertificate: post-processing certificate.\n"); |
||
| 178 | |||
| 179 | // with the cert, our private key and import password, make a PKCS#12 container out of it |
||
| 180 | $exportedCertProt = ""; |
||
| 181 | openssl_pkcs12_export($cert, $exportedCertProt, $privateKey, $importPassword, ['extracerts' => [$issuingCaPem /* , $rootCaPem */]]); |
||
| 182 | $exportedCertClear = ""; |
||
| 183 | openssl_pkcs12_export($cert, $exportedCertClear, $privateKey, "", ['extracerts' => [$issuingCaPem, $rootCaPem]]); |
||
| 184 | // store resulting cert CN and expiry date in separate columns into DB - do not store the cert data itself as it contains the private key! |
||
| 185 | // we need the *real* expiry date, not just the day-approximation |
||
| 186 | $x509 = new \core\common\X509(); |
||
| 187 | $certString = ""; |
||
| 188 | openssl_x509_export($cert, $certString); |
||
| 189 | $parsedCert = $x509->processCertificate($certString); |
||
| 190 | $loggerInstance->debug(5, "CERTINFO: " . print_r($parsedCert['full_details'], true)); |
||
| 191 | $realExpiryDate = date_create_from_format("U", $parsedCert['full_details']['validTo_time_t'])->format("Y-m-d H:i:s"); |
||
| 192 | |||
| 193 | // store new cert info in DB |
||
| 194 | $databaseHandle->exec("INSERT INTO `silverbullet_certificate` (`profile_id`, `silverbullet_user_id`, `silverbullet_invitation_id`, `serial_number`, `cn` ,`expiry`) VALUES (?, ?, ?, ?, ?, ?)", "iiisss", $invitationObject->profile, $invitationObject->userId, $invitationObject->identifier, $serial, $csr["USERNAME"], $realExpiryDate); |
||
| 195 | // newborn cert immediately gets its "valid" OCSP response |
||
| 196 | $certObject = new SilverbulletCertificate($serial); |
||
| 197 | $certObject->triggerNewOCSPStatement(); |
||
| 198 | // return PKCS#12 data stream |
||
| 199 | return [ |
||
| 200 | "certObject" => $certObject, |
||
| 201 | "certdata" => $exportedCertProt, |
||
| 202 | "certdataclear" => $exportedCertClear, |
||
| 203 | "sha1" => openssl_x509_fingerprint($cert, "sha1"), |
||
|
1 ignored issue
–
show
|
|||
| 204 | "sha256" => openssl_x509_fingerprint($cert, "sha256"), |
||
| 205 | 'importPassword' => $importPassword, |
||
| 206 | 'GUID' => common\Entity::uuid("", $exportedCertProt), |
||
| 207 | ]; |
||
| 208 | } |
||
| 209 | |||
| 210 | /** |
||
| 211 | * triggers a new OCSP statement for the given serial number |
||
| 212 | * |
||
| 213 | * @return string DER-encoded OCSP status info (binary data!) |
||
| 214 | */ |
||
| 215 | public function triggerNewOCSPStatement() { |
||
| 299 | } |
||
| 300 | |||
| 301 | /** |
||
| 302 | * revokes a certificate |
||
| 303 | * @return array with revocation information |
||
| 304 | */ |
||
| 305 | public function revokeCertificate() { |
||
| 306 | $nowSql = (new \DateTime())->format("Y-m-d H:i:s"); |
||
| 307 | // regardless if embedded or not, always keep local state in our own DB |
||
| 308 | $this->databaseHandle->exec("UPDATE silverbullet_certificate SET revocation_status = 'REVOKED', revocation_time = ? WHERE serial_number = ?", "si", $nowSql, $this->serial); |
||
| 309 | $this->loggerInstance->debug(2, "Certificate revocation status for $this->serial updated, about to call triggerNewOCSPStatement().\n"); |
||
| 310 | // newly instantiate us, DB content has changed... |
||
| 311 | $certObject = new SilverbulletCertificate($this->serial); |
||
| 312 | // embedded CA does "nothing special" for revocation: the DB change was the entire thing to do |
||
| 313 | // but for external CAs, we need to notify explicitly that the cert is now revoked |
||
| 314 | switch (CONFIG_CONFASSISTANT['SILVERBULLET']['CA']['type']) { |
||
| 315 | case "embedded": |
||
| 316 | break; |
||
| 317 | case "eduPKI": |
||
| 318 | try { |
||
| 319 | $soap = SilverbulletCertificate::initEduPKISoapSession("RA"); |
||
| 320 | $soapRevocationSerial = $soap->newRevocationRequest($this->serial, ""); |
||
| 321 | if ($soapRevocationSerial == 0) { |
||
| 322 | throw new Exception("Unable to create revocation request, serial number was zero."); |
||
| 323 | } |
||
| 324 | // retrieve the raw request to prepare for signature and approval |
||
| 325 | $soapRawRevRequest = $soap->getRawRevocationRequest($soapRevocationSerial); |
||
| 326 | if (strlen($soapRawRevRequest) < 10) { // very basic error handling |
||
| 327 | throw new Exception("Suspiciously short data to sign!"); |
||
| 328 | } |
||
| 329 | // for obnoxious reasons, we have to dump the request into a file and let pkcs7_sign read from the file |
||
| 330 | // rather than just using the string. Grr. |
||
| 331 | $tempdir = \core\common\Entity::createTemporaryDirectory("test"); |
||
| 332 | file_put_contents($tempdir['dir'] . "/content.txt", $soapRawRevRequest); |
||
| 333 | // retrieve our RA cert from filesystem |
||
| 334 | $raCertFile = file_get_contents(ROOT . "../edupki-test-ra.pem"); |
||
| 335 | $raCert = openssl_x509_read($raCertFile); |
||
| 336 | $raKey = openssl_pkey_get_private("file://" . ROOT . "../edupki-test-ra.clearkey"); |
||
| 337 | // sign the data |
||
| 338 | if (openssl_pkcs7_sign($tempdir['dir'] . "/content.txt", $tempdir['dir'] . "/signature.txt", $raCert, $raKey, []) === FALSE) { |
||
| 339 | throw new Exception("Unable to sign the revocation approval data!"); |
||
| 340 | } |
||
| 341 | // and get the signature blob back from the filesystem |
||
| 342 | $detachedSig = file_get_contents($tempdir['dir'] . "/signature.txt"); |
||
| 343 | $soapIssueRev = $soap->approveRevocationRequest($soapRevocationSerial, $soapRawRevRequest, $detachedSig); |
||
| 344 | if ($soapIssueRev === FALSE) { |
||
| 345 | throw new Exception("The locally approved revocation request was NOT processed by the CA."); |
||
| 346 | } |
||
| 347 | } catch (Exception $e) { |
||
| 348 | // PHP 7.1 can do this much better |
||
| 349 | if (is_soap_fault($e)) { |
||
| 350 | throw new Exception("Error when sending SOAP request: " . "{$e->faultcode}: {$e->faultstring}\n"); |
||
| 351 | } |
||
| 352 | throw new Exception("Something odd happened while doing the SOAP request:" . $e->getMessage()); |
||
| 353 | } |
||
| 354 | break; |
||
| 355 | default: |
||
| 356 | throw new Exception("Unknown type of CA requested!"); |
||
| 357 | } |
||
| 358 | // what happens wrt OCSP etc. is really something for the following function to decide. We just call it. |
||
| 359 | $certObject->triggerNewOCSPStatement(); |
||
| 360 | } |
||
| 361 | |||
| 362 | /** |
||
| 363 | * create a CSR |
||
| 364 | * |
||
| 365 | * @param resource $privateKey the private key to create the CSR with |
||
| 366 | * @return array with the CSR and some meta info |
||
| 367 | */ |
||
| 368 | private static function generateCsr($privateKey, $fed, $realm) { |
||
| 431 | ]; |
||
| 432 | } |
||
| 433 | |||
| 434 | private static function initEduPKISoapSession($type) { |
||
| 482 | } |
||
| 483 | |||
| 484 | const EDUPKI_RA_ID = 700; |
||
| 485 | const EDUPKI_CERT_PROFILE = "User SOAP"; |
||
| 486 | const EDUPKI_RA_PKEY_PASSPHRASE = "..."; |
||
| 487 | |||
| 488 | /** |
||
| 489 | * take a CSR and sign it with our issuing CA's certificate |
||
| 490 | * |
||
| 491 | * @param mixed $csr the CSR |
||
| 492 | * @param int $expiryDays the number of days until the cert is going to expire |
||
| 493 | * @return array the cert and some meta info |
||
| 494 | */ |
||
| 495 | private static function signCsr($csr, $expiryDays) { |
||
| 683 |