Passed
Push — master ( febf48...47f126 )
by Stefan
09:24
created

SilverbulletCertificate::issueCertificate()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 75
Code Lines 53

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 53
dl 0
loc 75
rs 8.4032
c 0
b 0
f 0
cc 6
nc 5
nop 2

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
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
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() {
0 ignored issues
show
Coding Style introduced by
Missing function doc comment
Loading history...
121
        // nothing to be done here.
122
    }
123
124
    /**
125
     * issue a certificate based on a token
126
     *
127
     * @param string $token
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
128
     * @param string $importPassword
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
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"),
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("RA");
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
    /**
0 ignored issues
show
Coding Style introduced by
Parameter $fed should have a doc-comment as per coding-style.
Loading history...
Coding Style introduced by
Parameter $realm should have a doc-comment as per coding-style.
Loading history...
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 CSR.\n");
383
384
        switch (CONFIG_CONFASSISTANT['SILVERBULLET']['CA']['type']) {
385
            case "embedded":
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
386
387
                $newCsr = openssl_csr_new(
388
                        ['O' => CONFIG_CONFASSISTANT['CONSORTIUM']['name'],
389
                    'OU' => $fed,
390
                    'CN' => $username,
391
                    'emailAddress' => $username,
392
                        ], $privateKey, [
393
                    'digest_alg' => 'sha256',
394
                    'req_extensions' => 'v3_req',
395
                        ]
396
                );
397
                break;
398
            case "eduPKI":
399
                $tempdirArray = \core\common\Entity::createTemporaryDirectory("test");
400
                $tempdir = $tempdirArray['dir'];
401
                // dump private key into directly
402
                $outstring = "";
403
                openssl_pkey_export($privateKey, $outstring);
404
                file_put_contents($tempdir . "/pkey.pem", $outstring);
405
                // PHP can only do one DC in the Subject. But we need three.
406
                $execCmd = CONFIG['PATHS']['openssl'] . " req -new -sha256 -key $tempdir/pkey.pem -out $tempdir/request.csr -subj /DC=test/DC=test/DC=eduroam/C=$fed/O=".CONFIG_CONFASSISTANT['CONSORTIUM']['name']."/OU=$fed/CN=$username/emailAddress=$username";
407
                $loggerInstance->debug(2, "Calling openssl req with following cmdline: $execCmd\n");
408
                $output = [];
409
                $return = 999;
410
                exec($execCmd, $output, $return);
411
                if ($return !== 0) {
412
                    throw new Exception("Non-zero return value from openssl req!");
413
                }
414
                $newCsr = file_get_contents("$tempdir/request.csr");
415
                // remove the temp dir!
416
                unlink("$tempdir/pkey.pem");
417
                unlink("$tempdir/request.csr");
418
                rmdir($tempdir);
419
                break;
420
            default:
421
                throw new Exception("Unknown CA!");
422
        }
423
        if ($newCsr === FALSE) {
424
            throw new Exception("Unable to create a CSR!");
425
        }
426
        return [
427
            "CSR" => $newCsr, // a resource for embedded, a string for eduPKI
428
            "USERNAME" => $username,
429
            "FED" => $fed
430
        ];
431
    }
432
433
    private static function initEduPKISoapSession($type) {
0 ignored issues
show
Coding Style introduced by
Missing function doc comment
Loading history...
434
        // set context parameters common to both endpoints
435
        $context_params = [
436
            'http' => [
437
                'timeout' => 60,
438
                'user_agent' => 'Stefan',
439
                'protocol_version' => 1.1
440
            ],
441
            'ssl' => [
442
                'verify_peer' => true,
443
                'verify_peer_name' => true,
444
                // below is the CA "/C=DE/O=Deutsche Telekom AG/OU=T-TeleSec Trust Center/CN=Deutsche Telekom Root CA 2"
445
                'cafile' => ROOT . "/config/SilverbulletClientCerts/eduPKI-webserver-root.pem",
446
                'verify_depth' => 5,
447
                'capture_peer_cert' => true,
448
            ],
449
        ];
450
        $url = "";
451
        switch ($type) {
452
            case "PUBLIC":
453
                $url = "https://pki.edupki.org/edupki-test-ca/cgi-bin/pub/soap?wsdl=1";
454
                $context_params['ssl']['peer_name'] = 'pki.edupki.org';
455
                break;
456
            case "RA":
457
                $url = "https://ra.edupki.org/edupki-test-ca/cgi-bin/ra/soap?wsdl=1";
458
                $context_params['ssl']['peer_name'] = 'ra.edupki.org';
459
                break;
460
            default:
461
                throw new Exception("Unknown type of eduPKI interface requested.");
462
        }
463
        if ($type == "RA") { // add client auth parameters to the context
464
            $context_params['ssl']['local_cert'] = ROOT . "/config/SilverbulletClientCerts/edupki-test-ra.pem";
465
            $context_params['ssl']['local_pk'] = ROOT . "/config/SilverbulletClientCerts/edupki-test-ra.key";
466
            $context_params['ssl']['passphrase'] = SilverbulletCertificate::EDUPKI_RA_PKEY_PASSPHRASE;
467
        }
468
        // initialse connection to eduPKI CA / eduroam RA
469
        $soap = new \SoapClient($url, [
470
            'soap_version' => SOAP_1_1,
471
            'trace' => TRUE,
472
            'exceptions' => TRUE,
473
            'connection_timeout' => 5, // if can't establish the connection within 5 sec, something's wrong
474
            'cache_wsdl' => WSDL_CACHE_NONE,
475
            'user_agent' => 'eduroam CAT to eduPKI SOAP Interface',
476
            'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
477
            'stream_context' => stream_context_create($context_params),
478
                ]
479
        );
480
        return $soap;
481
    }
482
483
    const EDUPKI_RA_ID = 700;
484
    const EDUPKI_CERT_PROFILE = "User SOAP";
485
    const EDUPKI_RA_PKEY_PASSPHRASE = "...";
486
487
    /**
488
     * take a CSR and sign it with our issuing CA's certificate
489
     * 
490
     * @param mixed $csr the CSR
0 ignored issues
show
Coding Style introduced by
Expected 8 spaces after parameter name; 1 found
Loading history...
491
     * @param int $expiryDays the number of days until the cert is going to expire
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter type; 1 found
Loading history...
492
     * @return array the cert and some meta info
493
     */
