Passed
Push — master ( b52463...f9f605 )
by Stefan
15:46 queued 08:00
created

SilverbulletCertificate::revokeCertificate()   B

Complexity

Conditions 9
Paths 35

Size

Total Lines 55
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 35
dl 0
loc 55
rs 8.0555
c 0
b 0
f 0
cc 9
nc 35
nop 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/*
4
 * ******************************************************************************
5
 * Copyright 2011-2017 DANTE Ltd. and GÉANT on behalf of the GN3, GN3+, GN4-1 
6
 * and GN4-2 consortia
7
 *
8
 * License: see the web/copyright.php file in the file structure
9
 * ******************************************************************************
10
 */
11
12
/**
13
 * This file contains the SilverbulletInvitation class.
14
 *
15
 * @author Stefan Winter <[email protected]>
16
 * @author Tomasz Wolniewicz <[email protected]>
17
 *
18
 * @package Developer
19
 *
20
 */
21
22
namespace core;
23
24
use \Exception;
25
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) {
132
        $loggerInstance = new common\Logging();
133
        $databaseHandle = DBConnection::handle("INST");
134
        $loggerInstance->debug(5, "generateCertificate() - starting.\n");
135
        $invitationObject = new SilverbulletInvitation($token);
136
        $profile = new ProfileSilverbullet($invitationObject->profile);
137
        $inst = new IdP($profile->institution);
138
        $loggerInstance->debug(5, "tokenStatus: done, got " . $invitationObject->invitationTokenStatus . ", " . $invitationObject->profile . ", " . $invitationObject->userId . ", " . $invitationObject->expiry . ", " . $invitationObject->invitationTokenString . "\n");
139
        if ($invitationObject->invitationTokenStatus != SilverbulletInvitation::SB_TOKENSTATUS_VALID && $invitationObject->invitationTokenStatus != SilverbulletInvitation::SB_TOKENSTATUS_PARTIALLY_REDEEMED) {
140
            throw new Exception("Attempt to generate a SilverBullet installer with an invalid/redeemed/expired token. The user should never have gotten that far!");
141
        }
142
143
        // SQL query to find the expiry date of the *user* to find the correct ValidUntil for the cert
144
        $user = $invitationObject->userId;
145
        $userrow = $databaseHandle->exec("SELECT expiry FROM silverbullet_user WHERE id = ?", "i", $user);
146
        // SELECT -> resource, not boolean
147
        if ($userrow->num_rows != 1) {
148
            throw new Exception("Despite a valid token, the corresponding user was not found in database or database query error!");
149
        }
150
        $expiryObject = mysqli_fetch_object(/** @scrutinizer ignore-type */ $userrow);
151
        $loggerInstance->debug(5, "EXP: " . $expiryObject->expiry . "\n");
152
        $expiryDateObject = date_create_from_format("Y-m-d H:i:s", $expiryObject->expiry);
153
        if ($expiryDateObject === FALSE) {
154
            throw new Exception("The expiry date we got from the DB is bogus!");
155
        }
156
        $loggerInstance->debug(5, $expiryDateObject->format("Y-m-d H:i:s") . "\n");
157
        // date_create with no parameters can't fail, i.e. is never FALSE
158
        $validity = date_diff(/** @scrutinizer ignore-type */ date_create(), $expiryDateObject);
159
        $expiryDays = $validity->days + 1;
160
        if ($validity->invert == 1) { // negative! That should not be possible
161
            throw new Exception("Attempt to generate a certificate for a user which is already expired!");
162
        }
163
164
        $privateKey = openssl_pkey_new(['private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA, 'encrypt_key' => FALSE]);
165
166
        $csr = SilverbulletCertificate::generateCsr($privateKey, strtoupper($inst->federation), $profile->getAttributes("internal:realm")[0]['value']);
167
168
        $loggerInstance->debug(5, "generateCertificate: proceeding to sign cert.\n");
169
170
        $certMeta = SilverbulletCertificate::signCsr($csr, $expiryDays);
171
        $cert = $certMeta["CERT"];
172
        $issuingCaPem = $certMeta["ISSUER"];
173
        $rootCaPem = $certMeta["ROOT"];
174
        $serial = $certMeta["SERIAL"];
175
176
        $loggerInstance->debug(5, "generateCertificate: post-processing certificate.\n");
177
178
        // with the cert, our private key and import password, make a PKCS#12 container out of it
179
        $exportedCertProt = "";
180
        openssl_pkcs12_export($cert, $exportedCertProt, $privateKey, $importPassword, ['extracerts' => [$issuingCaPem /* , $rootCaPem */]]);
181
        $exportedCertClear = "";
182
        openssl_pkcs12_export($cert, $exportedCertClear, $privateKey, "", ['extracerts' => [$issuingCaPem, $rootCaPem]]);
183
        // 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!
184
        // we need the *real* expiry date, not just the day-approximation
185
        $x509 = new \core\common\X509();
186
        $certString = "";
187
        openssl_x509_export($cert, $certString);
188
        $parsedCert = $x509->processCertificate($certString);
189
        $loggerInstance->debug(5, "CERTINFO: " . print_r($parsedCert['full_details'], true));
190
        $realExpiryDate = date_create_from_format("U", $parsedCert['full_details']['validTo_time_t'])->format("Y-m-d H:i:s");
191
192
        // store new cert info in DB
193
        $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);
194
        // newborn cert immediately gets its "valid" OCSP response
195
        $certObject = new SilverbulletCertificate($serial);
196
        $certObject->triggerNewOCSPStatement();
197
// return PKCS#12 data stream
198
        return [
199
            "certObject" => $certObject,
200
            "certdata" => $exportedCertProt,
201
            "certdataclear" => $exportedCertClear,
202
            "sha1" => openssl_x509_fingerprint($cert, "sha1"),
0 ignored issues
show
Bug introduced by
$cert of type resource is incompatible with the type string expected by parameter $x509 of openssl_x509_fingerprint(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

202
            "sha1" => openssl_x509_fingerprint(/** @scrutinizer ignore-type */ $cert, "sha1"),
Loading history...
203
            "sha256" => openssl_x509_fingerprint($cert, "sha256"),
204
            'importPassword' => $importPassword,
205
            'GUID' => common\Entity::uuid("", $exportedCertProt),
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) {
0 ignored issues
show
Bug introduced by
The call to openssl_pkcs7_sign() has too few arguments starting with headers. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

337
                    if (/** @scrutinizer ignore-call */ openssl_pkcs7_sign($tempdir['dir'] . "/content.txt", $tempdir['dir'] . "/signature.txt", $raCert, $raKey) === FALSE) {

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
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());
0 ignored issues
show
Bug introduced by
$e->getMessage() of type string is incompatible with the type integer expected by parameter $code of Exception::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

351
                    throw new Exception("Something odd happened while doing the SOAP request:", /** @scrutinizer ignore-type */ $e->getMessage());
Loading history...
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() {
404
        // initialse connection to eduPKI CA / eduroam RA
405
        $soap = new \SoapClient(
406
                "https://ra.edupki.org/edupki-test-ca/cgi-bin/ra/soap?wsdl=1", [
407
            'soap_version' => SOAP_1_1,
408
            'trace' => TRUE,
409
            'exceptions' => TRUE,
410
            'connection_timeout' => 5, // if can't establish the connection within 5 sec, something's wrong
411
            'cache_wsdl' => WSDL_CACHE_NONE,
412
            'user_agent' => 'eduroam CAT to eduPKI SOAP Interface',
413
            'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
414
            'stream_context' => stream_context_create(
415
                    [
416
                        'https' => [
417
                            'timeout' => 60,
418
                        ],
419
                        'ssl' => [
420
                            // 'verify_peer' => true,
421
                            // 'cafile' => $root,
422
                            'verify_depth' => 3,
423
                        ],
424
                    ]
425
            ),
426
                ]
427
        );
428
        return $soap;
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) {
439
        $loggerInstance = new common\Logging();
440
        $databaseHandle = DBConnection::handle("INST");
441
        switch (CONFIG_CONFASSISTANT['SILVERBULLET']['CA']['type']) {
442
            case "embedded":
443
                $rootCaPem = file_get_contents(ROOT . "/config/SilverbulletClientCerts/rootca.pem");
444
                $raCertFile = file_get_contents(ROOT . "/config/SilverbulletClientCerts/real.pem");
445
                $raCert = openssl_x509_read($raCertFile);
446
                $raKey = openssl_pkey_get_private("file://" . ROOT . "/config/SilverbulletClientCerts/real.key");
447
                $nonDupSerialFound = FALSE;
448
                do {
449
                    $serial = random_int(1000000000, PHP_INT_MAX);
450
                    $dupeQuery = $databaseHandle->exec("SELECT serial_number FROM silverbullet_certificate WHERE serial_number = ?", "i", $serial);
451
                    // SELECT -> resource, not boolean
452
                    if (mysqli_num_rows(/** @scrutinizer ignore-type */$dupeQuery) == 0) {
453
                        $nonDupSerialFound = TRUE;
454
                    }
455
                } while (!$nonDupSerialFound);
456
                $loggerInstance->debug(5, "generateCertificate: signing imminent with unique serial $serial.\n");
457
                return [
458
                    "CERT" => openssl_csr_sign($csr["CSR"], $raCert, $raKey, $expiryDays, ['digest_alg' => 'sha256'], $serial),
459
                    "SERIAL" => $serial,
460
                    "ISSUER" => $raCertFile,
461
                    "ROOT" => $rootCaPem,
462
                ];
463
            case "eduPKI":
464
                // initialse connection to eduPKI CA / eduroam RA and send the request to them
465
                try {
466
                    $soap = SilverbulletCertificate::initEduPKISoapSession();
467
                    $soapNewRequest = $soap->newRequest(
468
                            700, # RA-ID
469
                            $csr["CSR"], # Request im PEM-Format
470
                            [# Array mit den Subject Alternative Names
471
                        "email:" . $csr["USERNAME"]
472
                            ], "eduroam IdP and SP", # Zertifikatprofil
473
                            sha1("notused"), # PIN
474
                            $csr["USERNAME"], # Name des Antragstellers
475
                            "eduroam Managed IdP", # Organisationseinheit des Antragstellers
476
                            true                   # Veröffentlichen des Zertifikats?
477
                    );
478
                    if ($soapNewRequest == 0) {
479
                        throw new Exception("Error when sending SOAP request (request serial number was zero). No further details available.");
480
                    }
481
                    $soapReqnum = intval($soapNewRequest);
482
                    // tell the CA the desired expiry date of the new certificate
483
                    $expiry = new \DateTime();
484
                    $expiry->modify("+$expiryDays day");
485
                    $expiry->setTimezone("UTC");
0 ignored issues
show
Bug introduced by
'UTC' of type string is incompatible with the type DateTimeZone expected by parameter $timezone of DateTime::setTimezone(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

485
                    $expiry->setTimezone(/** @scrutinizer ignore-type */ "UTC");
Loading history...
486
                    $soapExpiryChange = $soap->setRequestParameters(
487
                            $soapReqnum, [
488
                        "NotAfter" => $expiry->format('c'),
489
                            ]
490
                    );
491
                    if ($soapExpiryChange === FALSE) {
492
                        throw new Exception("Error when sending SOAP request (unable to change expiry date).");
493
                    }
494
                    // retrieve the raw request to prepare for signature and approval
495
                    $soapRawRequest = $soap->getRawRequest($soapReqnum);
496
                    if (strlen($soapRawRequest) < 10) { // very basic error handling
497
                        throw new Exception("Suspiciously short data to sign!");
498
                    }
499
                    // for obnoxious reasons, we have to dump the request into a file and let pkcs7_sign read from the file
500
                    // rather than just using the string. Grr.
501
                    $tempdir = \core\common\Entity::createTemporaryDirectory("test");
502
                    file_put_contents($tempdir['dir'] . "/content.txt", $soapRawRequest);
503
                    // retrieve our RA cert from filesystem
504
                    $raCertFile = file_get_contents(ROOT . "../edupki-test-ra.pem");
505
                    $raCert = openssl_x509_read($raCertFile);
506
                    $raKey = openssl_pkey_get_private("file://" . ROOT . "../edupki-test-ra.clearkey");
507
                    // sign the data
508
                    if (openssl_pkcs7_sign($tempdir['dir'] . "/content.txt", $tempdir['dir'] . "/signature.txt", $raCert, $raKey) === FALSE) {
0 ignored issues
show
Bug introduced by
The call to openssl_pkcs7_sign() has too few arguments starting with headers. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

508
                    if (/** @scrutinizer ignore-call */ openssl_pkcs7_sign($tempdir['dir'] . "/content.txt", $tempdir['dir'] . "/signature.txt", $raCert, $raKey) === FALSE) {

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
509
                        throw new Exception("Unable to sign the certificate approval data!");
510
                    }
511
                    // and get the signature blob back from the filesystem
512
                    $detachedSig = file_get_contents($tempdir['dir'] . "/signature.txt");
513
                    $soapIssueCert = $soap->approveRequest($soapReqnum, $soapRawRequest, $detachedSig);
514
                    if ($soapIssueCert === FALSE) {
515
                        throw new Exception("The locally approved request was NOT processed by the CA.");
516
                    }
517
                    // now, get the actual cert from the CA
518
                    $soapCert = $soap->getCertificateByRequestSerial($soapReqnum);
519
                    $x509 = new common\X509();
520
                    $parsedCert = $x509->processCertificate($soapCert);
521
                    if (!is_array($parsedCert)) {
522
                        throw new Exception("We did not actually get a certificate.");
523
                    }
524
                } catch (Exception $e) {
525
                    // PHP 7.1 can do this much better
526
                    if (is_soap_fault($e)) {
527
                        throw new Exception("Error when sending SOAP request: " . "{$e->faultcode}: {$e->faultstring}\n");
528
                    }
529
                    throw new Exception("Something odd happened while doing the SOAP request:", $e->getMessage());
0 ignored issues
show
Bug introduced by
$e->getMessage() of type string is incompatible with the type integer expected by parameter $code of Exception::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

529
                    throw new Exception("Something odd happened while doing the SOAP request:", /** @scrutinizer ignore-type */ $e->getMessage());
Loading history...
530
                }
531
                return [
532
                    "CERT" => openssl_x509_read($parsedCert['pem']),
533
                    "SERIAL" => $parsedCert['serial'],
534
                    "ISSUER" => $raCertFile, // change this to the actual eduPKI Issuer CA
535
                    "ROOT" => $rootCaPem, // change this to the actual eduPKI Root CA
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $rootCaPem seems to be never defined.
Loading history...
536
                ];
537
            default:
538
                /* HTTP POST the CSR to the CA with the $expiryDays as parameter
539
                 * on successful execution, gets back a PEM file which is the
540
                 * certificate (structure TBD)
541
                 * $httpResponse = httpRequest("https://clientca.hosted.eduroam.org/issue/", ["csr" => $csr, "expiry" => $expiryDays ] );
542
                 *
543
                 * The result of this if clause has to be a certificate in PHP's 
544
                 * "openssl_object" style (like the one that openssl_csr_sign would 
545
                 * produce), to be stored in the variable $cert; we also need the
546
                 * serial - which can be extracted from the received cert and has
547
                 * to be stored in $serial.
548
                 */
549
                throw new Exception("External silverbullet CA is not implemented yet!");
550
        }
551
    }
552
553
}
554