| Total Complexity | 53 |
| Total Lines | 524 |
| 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 |
||
| 26 | class SilverbulletCertificate extends EntityWithDBProperties { |
||
| 27 | |||
| 28 | public $username; |
||
| 29 | public $expiry; |
||
| 30 | public $serial; |
||
| 31 | public $dbId; |
||
| 32 | public $invitationId; |
||
| 33 | public $userId; |
||
| 34 | public $profileId; |
||
| 35 | public $issued; |
||
| 36 | public $device; |
||
| 37 | public $revocationStatus; |
||
| 38 | public $revocationTime; |
||
| 39 | public $ocsp; |
||
| 40 | public $ocspTimestamp; |
||
| 41 | public $status; |
||
| 42 | |||
| 43 | const CERTSTATUS_VALID = 1; |
||
| 44 | const CERTSTATUS_EXPIRED = 2; |
||
| 45 | const CERTSTATUS_REVOKED = 3; |
||
| 46 | const CERTSTATUS_INVALID = 4; |
||
| 47 | |||
| 48 | /** |
||
| 49 | * instantiates an existing certificate, identified either by its serial |
||
| 50 | * number or the username. |
||
| 51 | * |
||
| 52 | * Use static issueCertificate() to generate a whole new cert. |
||
| 53 | * |
||
| 54 | * @param int|string $identifier |
||
| 55 | */ |
||
| 56 | public function __construct($identifier) { |
||
| 57 | $this->databaseType = "INST"; |
||
| 58 | parent::__construct(); |
||
| 59 | $this->username = ""; |
||
| 60 | $this->expiry = "2000-01-01 00:00:00"; |
||
| 61 | $this->serial = -1; |
||
| 62 | $this->dbId = -1; |
||
| 63 | $this->invitationId = -1; |
||
| 64 | $this->userId = -1; |
||
| 65 | $this->profileId = -1; |
||
| 66 | $this->issued = "2000-01-01 00:00:00"; |
||
| 67 | $this->device = NULL; |
||
| 68 | $this->revocationStatus = "REVOKED"; |
||
| 69 | $this->revocationTime = "2000-01-01 00:00:00"; |
||
| 70 | $this->ocsp = NULL; |
||
| 71 | $this->ocspTimestamp = "2000-01-01 00:00:00"; |
||
| 72 | $this->status = SilverbulletCertificate::CERTSTATUS_INVALID; |
||
| 73 | |||
| 74 | $incoming = FALSE; |
||
| 75 | if (is_numeric($identifier)) { |
||
| 76 | $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); |
||
| 77 | } else { // it's a string instead |
||
| 78 | $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); |
||
| 79 | } |
||
| 80 | |||
| 81 | // SELECT -> mysqli_resource, not boolean |
||
| 82 | while ($oneResult = mysqli_fetch_object(/** @scrutinizer ignore-type */ $incoming)) { // there is only at most one |
||
| 83 | $this->username = $oneResult->cn; |
||
| 84 | $this->expiry = $oneResult->expiry; |
||
| 85 | $this->serial = $oneResult->serial_number; |
||
| 86 | $this->dbId = $oneResult->id; |
||
| 87 | $this->invitationId = $oneResult->silverbullet_invitation_id; |
||
| 88 | $this->userId = $oneResult->silverbullet_user_id; |
||
| 89 | $this->profileId = $oneResult->profile_id; |
||
| 90 | $this->issued = $oneResult->issued; |
||
| 91 | $this->device = $oneResult->device; |
||
| 92 | $this->revocationStatus = $oneResult->revocation_status; |
||
| 93 | $this->revocationTime = $oneResult->revocation_time; |
||
| 94 | $this->ocsp = $oneResult->OCSP; |
||
| 95 | $this->ocspTimestamp = $oneResult->OCSP_timestamp; |
||
| 96 | // is the cert expired? |
||
| 97 | $now = new \DateTime(); |
||
| 98 | $cert_expiry = new \DateTime($this->expiry); |
||
| 99 | $delta = $now->diff($cert_expiry); |
||
| 100 | $this->status = ($delta->invert == 1 ? SilverbulletCertificate::CERTSTATUS_EXPIRED : SilverbulletCertificate::CERTSTATUS_VALID); |
||
| 101 | // expired is expired; even if it was previously revoked. But do update status for revoked ones... |
||
| 102 | if ($this->status == SilverbulletCertificate::CERTSTATUS_VALID && $this->revocationStatus == "REVOKED") { |
||
| 103 | $this->status = SilverbulletCertificate::CERTSTATUS_REVOKED; |
||
| 104 | } |
||
| 105 | } |
||
| 106 | } |
||
| 107 | |||
| 108 | /** |
||
| 109 | * |
||
| 110 | * @return array of basic certificate details |
||
| 111 | */ |
||
| 112 | public function getBasicInfo() { |
||
| 113 | $returnArray = []; // unnecessary because the iterator below is never empty, but Scrutinizer gets excited nontheless |
||
| 114 | foreach (['status', 'serial', 'username', 'device', 'issued', 'expiry'] as $key) { |
||
| 115 | $returnArray[$key] = $this->$key; |
||
| 116 | } |
||
| 117 | return($returnArray); |
||
| 118 | } |
||
| 119 | |||
| 120 | public function updateFreshness() { |
||
| 121 | // nothing to be done here. |
||
| 122 | } |
||
| 123 | |||
| 124 | /** |
||
| 125 | * issue a certificate based on a token |
||
| 126 | * |
||
| 127 | * @param string $token |
||
| 128 | * @param string $importPassword |
||
| 129 | * @return array |
||
| 130 | */ |
||
| 131 | public static function issueCertificate($token, $importPassword) { |
||
| 206 | ]; |
||
| 207 | } |
||
| 208 | |||
| 209 | /** |
||
| 210 | * triggers a new OCSP statement for the given serial number |
||
| 211 | * |
||
| 212 | * @return string DER-encoded OCSP status info (binary data!) |
||
| 213 | */ |
||
| 214 | public function triggerNewOCSPStatement() { |
||
| 215 | $logHandle = new \core\common\Logging(); |
||
| 216 | $logHandle->debug(2, "Triggering new OCSP statement for serial $this->serial.\n"); |
||
| 217 | switch (CONFIG_CONFASSISTANT['SILVERBULLET']['CA']['type']) { |
||
| 218 | case "embedded": |
||
| 219 | $certstatus = ""; |
||
| 220 | // get all relevant info from object properties |
||
| 221 | if ($this->serial >= 0) { // let's start with the assumption that the cert is valid |
||
| 222 | if ($this->revocationStatus == "REVOKED") { |
||
| 223 | // already revoked, simply return canned OCSP response |
||
| 224 | $certstatus = "R"; |
||
| 225 | } else { |
||
| 226 | $certstatus = "V"; |
||
| 227 | } |
||
| 228 | } |
||
| 229 | |||
| 230 | $originalExpiry = date_create_from_format("Y-m-d H:i:s", $this->expiry); |
||
| 231 | if ($originalExpiry === FALSE) { |
||
| 232 | throw new Exception("Unable to calculate original expiry date, input data bogus!"); |
||
| 233 | } |
||
| 234 | $validity = date_diff(/** @scrutinizer ignore-type */ date_create(), $originalExpiry); |
||
| 235 | if ($validity->invert == 1) { |
||
| 236 | // negative! Cert is already expired, no need to revoke. |
||
| 237 | // No need to return anything really, but do return the last known OCSP statement to prevent special case |
||
| 238 | $certstatus = "E"; |
||
| 239 | } |
||
| 240 | $profile = new ProfileSilverbullet($this->profileId); |
||
| 241 | $inst = new IdP($profile->institution); |
||
| 242 | $federation = strtoupper($inst->federation); |
||
| 243 | // generate stub index.txt file |
||
| 244 | $tempdirArray = \core\common\Entity::createTemporaryDirectory("test"); |
||
| 245 | $tempdir = $tempdirArray['dir']; |
||
| 246 | $nowIndexTxt = (new \DateTime())->format("ymdHis") . "Z"; |
||
| 247 | $expiryIndexTxt = $originalExpiry->format("ymdHis") . "Z"; |
||
| 248 | $serialHex = strtoupper(dechex($this->serial)); |
||
| 249 | if (strlen($serialHex) % 2 == 1) { |
||
| 250 | $serialHex = "0" . $serialHex; |
||
| 251 | } |
||
| 252 | |||
| 253 | $indexStatement = "$certstatus\t$expiryIndexTxt\t" . ($certstatus == "R" ? "$nowIndexTxt,unspecified" : "") . "\t$serialHex\tunknown\t/O=" . CONFIG_CONFASSISTANT['CONSORTIUM']['name'] . "/OU=$federation/CN=$this->username/emailAddress=$this->username\n"; |
||
| 254 | $logHandle->debug(4, "index.txt contents-to-be: $indexStatement"); |
||
| 255 | if (!file_put_contents($tempdir . "/index.txt", $indexStatement)) { |
||
| 256 | $logHandle->debug(1, "Unable to write openssl index.txt file for revocation handling!"); |
||
| 257 | } |
||
| 258 | // index.txt.attr is dull but needs to exist |
||
| 259 | file_put_contents($tempdir . "/index.txt.attr", "unique_subject = yes\n"); |
||
| 260 | // call "openssl ocsp" to manufacture our own OCSP statement |
||
| 261 | // adding "-rmd sha1" to the following command-line makes the |
||
| 262 | // choice of signature algorithm for the response explicit |
||
| 263 | // but it's only available from openssl-1.1.0 (which we do not |
||
| 264 | // want to require just for that one thing). |
||
| 265 | $execCmd = CONFIG['PATHS']['openssl'] . " ocsp -issuer " . ROOT . "/config/SilverbulletClientCerts/real.pem -sha1 -ndays 10 -no_nonce -serial 0x$serialHex -CA " . ROOT . "/config/SilverbulletClientCerts/real.pem -rsigner " . ROOT . "/config/SilverbulletClientCerts/real.pem -rkey " . ROOT . "/config/SilverbulletClientCerts/real.key -index $tempdir/index.txt -no_cert_verify -respout $tempdir/$serialHex.response.der"; |
||
| 266 | $logHandle->debug(2, "Calling openssl ocsp with following cmdline: $execCmd\n"); |
||
| 267 | $output = []; |
||
| 268 | $return = 999; |
||
| 269 | exec($execCmd, $output, $return); |
||
| 270 | if ($return !== 0) { |
||
| 271 | throw new Exception("Non-zero return value from openssl ocsp!"); |
||
| 272 | } |
||
| 273 | $ocsp = file_get_contents($tempdir . "/$serialHex.response.der"); |
||
| 274 | // remove the temp dir! |
||
| 275 | unlink($tempdir . "/$serialHex.response.der"); |
||
| 276 | unlink($tempdir . "/index.txt.attr"); |
||
| 277 | unlink($tempdir . "/index.txt"); |
||
| 278 | rmdir($tempdir); |
||
| 279 | break; |
||
| 280 | case "eduPKI": |
||
| 281 | // nothing to be done here - eduPKI have their own OCSP responder |
||
| 282 | // and the certs point to it. So we are not in the loop. |
||
| 283 | break; |
||
| 284 | default: |
||
| 285 | /* HTTP POST the serial to the CA. The CA knows about the state of |
||
| 286 | * the certificate. |
||
| 287 | * |
||
| 288 | * $httpResponse = httpRequest("https://clientca.hosted.eduroam.org/ocsp/", ["serial" => $serial ] ); |
||
| 289 | * |
||
| 290 | * The result of this if clause has to be a DER-encoded OCSP statement |
||
| 291 | * to be stored in the variable $ocsp |
||
| 292 | */ |
||
| 293 | throw new Exception("This type of silverbullet CA is not implemented yet!"); |
||
| 294 | } |
||
| 295 | // write the new statement into DB |
||
| 296 | $this->databaseHandle->exec("UPDATE silverbullet_certificate SET OCSP = ?, OCSP_timestamp = NOW() WHERE serial_number = ?", "si", $ocsp, $this->serial); |
||
| 297 | return $ocsp; |
||
| 298 | } |
||
| 299 | |||
| 300 | /** |
||
| 301 | * revokes a certificate |
||
| 302 | * @return array with revocation information |
||
| 303 | */ |
||
| 304 | public function revokeCertificate() { |
||
| 305 | $nowSql = (new \DateTime())->format("Y-m-d H:i:s"); |
||
| 306 | // regardless if embedded or not, always keep local state in our own DB |
||
| 307 | $this->databaseHandle->exec("UPDATE silverbullet_certificate SET revocation_status = 'REVOKED', revocation_time = ? WHERE serial_number = ?", "si", $nowSql, $this->serial); |
||
| 308 | $this->loggerInstance->debug(2, "Certificate revocation status for $this->serial updated, about to call triggerNewOCSPStatement().\n"); |
||
| 309 | // newly instantiate us, DB content has changed... |
||
| 310 | $certObject = new SilverbulletCertificate($this->serial); |
||
| 311 | // embedded CA does "nothing special" for revocation: the DB change was the entire thing to do |
||
| 312 | // but for external CAs, we need to notify explicitly that the cert is now revoked |
||
| 313 | switch (CONFIG_CONFASSISTANT['SILVERBULLET']['CA']['type']) { |
||
| 314 | case "embedded": |
||
| 315 | break; |
||
| 316 | case "eduPKI": |
||
| 317 | try { |
||
| 318 | $soap = SilverbulletCertificate::initEduPKISoapSession(); |
||
| 319 | $soapRevocationSerial = $soap->newRevocationRequest($this->serial, ""); |
||
| 320 | if ($soapRevocationSerial == 0) { |
||
| 321 | throw new Exception("Unable to create revocation request, serial number was zero."); |
||
| 322 | } |
||
| 323 | // retrieve the raw request to prepare for signature and approval |
||
| 324 | $soapRawRevRequest = $soap->getRawRevocationRequest($soapRevocationSerial); |
||
| 325 | if (strlen($soapRawRevRequest) < 10) { // very basic error handling |
||
| 326 | throw new Exception("Suspiciously short data to sign!"); |
||
| 327 | } |
||
| 328 | // for obnoxious reasons, we have to dump the request into a file and let pkcs7_sign read from the file |
||
| 329 | // rather than just using the string. Grr. |
||
| 330 | $tempdir = \core\common\Entity::createTemporaryDirectory("test"); |
||
| 331 | file_put_contents($tempdir['dir'] . "/content.txt", $soapRawRevRequest); |
||
| 332 | // retrieve our RA cert from filesystem |
||
| 333 | $raCertFile = file_get_contents(ROOT . "../edupki-test-ra.pem"); |
||
| 334 | $raCert = openssl_x509_read($raCertFile); |
||
| 335 | $raKey = openssl_pkey_get_private("file://" . ROOT . "../edupki-test-ra.clearkey"); |
||
| 336 | // sign the data |
||
| 337 | if (openssl_pkcs7_sign($tempdir['dir'] . "/content.txt", $tempdir['dir'] . "/signature.txt", $raCert, $raKey) === FALSE) { |
||
| 338 | throw new Exception("Unable to sign the revocation approval data!"); |
||
| 339 | } |
||
| 340 | // and get the signature blob back from the filesystem |
||
| 341 | $detachedSig = file_get_contents($tempdir['dir'] . "/signature.txt"); |
||
| 342 | $soapIssueRev = $soap->approveRevocationRequest($soapRevocationSerial, $soapRawRevRequest, $detachedSig); |
||
| 343 | if ($soapIssueRev === FALSE) { |
||
| 344 | throw new Exception("The locally approved revocation request was NOT processed by the CA."); |
||
| 345 | } |
||
| 346 | } catch (Exception $e) { |
||
| 347 | // PHP 7.1 can do this much better |
||
| 348 | if (is_soap_fault($e)) { |
||
| 349 | throw new Exception("Error when sending SOAP request: " . "{$e->faultcode}: {$e->faultstring}\n"); |
||
| 350 | } |
||
| 351 | throw new Exception("Something odd happened while doing the SOAP request:", $e->getMessage()); |
||
| 352 | } |
||
| 353 | break; |
||
| 354 | default: |
||
| 355 | throw new Exception("Unknown type of CA requested!"); |
||
| 356 | } |
||
| 357 | // what happens wrt OCSP etc. is really something for the following function to decide. We just call it. |
||
| 358 | $certObject->triggerNewOCSPStatement(); |
||
| 359 | } |
||
| 360 | |||
| 361 | /** |
||
| 362 | * create a CSR |
||
| 363 | * |
||
| 364 | * @param resource $privateKey the private key to create the CSR with |
||
| 365 | * @return array with the CSR and some meta info |
||
| 366 | */ |
||
| 367 | private static function generateCsr($privateKey, $fed, $realm) { |
||
| 368 | $databaseHandle = DBConnection::handle("INST"); |
||
| 369 | $loggerInstance = new common\Logging(); |
||
| 370 | $usernameIsUnique = FALSE; |
||
| 371 | $username = ""; |
||
| 372 | while ($usernameIsUnique === FALSE) { |
||
| 373 | $usernameLocalPart = common\Entity::randomString(64 - 1 - strlen($realm), "0123456789abcdefghijklmnopqrstuvwxyz"); |
||
| 374 | $username = $usernameLocalPart . "@" . $realm; |
||
| 375 | $uniquenessQuery = $databaseHandle->exec("SELECT cn from silverbullet_certificate WHERE cn = ?", "s", $username); |
||
| 376 | // SELECT -> resource, not boolean |
||
| 377 | if (mysqli_num_rows(/** @scrutinizer ignore-type */ $uniquenessQuery) == 0) { |
||
| 378 | $usernameIsUnique = TRUE; |
||
| 379 | } |
||
| 380 | } |
||
| 381 | |||
| 382 | $loggerInstance->debug(5, "generateCertificate: generating private key.\n"); |
||
| 383 | |||
| 384 | $newCsr = openssl_csr_new( |
||
| 385 | ['O' => CONFIG_CONFASSISTANT['CONSORTIUM']['name'], |
||
| 386 | 'OU' => $fed, |
||
| 387 | 'CN' => $username, |
||
| 388 | 'emailAddress' => $username, |
||
| 389 | ], $privateKey, [ |
||
| 390 | 'digest_alg' => 'sha256', |
||
| 391 | 'req_extensions' => 'v3_req', |
||
| 392 | ] |
||
| 393 | ); |
||
| 394 | if ($newCsr === FALSE) { |
||
| 395 | throw new Exception("Unable to create a CSR!"); |
||
| 396 | } |
||
| 397 | return [ |
||
| 398 | "CSR" => $newCsr, |
||
| 399 | "USERNAME" => $username |
||
| 400 | ]; |
||
| 401 | } |
||
| 402 | |||
| 403 | private static function initEduPKISoapSession() { |
||
| 429 | } |
||
| 430 | |||
| 431 | /** |
||
| 432 | * take a CSR and sign it with our issuing CA's certificate |
||
| 433 | * |
||
| 434 | * @param mixed $csr the CSR |
||
| 435 | * @param int $expiryDays the number of days until the cert is going to expire |
||
| 436 | * @return array the cert and some meta info |
||
| 437 | */ |
||
| 438 | private static function signCsr($csr, $expiryDays) { |
||
| 554 |