Passed
Branch master (4eb06b)
by Stefan
08:42
created

SilverbulletCertificate::generateCsr()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 33
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 24
nc 6
nop 3
dl 0
loc 33
rs 9.536
c 0
b 0
f 0
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();
0 ignored issues
show
Bug introduced by
The call to core\SilverbulletCertifi...initEduPKISoapSession() has too few arguments starting with type. ( Ignorable by Annotation )

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

318
                    /** @scrutinizer ignore-call */ 
319
                    $soap = SilverbulletCertificate::initEduPKISoapSession();

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...
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($type) {
404
        // set context parameters common to both endpoints
405
        $context_params = [
406
            'http' => [
407
                'timeout' => 60,
408
                'user_agent' => 'Stefan',
409
                'protocol_version' => 1.1
410
            ],
411
            'ssl' => [
412
                'verify_peer' => true,
413
                'verify_peer_name' => true,
414
                // below is the CA "/C=DE/O=Deutsche Telekom AG/OU=T-TeleSec Trust Center/CN=Deutsche Telekom Root CA 2"
415
                'cafile' => ROOT . "/config/SilverbulletClientCerts/eduPKI-webserver-root.pem",
416
                'verify_depth' => 5,
417
                'capture_peer_cert' => true,
418
            ],
419
        ];
420
        $url = "";
421
        switch ($type) {
422
            case "PUBLIC":
423
                $url = "https://pki.edupki.org/edupki-test-ca/cgi-bin/pub/soap?wsdl=1";
424
                $context_params['ssl']['peer_name'] = 'pki.edupki.org';
425
                break;
426
            case "RA":
427
                $url = "https://ra.edupki.org/edupki-test-ca/cgi-bin/ra/soap?wsdl=1";
428
                $context_params['ssl']['peer_name'] = 'ra.edupki.org';
429
                break;
430
            default:
431
                throw new Exception("Unknown type of eduPKI interface requested.");
432
        }
433
        if ($type == "RA") { // add client auth parameters to the context
434
            $context_params['ssl']['local_cert'] = ROOT . "/config/SilverbulletClientCerts/edupki-test-ra.pem";
435
            $context_params['ssl']['local_pk'] = ROOT . "/config/SilverbulletClientCerts/edupki-test-ra.key";
436
            $context_params['ssl']['passphrase'] = '...';
437
        }
438
        // initialse connection to eduPKI CA / eduroam RA
439
        $soap = new \SoapClient($url, [
440
            'soap_version' => SOAP_1_1,
441
            'trace' => TRUE,
442
            'exceptions' => TRUE,
443
            'connection_timeout' => 5, // if can't establish the connection within 5 sec, something's wrong
444
            'cache_wsdl' => WSDL_CACHE_NONE,
445
            'user_agent' => 'eduroam CAT to eduPKI SOAP Interface',
446
            'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
447
            'stream_context' => stream_context_create($context_params),
448
                ]
449
        );
450
        return $soap;
451
    }
452
453
    const EDUPKI_RA_ID = 700;
454
    const EDUPKI_CERT_PROFILE = "eduroam IdP and SP";
455
456
    /**
457
     * take a CSR and sign it with our issuing CA's certificate
458
     * 
459
     * @param mixed $csr the CSR
460
     * @param int $expiryDays the number of days until the cert is going to expire
461
     * @return array the cert and some meta info
462
     */