494
    private static function signCsr($csr, $expiryDays) {
495
        $loggerInstance = new common\Logging();
496
        $databaseHandle = DBConnection::handle("INST");
497
        switch (CONFIG_CONFASSISTANT['SILVERBULLET']['CA']['type']) {
498
            case "embedded":
499
                $rootCaPem = file_get_contents(ROOT . "/config/SilverbulletClientCerts/rootca.pem");
500
                $raCertFile = file_get_contents(ROOT . "/config/SilverbulletClientCerts/real.pem");
501
                $raCert = openssl_x509_read($raCertFile);
502
                $raKey = openssl_pkey_get_private("file://" . ROOT . "/config/SilverbulletClientCerts/real.key");
503
                $nonDupSerialFound = FALSE;
504
                do {
505
                    $serial = random_int(1000000000, PHP_INT_MAX);
506
                    $dupeQuery = $databaseHandle->exec("SELECT serial_number FROM silverbullet_certificate WHERE serial_number = ?", "i", $serial);
507
                    // SELECT -> resource, not boolean
508
                    if (mysqli_num_rows(/** @scrutinizer ignore-type */$dupeQuery) == 0) {
509
                        $nonDupSerialFound = TRUE;
510
                    }
511
                } while (!$nonDupSerialFound);
512
                $loggerInstance->debug(5, "generateCertificate: signing imminent with unique serial $serial.\n");
513
                return [
514
                    "CERT" => openssl_csr_sign($csr["CSR"], $raCert, $raKey, $expiryDays, ['digest_alg' => 'sha256'], $serial),
515
                    "SERIAL" => $serial,
516
                    "ISSUER" => $raCertFile,
517
                    "ROOT" => $rootCaPem,
518
                ];
519
            case "eduPKI":
520
                // initialse connection to eduPKI CA / eduroam RA and send the request to them
521
                try {
522
                    $altArray = [# Array mit den Subject Alternative Names
523
                        "email:" . $csr["USERNAME"]
524
                    ];
525
                    $soapPub = SilverbulletCertificate::initEduPKISoapSession("PUBLIC");
526
                    $loggerInstance->debug(5, "FIRST ACTUAL SOAP REQUEST (Public, newRequest)!\n");
527
                    $loggerInstance->debug(5, "PARAM_1: " . SilverbulletCertificate::EDUPKI_RA_ID . "\n");
528
                    $loggerInstance->debug(5, "PARAM_2: ".$csr["CSR"]."\n");
529
                    $loggerInstance->debug(5, "PARAM_3: ");
530
                    $loggerInstance->debug(5, $altArray);
531
                    $loggerInstance->debug(5, "PARAM_4: " . SilverbulletCertificate::EDUPKI_CERT_PROFILE . "\n");
532
                    $loggerInstance->debug(5, "PARAM_5: " . sha1("notused") . "\n");
533
                    $loggerInstance->debug(5, "PARAM_6: " . $csr["USERNAME"] . "\n");
534
                    $loggerInstance->debug(5, "PARAM_7: " . $csr["USERNAME"] . "\n");
535
                    $loggerInstance->debug(5, "PARAM_8: " . ProfileSilverbullet::PRODUCTNAME . "\n");
536
                    $loggerInstance->debug(5, "PARAM_9: false\n");
537
                    $soapNewRequest = $soapPub->newRequest(
538
                            SilverbulletCertificate::EDUPKI_RA_ID, # RA-ID
539
                            $csr["CSR"], # Request im PEM-Format
540
                            $altArray, # altNames
541
                            SilverbulletCertificate::EDUPKI_CERT_PROFILE, # Zertifikatprofil
542
                            sha1("notused"), # PIN
543
                            $csr["USERNAME"], # Name des Antragstellers
544
                            $csr["USERNAME"], # Kontakt-E-Mail
545
                            ProfileSilverbullet::PRODUCTNAME, # Organisationseinheit des Antragstellers
546
                            false                   # Veröffentlichen des Zertifikats?
547
                    );
548
                    $loggerInstance->debug(5, $soapPub->__getLastRequest());
549
                    $loggerInstance->debug(5, $soapPub->__getLastResponse());
550
                    if ($soapNewRequest == 0) {
551
                        throw new Exception("Error when sending SOAP request (request serial number was zero). No further details available.");
552
                    }
553
                    $soapReqnum = intval($soapNewRequest);
554
                } catch (Exception $e) {
555
                    // PHP 7.1 can do this much better
556
                    if (is_soap_fault($e)) {
557
                        throw new Exception("Error when sending SOAP request: " . "{$e->faultcode}: {$e->faultstring}\n");
558
                    }
559
                    throw new Exception("Something odd happened while doing the SOAP request:" . $e->getMessage());
560
                }
561
                try {
562
                    $soap = SilverbulletCertificate::initEduPKISoapSession("RA");
563
                    // tell the CA the desired expiry date of the new certificate
564
                    $expiry = new \DateTime();
565
                    $expiry->modify("+$expiryDays day");
566
                    $expiry->setTimezone(new \DateTimeZone("UTC"));
567
                    $soapExpiryChange = $soap->setRequestParameters(
568
                            $soapReqnum, [
569
                        "RaID" => SilverbulletCertificate::EDUPKI_RA_ID,
570
                        "Role" => SilverbulletCertificate::EDUPKI_CERT_PROFILE,
571
                        "Subject" => "DC=eduroam,DC=test,DC=test,C=".$csr["FED"].",O=".CONFIG_CONFASSISTANT['CONSORTIUM']['name'].",OU=".$csr["FED"].",CN=".$csr['USERNAME'].",emailAddress=".$csr['USERNAME'],
572
                        "SubjectAltNames" => ["email:".$csr["USERNAME"]],
573
                        "NotBefore" => (new \DateTime())->format('c'),
574
                        "NotAfter" => $expiry->format('c'),
575
                            ]
576
                    );
577
                    if ($soapExpiryChange === FALSE) {
578
                        throw new Exception("Error when sending SOAP request (unable to change expiry date).");
579
                    }
580
                    // retrieve the raw request to prepare for signature and approval
581
                    $soapRawRequest = $soap->getRawRequest($soapReqnum);
582
                    if (strlen($soapRawRequest) < 10) { // very basic error handling
583
                        throw new Exception("Suspiciously short data to sign!");
584
                    }
585
                    // for obnoxious reasons, we have to dump the request into a file and let pkcs7_sign read from the file
586
                    // rather than just using the string. Grr.
587
                    $tempdir = \core\common\Entity::createTemporaryDirectory("test");
588
                    file_put_contents($tempdir['dir'] . "/content.txt", $soapRawRequest);
589
                    // retrieve our RA cert from filesystem
590
                    $raCertFile = file_get_contents(ROOT . "/config/SilverbulletClientCerts/edupki-test-ra.pem");
591
                    $raCert = openssl_x509_read($raCertFile);
592
                    $raKey = openssl_pkey_get_private("file://" . ROOT . "/config/SilverbulletClientCerts/edupki-test-ra.clearkey");
593
                    // sign the data
594
                    if (openssl_pkcs7_sign($tempdir['dir'] . "/content.txt", $tempdir['dir'] . "/signature.txt", $raCert, $raKey, []) === FALSE) {
595
                        throw new Exception("Unable to sign the certificate approval data!");
596
                    }
597
                    // and get the signature blob back from the filesystem
598
                    $detachedSigBloat = file_get_contents($tempdir['dir'] . "/signature.txt");
599
                    $loggerInstance->debug(5, "Raw Request is:\n");
600
                    $loggerInstance->debug(5, $soapRawRequest."\n");
601
                    $loggerInstance->debug(5, "Signature is:\n");
602
                    $loggerInstance->debug(5, $detachedSigBloat."\n");
603
                    $detachedSigBloatArray = explode("\n",$detachedSigBloat);
604
                    $index = array_search('Content-Disposition: attachment; filename="smime.p7s"',$detachedSigBloatArray);
605
                    $detachedSigSmall = array_slice($detachedSigBloatArray, $index+1);
606
                    $detachedSigSmall[0] = "-----BEGIN PKCS7-----";
607
                    array_pop($detachedSigSmall);
608
                    array_pop($detachedSigSmall);
609
                    array_pop($detachedSigSmall);
610
                    $detachedSigSmall[count($detachedSigSmall)-1] = "-----END PKCS7-----";
611
                    $detachedSig = implode("\n",$detachedSigSmall);
612
                    $loggerInstance->debug(5, "Request for server approveRequest has parameters:\n");
613
                    $loggerInstance->debug(5, $soapReqnum."\n");
614
                    $loggerInstance->debug(5, base64_encode($soapRawRequest)."\n");
615
                    $loggerInstance->debug(5, $detachedSig."\n");
616
                    $soapIssueCert = $soap->approveRequest($soapReqnum, base64_encode($soapRawRequest), $detachedSig);
617
                    if ($soapIssueCert === FALSE) {
618
                        throw new Exception("The locally approved request was NOT processed by the CA.");
619
                    }
620
                    // now, get the actual cert from the CA
621
                    $soapCert = $soap->getCertificateByRequestSerial($soapReqnum);
622
                    $x509 = new common\X509();
623
                    $parsedCert = $x509->processCertificate($soapCert);
624
                    if (!is_array($parsedCert)) {
1 ignored issue
show
introduced by
The condition is_array($parsedCert) is always false.
Loading history...
625
                        throw new Exception("We did not actually get a certificate.");
626
                    }
627
                    // let's get the CA certificate chain
628
                    $caInfo = $soap->getCAInfo();
629
                    $certList = $x509->splitCertificate($caInfo['CAChain']);
630
                    // find the root
631
                    $theRoot = "";
632
                    foreach ($certList as $oneCert) {
633
                        $content = $x509->processCertificate($oneCert);
634
                        if ($content['root'] == 1) {
635
                            $theRoot = $content;
636
                        }
637
                    }
638
                    if ($theRoot == "") {
639
                        throw new Exception("CAInfo has no root certificate for us!");
640
                    }
641
                } catch (Exception $e) {
642
                    // PHP 7.1 can do this much better
643
                    if (is_soap_fault($e)) {
644
                        throw new Exception("Error when sending SOAP request: " . "{$e->faultcode}: {$e->faultstring}\n");
645
                    }
646
                    throw new Exception("Something odd happened while doing the SOAP request:" . $e->getMessage());
647
                }
648
                return [
649
                    "CERT" => openssl_x509_read($parsedCert['pem']),
650
                    "SERIAL" => $parsedCert['serial'],
651
                    "ISSUER" => $raCertFile, // change this to the actual eduPKI Issuer CA
652
                    "ROOT" => $theRoot, // change this to the actual eduPKI Root CA
653
                ];
654
            default:
655
                /* HTTP POST the CSR to the CA with the $expiryDays as parameter
656
                 * on successful execution, gets back a PEM file which is the
657
                 * certificate (structure TBD)
658
                 * $httpResponse = httpRequest("https://clientca.hosted.eduroam.org/issue/", ["csr" => $csr, "expiry" => $expiryDays ] );
659
                 *
660
                 * The result of this if clause has to be a certificate in PHP's 
661
                 * "openssl_object" style (like the one that openssl_csr_sign would 
662
                 * produce), to be stored in the variable $cert; we also need the
663
                 * serial - which can be extracted from the received cert and has
664
                 * to be stored in $serial.
665
                 */
666
                throw new Exception("External silverbullet CA is not implemented yet!");
667
        }
668
    }
669
670
}
671