Total Complexity | 43 |
Total Lines | 442 |
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 |
||
35 | class SilverbulletCertificate extends EntityWithDBProperties { |
||
36 | |||
37 | public $username; |
||
38 | public $expiry; |
||
39 | public $serial; |
||
40 | public $dbId; |
||
41 | public $invitationId; |
||
42 | public $userId; |
||
43 | public $profileId; |
||
44 | public $issued; |
||
45 | public $device; |
||
46 | public $revocationStatus; |
||
47 | public $revocationTime; |
||
48 | public $ocsp; |
||
49 | public $ocspTimestamp; |
||
50 | public $status; |
||
51 | public $ca_type; |
||
52 | public $annotation; |
||
53 | |||
54 | const CERTSTATUS_VALID = 1; |
||
55 | const CERTSTATUS_EXPIRED = 2; |
||
56 | const CERTSTATUS_REVOKED = 3; |
||
57 | const CERTSTATUS_INVALID = 4; |
||
58 | |||
59 | /** |
||
60 | * instantiates an existing certificate, identified either by its serial |
||
61 | * number or the username. |
||
62 | * |
||
63 | * Use static issueCertificate() to generate a whole new cert. |
||
64 | * |
||
65 | * @param int|string $identifier identify certificate either by CN or by serial |
||
66 | * @param string $certtype RSA or ECDSA? |
||
67 | */ |
||
68 | public function __construct($identifier, $certtype) { |
||
69 | $this->databaseType = "INST"; |
||
70 | parent::__construct(); |
||
71 | $this->username = ""; |
||
72 | $this->expiry = "2000-01-01 00:00:00"; |
||
73 | $this->serial = -1; |
||
74 | $this->dbId = -1; |
||
75 | $this->invitationId = -1; |
||
76 | $this->userId = -1; |
||
77 | $this->profileId = -1; |
||
78 | $this->issued = "2000-01-01 00:00:00"; |
||
79 | $this->device = NULL; |
||
80 | $this->revocationStatus = "REVOKED"; |
||
81 | $this->revocationTime = "2000-01-01 00:00:00"; |
||
82 | $this->ocsp = NULL; |
||
83 | $this->ocspTimestamp = "2000-01-01 00:00:00"; |
||
84 | $this->ca_type = $certtype; |
||
85 | $this->status = SilverbulletCertificate::CERTSTATUS_INVALID; |
||
86 | $this->annotation = NULL; |
||
87 | |||
88 | $incoming = FALSE; |
||
89 | if (is_numeric($identifier)) { |
||
90 | $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`, `extrainfo` FROM `silverbullet_certificate` WHERE serial_number = ? AND ca_type = ?", "is", $identifier, $certtype); |
||
91 | } else { // it's a string instead |
||
92 | $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`, `extrainfo` FROM `silverbullet_certificate` WHERE cn = ? AND ca_type = ?", "ss", $identifier, $certtype); |
||
93 | } |
||
94 | |||
95 | // SELECT -> mysqli_resource, not boolean |
||
96 | while ($oneResult = mysqli_fetch_object(/** @scrutinizer ignore-type */ $incoming)) { // there is only at most one |
||
97 | $this->username = $oneResult->cn; |
||
98 | $this->expiry = $oneResult->expiry; |
||
99 | $this->serial = $oneResult->serial_number; |
||
100 | $this->dbId = $oneResult->id; |
||
101 | $this->invitationId = $oneResult->silverbullet_invitation_id; |
||
102 | $this->userId = $oneResult->silverbullet_user_id; |
||
103 | $this->profileId = $oneResult->profile_id; |
||
104 | $this->issued = $oneResult->issued; |
||
105 | $this->device = $oneResult->device; |
||
106 | $this->revocationStatus = $oneResult->revocation_status; |
||
107 | $this->revocationTime = $oneResult->revocation_time; |
||
108 | $this->ocsp = $oneResult->OCSP; |
||
109 | $this->ocspTimestamp = $oneResult->OCSP_timestamp; |
||
110 | $this->annotation = $oneResult->extrainfo; |
||
111 | // is the cert expired? |
||
112 | $now = new \DateTime(); |
||
113 | $cert_expiry = new \DateTime($this->expiry); |
||
114 | $delta = $now->diff($cert_expiry); |
||
115 | $this->status = ($delta->invert == 1 ? SilverbulletCertificate::CERTSTATUS_EXPIRED : SilverbulletCertificate::CERTSTATUS_VALID); |
||
116 | // expired is expired; even if it was previously revoked. But do update status for revoked ones... |
||
117 | if ($this->status == SilverbulletCertificate::CERTSTATUS_VALID && $this->revocationStatus == "REVOKED") { |
||
118 | $this->status = SilverbulletCertificate::CERTSTATUS_REVOKED; |
||
119 | } |
||
120 | } |
||
121 | } |
||
122 | |||
123 | /** |
||
124 | * retrieve basic information about the certificate |
||
125 | * |
||
126 | * @return array of basic certificate details |
||
127 | */ |
||
128 | public function getBasicInfo() { |
||
129 | $returnArray = []; // unnecessary because the iterator below is never empty, but Scrutinizer gets excited nontheless |
||
130 | foreach (['status', 'serial', 'username', 'issued', 'expiry', 'ca_type', 'annotation'] as $key) { |
||
131 | $returnArray[$key] = $this->$key; |
||
132 | } |
||
133 | $returnArray['device'] = \devices\Devices::listDevices()[$this->device]['display'] ?? $this->device; |
||
134 | return $returnArray; |
||
135 | } |
||
136 | |||
137 | /** |
||
138 | * adds extra information about the certificate to the DB |
||
139 | * |
||
140 | * @param array $annotation information to be stored |
||
141 | * @return void |
||
142 | */ |
||
143 | public function annotate($annotation) { |
||
147 | } |
||
148 | /** |
||
149 | * we don't use caching in SB, so this function does nothing |
||
150 | * |
||
151 | * @return void |
||
152 | */ |
||
153 | public function updateFreshness() { |
||
154 | // nothing to be done here. |
||
155 | } |
||
156 | |||
157 | /** |
||
158 | * issue a certificate based on a token |
||
159 | * |
||
160 | * @param string $token the token string |
||
161 | * @param string $importPassword the PIN |
||
162 | * @param string $certtype is this for the RSA or ECDSA CA? |
||
163 | * @return array |
||
164 | */ |
||
165 | public static function issueCertificate($token, $importPassword, $certtype) { |
||
166 | $loggerInstance = new common\Logging(); |
||
167 | $databaseHandle = DBConnection::handle("INST"); |
||
168 | $loggerInstance->debug(5, "generateCertificate() - starting.\n"); |
||
169 | $invitationObject = new SilverbulletInvitation($token); |
||
170 | $profile = new ProfileSilverbullet($invitationObject->profile); |
||
171 | $inst = new IdP($profile->institution); |
||
172 | $loggerInstance->debug(5, "tokenStatus: done, got " . $invitationObject->invitationTokenStatus . ", " . $invitationObject->profile . ", " . $invitationObject->userId . ", " . $invitationObject->expiry . ", " . $invitationObject->invitationTokenString . "\n"); |
||
173 | if ($invitationObject->invitationTokenStatus != SilverbulletInvitation::SB_TOKENSTATUS_VALID && $invitationObject->invitationTokenStatus != SilverbulletInvitation::SB_TOKENSTATUS_PARTIALLY_REDEEMED) { |
||
174 | throw new Exception("Attempt to generate a SilverBullet installer with an invalid/redeemed/expired token. The user should never have gotten that far!"); |
||
175 | } |
||
176 | |||
177 | // SQL query to find the expiry date of the *user* to find the correct ValidUntil for the cert |
||
178 | $user = $invitationObject->userId; |
||
179 | $userrow = $databaseHandle->exec("SELECT expiry FROM silverbullet_user WHERE id = ?", "i", $user); |
||
180 | // SELECT -> resource, not boolean |
||
181 | if ($userrow->num_rows != 1) { |
||
182 | throw new Exception("Despite a valid token, the corresponding user was not found in database or database query error!"); |
||
183 | } |
||
184 | $expiryObject = mysqli_fetch_object(/** @scrutinizer ignore-type */ $userrow); |
||
185 | $loggerInstance->debug(5, "EXP: " . $expiryObject->expiry . "\n"); |
||
186 | $expiryDateObject = date_create_from_format("Y-m-d H:i:s", $expiryObject->expiry); |
||
187 | if ($expiryDateObject === FALSE) { |
||
188 | throw new Exception("The expiry date we got from the DB is bogus!"); |
||
189 | } |
||
190 | $loggerInstance->debug(5, $expiryDateObject->format("Y-m-d H:i:s") . "\n"); |
||
191 | // date_create with no parameters can't fail, i.e. is never FALSE |
||
192 | $validity = date_diff(/** @scrutinizer ignore-type */ date_create(), $expiryDateObject); |
||
193 | $expiryDays = $validity->days + 1; |
||
194 | if ($validity->invert == 1) { // negative! That should not be possible |
||
195 | throw new Exception("Attempt to generate a certificate for a user which is already expired!"); |
||
196 | } |
||
197 | switch ($certtype) { |
||
198 | case \devices\Devices::SUPPORT_RSA: |
||
199 | $privateKey = openssl_pkey_new(['private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA, 'encrypt_key' => FALSE]); |
||
200 | break; |
||
201 | case \devices\Devices::SUPPORT_ECDSA: |
||
202 | $privateKey = openssl_pkey_new(['curve_name' => 'secp384r1', 'private_key_type' => OPENSSL_KEYTYPE_EC, 'encrypt_key' => FALSE]); |
||
203 | break; |
||
204 | default: |
||
205 | throw new Exception("Unknown certificate type!"); |
||
206 | } |
||
207 | |||
208 | $csr = SilverbulletCertificate::generateCsr($privateKey, strtoupper($inst->federation), $profile->getAttributes("internal:realm")[0]['value'], $certtype); |
||
209 | |||
210 | $loggerInstance->debug(5, "generateCertificate: proceeding to sign cert.\n"); |
||
211 | |||
212 | $certMeta = SilverbulletCertificate::signCsr($csr["CSR"], $expiryDays, $certtype); |
||
213 | $cert = $certMeta["CERT"]; |
||
214 | $issuingCaPem = $certMeta["ISSUER"]; |
||
215 | $rootCaPem = $certMeta["ROOT"]; |
||
216 | $serial = $certMeta["SERIAL"]; |
||
217 | |||
218 | if ($cert === FALSE) { |
||
219 | throw new Exception("The CA did not generate a certificate."); |
||
220 | } |
||
221 | $loggerInstance->debug(5, "generateCertificate: post-processing certificate.\n"); |
||
222 | |||
223 | // get the SHA1 fingerprint, this will be handy for Windows installers |
||
224 | $sha1 = openssl_x509_fingerprint($cert, "sha1"); |
||
225 | // with the cert, our private key and import password, make a PKCS#12 container out of it |
||
226 | $exportedCertProt = ""; |
||
227 | openssl_pkcs12_export($cert, $exportedCertProt, $privateKey, $importPassword, ['extracerts' => [$issuingCaPem /* , $rootCaPem */]]); |
||
228 | // and without intermediate, to keep EAP conversation short where possible |
||
229 | $exportedNoInterm = ""; |
||
230 | openssl_pkcs12_export($cert, $exportedNoInterm, $privateKey, $importPassword, []); |
||
231 | $exportedCertClear = ""; |
||
232 | openssl_pkcs12_export($cert, $exportedCertClear, $privateKey, "", ['extracerts' => [$issuingCaPem, $rootCaPem]]); |
||
233 | // 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! |
||
234 | // we need the *real* expiry date, not just the day-approximation |
||
235 | $x509 = new \core\common\X509(); |
||
236 | $certString = ""; |
||
237 | openssl_x509_export($cert, $certString); |
||
238 | $parsedCert = $x509->processCertificate($certString); |
||
239 | $loggerInstance->debug(5, "CERTINFO: " . print_r($parsedCert['full_details'], true)); |
||
240 | $realExpiryDate = date_create_from_format("U", $parsedCert['full_details']['validTo_time_t'])->format("Y-m-d H:i:s"); |
||
241 | |||
242 | // store new cert info in DB |
||
243 | $databaseHandle->exec("INSERT INTO `silverbullet_certificate` (`profile_id`, `silverbullet_user_id`, `silverbullet_invitation_id`, `serial_number`, `cn` ,`expiry`, `ca_type`) VALUES (?, ?, ?, ?, ?, ?, ?)", "iiissss", $invitationObject->profile, $invitationObject->userId, $invitationObject->identifier, $serial, $csr["USERNAME"], $realExpiryDate, $certtype); |
||
244 | // newborn cert immediately gets its "valid" OCSP response |
||
245 | $certObject = new SilverbulletCertificate($serial, $certtype); |
||
246 | $certObject->triggerNewOCSPStatement(); |
||
247 | // return PKCS#12 data stream |
||
248 | return [ |
||
249 | "certObject" => $certObject, |
||
250 | "certdata" => $exportedCertProt, |
||
251 | "certdata_nointermediate" => $exportedNoInterm, |
||
252 | "certdataclear" => $exportedCertClear, |
||
253 | "sha1" => $sha1, |
||
254 | 'importPassword' => $importPassword, |
||
255 | 'GUID' => common\Entity::uuid("", $exportedCertProt), |
||
256 | ]; |
||
257 | } |
||
258 | |||
259 | /** |
||
260 | * triggers a new OCSP statement for the given serial number |
||
261 | * |
||
262 | * @return string DER-encoded OCSP status info (binary data!) |
||
263 | */ |
||
264 | public function triggerNewOCSPStatement() { |
||
345 | } |
||
346 | |||
347 | /** |
||
348 | * revokes a certificate |
||
349 | * @return array with revocation information |
||
350 | */ |
||
351 | public function revokeCertificate() { |
||
352 | $nowSql = (new \DateTime())->format("Y-m-d H:i:s"); |
||
353 | if (CONFIG_CONFASSISTANT['SILVERBULLET']['CA']['type'] != "embedded") { |
||
354 | // send revocation request to CA. |
||
355 | // $httpResponse = httpRequest("https://clientca.hosted.eduroam.org/revoke/", ["serial" => $serial ] ); |
||
356 | throw new Exception("External silverbullet CA is not implemented yet!"); |
||
357 | } |
||
358 | // regardless if embedded or not, always keep local state in our own DB |
||
359 | $this->databaseHandle->exec("UPDATE silverbullet_certificate SET revocation_status = 'REVOKED', revocation_time = ? WHERE serial_number = ? AND ca_type = ?", "sis", $nowSql, $this->serial, $this->ca_type); |
||
360 | $this->loggerInstance->debug(2, "Certificate revocation status for $this->serial updated, about to call triggerNewOCSPStatement().\n"); |
||
361 | // newly instantiate us, DB content has changed... |
||
362 | $certObject = new SilverbulletCertificate($this->serial, $this->ca_type); |
||
363 | $certObject->triggerNewOCSPStatement(); |
||
364 | } |
||
365 | |||
366 | /** |
||
367 | * create a CSR |
||
368 | * |
||
369 | * @param resource $privateKey the private key to create the CSR with |
||
370 | * @param string $fed the federation to which the certificate belongs |
||
371 | * @param string $realm the realm for the future username |
||
372 | * @param string $certtype which type of certificate to generate: RSA or ECDSA |
||
373 | * @return array with the CSR and some meta info |
||
374 | */ |
||
375 | private static function generateCsr($privateKey, $fed, $realm, $certtype) { |
||
418 | ]; |
||
419 | } |
||
420 | |||
421 | /** |
||
422 | * take a CSR and sign it with our issuing CA's certificate |
||
423 | * |
||
424 | * @param mixed $csr the CSR |
||
425 | * @param int $expiryDays the number of days until the cert is going to expire |
||
426 | * @param string $certtype which type of certificate to use for signing |
||
427 | * @return array the cert and some meta info |
||
428 | */ |
||
429 | private static function signCsr($csr, $expiryDays, $certtype) { |
||
477 | } |
||
478 | } |
||
481 |