463
    private static function signCsr($csr, $expiryDays) {
464
        $loggerInstance = new common\Logging();
465
        $databaseHandle = DBConnection::handle("INST");
466
        switch (CONFIG_CONFASSISTANT['SILVERBULLET']['CA']['type']) {
467
            case "embedded":
468
                $rootCaPem = file_get_contents(ROOT . "/config/SilverbulletClientCerts/rootca.pem");
469
                $raCertFile = file_get_contents(ROOT . "/config/SilverbulletClientCerts/real.pem");
470
                $raCert = openssl_x509_read($raCertFile);
471
                $raKey = openssl_pkey_get_private("file://" . ROOT . "/config/SilverbulletClientCerts/real.key");
472
                $nonDupSerialFound = FALSE;
473
                do {
474
                    $serial = random_int(1000000000, PHP_INT_MAX);
475
                    $dupeQuery = $databaseHandle->exec("SELECT serial_number FROM silverbullet_certificate WHERE serial_number = ?", "i", $serial);
476
                    // SELECT -> resource, not boolean
477
                    if (mysqli_num_rows(/** @scrutinizer ignore-type */$dupeQuery) == 0) {
478
                        $nonDupSerialFound = TRUE;
479
                    }
480
                } while (!$nonDupSerialFound);
481
                $loggerInstance->debug(5, "generateCertificate: signing imminent with unique serial $serial.\n");
482
                return [
483
                    "CERT" => openssl_csr_sign($csr["CSR"], $raCert, $raKey, $expiryDays, ['digest_alg' => 'sha256'], $serial),
484
                    "SERIAL" => $serial,
485
                    "ISSUER" => $raCertFile,
486
                    "ROOT" => $rootCaPem,
487
                ];
488
            case "eduPKI":
489
                // initialse connection to eduPKI CA / eduroam RA and send the request to them
490
                try {
491
                    $csrText = "";
492
                    openssl_csr_export($csr["CSR"], $csrText);
493
                    $soapPub = SilverbulletCertificate::initEduPKISoapSession("PUBLIC");
494
                    $loggerInstance->debug(5, "FIRST ACTUAL SOAP REQUEST (Public, newRequest)!\n");
495
                    $loggerInstance->debug(5, "PARAM_1: ".SilverbulletCertificate::EDUPKI_RA_ID."\n");
496
                    $loggerInstance->debug(5, "PARAM_2: $csrText\n");
497
                    $loggerInstance->debug(5, "PARAM_3: ".["email:" . $csr["USERNAME"]]);
0 ignored issues
show
Bug introduced by
Are you sure array('email:' . $csr['USERNAME']) of type array<integer,string> can be used in concatenation? ( Ignorable by Annotation )

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

497
                    $loggerInstance->debug(5, "PARAM_3: "./** @scrutinizer ignore-type */ ["email:" . $csr["USERNAME"]]);
Loading history...
498
                    $loggerInstance->debug(5, "PARAM_4: ".SilverbulletCertificate::EDUPKI_CERT_PROFILE."\n");
499
                    $loggerInstance->debug(5, "PARAM_5: ".sha1("notused")."\n");
500
                    $loggerInstance->debug(5, "PARAM_6: ".$csr["USERNAME"]."\n");
501
                    $loggerInstance->debug(5, "PARAM_7: ".ProfileSilverbullet::PRODUCTNAME."\n");
502
                    $loggerInstance->debug(5, "PARAM_8: true\n");
503
                    $soapNewRequest = $soapPub->newRequest(
504
                            SilverbulletCertificate::EDUPKI_RA_ID, # RA-ID
505
                            $csrText, # Request im PEM-Format
506
                            [# Array mit den Subject Alternative Names
507
                        "email:" . $csr["USERNAME"]
508
                            ], SilverbulletCertificate::EDUPKI_CERT_PROFILE, # Zertifikatprofil
509
                            sha1("notused"), # PIN
510
                            $csr["USERNAME"], # Name des Antragstellers
511
                            ProfileSilverbullet::PRODUCTNAME, # Organisationseinheit des Antragstellers
512
                            true                   # Veröffentlichen des Zertifikats?
513
                    );
514
                    $loggerInstance->debug(5, $soapPub->__getLastRequest());
515
                    $loggerInstance->debug(5, $soapPub->__getLastResponse());
516
                    if ($soapNewRequest == 0) {
517
                        throw new Exception("Error when sending SOAP request (request serial number was zero). No further details available.");
518
                    }
519
                    $soapReqnum = intval($soapNewRequest);
520
                } catch (Exception $e) {
521
                    // PHP 7.1 can do this much better
522
                    if (is_soap_fault($e)) {
523
                        throw new Exception("Error when sending SOAP request: " . "{$e->faultcode}: {$e->faultstring}\n");
524
                    }
525
                    throw new Exception("Something odd happened while doing the SOAP request:" . $e->getMessage());
526
                }
527
                try {
528
                    $soap = SilverbulletCertificate::initEduPKISoapSession("PUBLIC");
529
                    // tell the CA the desired expiry date of the new certificate
530
                    $expiry = new \DateTime();
531
                    $expiry->modify("+$expiryDays day");
532
                    $expiry->setTimezone(new \DateTimeZone("UTC"));
533
                    $soapExpiryChange = $soap->setRequestParameters(
534
                            $soapReqnum, [
535
                        "NotAfter" => $expiry->format('c'),
536
                            ]
537
                    );
538
                    if ($soapExpiryChange === FALSE) {
539
                        throw new Exception("Error when sending SOAP request (unable to change expiry date).");
540
                    }
541
                    // retrieve the raw request to prepare for signature and approval
542
                    $soapRawRequest = $soap->getRawRequest($soapReqnum);
543
                    if (strlen($soapRawRequest) < 10) { // very basic error handling
544
                        throw new Exception("Suspiciously short data to sign!");
545
                    }
546
                    // for obnoxious reasons, we have to dump the request into a file and let pkcs7_sign read from the file
547
                    // rather than just using the string. Grr.
548
                    $tempdir = \core\common\Entity::createTemporaryDirectory("test");
549
                    file_put_contents($tempdir['dir'] . "/content.txt", $soapRawRequest);
550
                    // retrieve our RA cert from filesystem
551
                    $raCertFile = file_get_contents(ROOT . "../edupki-test-ra.pem");
552
                    $raCert = openssl_x509_read($raCertFile);
553
                    $raKey = openssl_pkey_get_private("file://" . ROOT . "../edupki-test-ra.clearkey");
554
                    // sign the data
555
                    if (openssl_pkcs7_sign($tempdir['dir'] . "/content.txt", $tempdir['dir'] . "/signature.txt", $raCert, $raKey, []) === FALSE) {
556
                        throw new Exception("Unable to sign the certificate approval data!");
557
                    }
558
                    // and get the signature blob back from the filesystem
559
                    $detachedSig = file_get_contents($tempdir['dir'] . "/signature.txt");
560
                    $soapIssueCert = $soap->approveRequest($soapReqnum, $soapRawRequest, $detachedSig);
561
                    if ($soapIssueCert === FALSE) {
562
                        throw new Exception("The locally approved request was NOT processed by the CA.");
563
                    }
564
                    // now, get the actual cert from the CA
565
                    $soapCert = $soap->getCertificateByRequestSerial($soapReqnum);
566
                    $x509 = new common\X509();
567
                    $parsedCert = $x509->processCertificate($soapCert);
568
                    if (!is_array($parsedCert)) {
569
                        throw new Exception("We did not actually get a certificate.");
570
                    }
571
                    // let's get the CA certificate chain
572
                    $caInfo = $soap->getCAInfo();
573
                    $certList = $x509->splitCertificate($caInfo['CAChain']);
574
                    // find the root
575
                    $theRoot = "";
576
                    foreach ($certList as $oneCert) {
577
                        $content = $x509->processCertificate($oneCert);
578
                        if ($content['root'] == 1) {
579
                            $theRoot = $content;
580
                        }
581
                    }
582
                    if ($theRoot == "") {
583
                        throw new Exception("CAInfo has no root certificate for us!");
584
                    }
585
                } catch (Exception $e) {
586
                    // PHP 7.1 can do this much better
587
                    if (is_soap_fault($e)) {
588
                        throw new Exception("Error when sending SOAP request: " . "{$e->faultcode}: {$e->faultstring}\n");
589
                    }
590
                    throw new Exception("Something odd happened while doing the SOAP request:" . $e->getMessage());
591
                }
592
                return [
593
                    "CERT" => openssl_x509_read($parsedCert['pem']),
594
                    "SERIAL" => $parsedCert['serial'],
595
                    "ISSUER" => $raCertFile, // change this to the actual eduPKI Issuer CA
596
                    "ROOT" => $theRoot, // change this to the actual eduPKI Root CA
597
                ];
598
            default:
599
                /* HTTP POST the CSR to the CA with the $expiryDays as parameter
600
                 * on successful execution, gets back a PEM file which is the
601
                 * certificate (structure TBD)
602
                 * $httpResponse = httpRequest("https://clientca.hosted.eduroam.org/issue/", ["csr" => $csr, "expiry" => $expiryDays ] );
603
                 *
604
                 * The result of this if clause has to be a certificate in PHP's 
605
                 * "openssl_object" style (like the one that openssl_csr_sign would 
606
                 * produce), to be stored in the variable $cert; we also need the
607
                 * serial - which can be extracted from the received cert and has
608
                 * to be stored in $serial.
609
                 */
610
                throw new Exception("External silverbullet CA is not implemented yet!");
611
        }
612
    }
613
614
}
615