Passed
Push — master ( 7e63ee...aaf88a )
by Stefan
10:38
created

SilverbulletCertificate::signCsr()   D

Complexity

Conditions 17
Paths 119

Size

Total Lines 170
Code Lines 122

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 122
dl 0
loc 170
rs 4.0466
c 0
b 0
f 0
cc 17
nc 119
nop 2

How to fix   Long Method    Complexity   

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
use \SoapFault;
26
27
class SilverbulletCertificate extends EntityWithDBProperties {
28
29
    public $username;
30
    public $expiry;
31
    public $serial;
32
    public $dbId;
33
    public $invitationId;
34
    public $userId;
35
    public $profileId;
36
    public $issued;
37
    public $device;
38
    public $revocationStatus;
39
    public $revocationTime;
40
    public $ocsp;
41
    public $ocspTimestamp;
42
    public $status;
43
44
    const CERTSTATUS_VALID = 1;
45
    const CERTSTATUS_EXPIRED = 2;
46
    const CERTSTATUS_REVOKED = 3;
47
    const CERTSTATUS_INVALID = 4;
48
49
    /**
50
     * instantiates an existing certificate, identified either by its serial
51
     * number or the username. 
52
     * 
53
     * Use static issueCertificate() to generate a whole new cert.
54
     * 
55
     * @param int|string $identifier
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
56
     */
57
    public function __construct($identifier) {
58
        $this->databaseType = "INST";
59
        parent::__construct();
60
        $this->username = "";
61
        $this->expiry = "2000-01-01 00:00:00";
62
        $this->serial = -1;
63
        $this->dbId = -1;
64
        $this->invitationId = -1;
65
        $this->userId = -1;
66
        $this->profileId = -1;
67
        $this->issued = "2000-01-01 00:00:00";
68
        $this->device = NULL;
69
        $this->revocationStatus = "REVOKED";
70
        $this->revocationTime = "2000-01-01 00:00:00";
71
        $this->ocsp = NULL;
72
        $this->ocspTimestamp = "2000-01-01 00:00:00";
73
        $this->status = SilverbulletCertificate::CERTSTATUS_INVALID;
74
75
        $incoming = FALSE;
76
        if (is_numeric($identifier)) {
77
            $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);
78
        } else { // it's a string instead
79
            $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);
80
        }
81
82
        // SELECT -> mysqli_resource, not boolean
83
        while ($oneResult = mysqli_fetch_object(/** @scrutinizer ignore-type */ $incoming)) { // there is only at most one
84
            $this->username = $oneResult->cn;
85
            $this->expiry = $oneResult->expiry;
86
            $this->serial = $oneResult->serial_number;
87
            $this->dbId = $oneResult->id;
88
            $this->invitationId = $oneResult->silverbullet_invitation_id;
89
            $this->userId = $oneResult->silverbullet_user_id;
90
            $this->profileId = $oneResult->profile_id;
91
            $this->issued = $oneResult->issued;
92
            $this->device = $oneResult->device;
93
            $this->revocationStatus = $oneResult->revocation_status;
94
            $this->revocationTime = $oneResult->revocation_time;
95
            $this->ocsp = $oneResult->OCSP;
96
            $this->ocspTimestamp = $oneResult->OCSP_timestamp;
97
            // is the cert expired?
98
            $now = new \DateTime();
99
            $cert_expiry = new \DateTime($this->expiry);
100
            $delta = $now->diff($cert_expiry);
101
            $this->status = ($delta->invert == 1 ? SilverbulletCertificate::CERTSTATUS_EXPIRED : SilverbulletCertificate::CERTSTATUS_VALID);
102
            // expired is expired; even if it was previously revoked. But do update status for revoked ones...
103
            if ($this->status == SilverbulletCertificate::CERTSTATUS_VALID && $this->revocationStatus == "REVOKED") {
104
                $this->status = SilverbulletCertificate::CERTSTATUS_REVOKED;
105
            }
106
        }
107
    }
108
109
    /**
110
     * 
111
     * @return array of basic certificate details
112
     */
113
    public function getBasicInfo() {
114
        $returnArray = []; // unnecessary because the iterator below is never empty, but Scrutinizer gets excited nontheless
115
        foreach (['status', 'serial', 'username', 'device', 'issued', 'expiry'] as $key) {
116
            $returnArray[$key] = $this->$key;
117
        }
118
        return($returnArray);
119
    }
120
121
    public function updateFreshness() {
0 ignored issues
show
Coding Style introduced by
Missing function doc comment
Loading history...
122
        // nothing to be done here.
123
    }
124
125
    /**
126
     * issue a certificate based on a token
127
     *
128
     * @param string $token
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
129
     * @param string $importPassword
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
130
     * @return array
131
     */
132
    public static function issueCertificate($token, $importPassword) {
133
        $loggerInstance = new common\Logging();
134
        $databaseHandle = DBConnection::handle("INST");
135
        $loggerInstance->debug(5, "generateCertificate() - starting.\n");
136
        $invitationObject = new SilverbulletInvitation($token);
137
        $profile = new ProfileSilverbullet($invitationObject->profile);
138
        $inst = new IdP($profile->institution);
139
        $loggerInstance->debug(5, "tokenStatus: done, got " . $invitationObject->invitationTokenStatus . ", " . $invitationObject->profile . ", " . $invitationObject->userId . ", " . $invitationObject->expiry . ", " . $invitationObject->invitationTokenString . "\n");
140
        if ($invitationObject->invitationTokenStatus != SilverbulletInvitation::SB_TOKENSTATUS_VALID && $invitationObject->invitationTokenStatus != SilverbulletInvitation::SB_TOKENSTATUS_PARTIALLY_REDEEMED) {
141
            throw new Exception("Attempt to generate a SilverBullet installer with an invalid/redeemed/expired token. The user should never have gotten that far!");
142
        }
143
144
        // SQL query to find the expiry date of the *user* to find the correct ValidUntil for the cert
145
        $user = $invitationObject->userId;
146
        $userrow = $databaseHandle->exec("SELECT expiry FROM silverbullet_user WHERE id = ?", "i", $user);
147
        // SELECT -> resource, not boolean
148
        if ($userrow->num_rows != 1) {
149
            throw new Exception("Despite a valid token, the corresponding user was not found in database or database query error!");
150
        }
151
        $expiryObject = mysqli_fetch_object(/** @scrutinizer ignore-type */ $userrow);
152
        $loggerInstance->debug(5, "EXP: " . $expiryObject->expiry . "\n");
153
        $expiryDateObject = date_create_from_format("Y-m-d H:i:s", $expiryObject->expiry);
154
        if ($expiryDateObject === FALSE) {
155
            throw new Exception("The expiry date we got from the DB is bogus!");
156
        }
157
        $loggerInstance->debug(5, $expiryDateObject->format("Y-m-d H:i:s") . "\n");
158
        // date_create with no parameters can't fail, i.e. is never FALSE
159
        $validity = date_diff(/** @scrutinizer ignore-type */ date_create(), $expiryDateObject);
160
        $expiryDays = $validity->days + 1;
161
        if ($validity->invert == 1) { // negative! That should not be possible
162
            throw new Exception("Attempt to generate a certificate for a user which is already expired!");
163
        }
164
165
        $privateKey = openssl_pkey_new(['private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA, 'encrypt_key' => FALSE]);
166
167
        $csr = SilverbulletCertificate::generateCsr($privateKey, strtoupper($inst->federation), $profile->getAttributes("internal:realm")[0]['value']);
168
169
        $loggerInstance->debug(5, "generateCertificate: proceeding to sign cert.\n");
170
171
        $certMeta = SilverbulletCertificate::signCsr($csr, $expiryDays);
172
        $cert = $certMeta["CERT"];
173
        $issuingCaPem = $certMeta["ISSUER"];
174
        $rootCaPem = $certMeta["ROOT"];
175
        $serial = $certMeta["SERIAL"];
176
177
        $loggerInstance->debug(5, "generateCertificate: post-processing certificate.\n");
178
179
        // with the cert, our private key and import password, make a PKCS#12 container out of it
180
        $exportedCertProt = "";
181
        openssl_pkcs12_export($cert, $exportedCertProt, $privateKey, $importPassword, ['extracerts' => [$issuingCaPem /* , $rootCaPem */]]);
182
        $exportedCertClear = "";
183
        openssl_pkcs12_export($cert, $exportedCertClear, $privateKey, "", ['extracerts' => [$issuingCaPem, $rootCaPem]]);
184
        // 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!
185
        // we need the *real* expiry date, not just the day-approximation
186
        $x509 = new \core\common\X509();
187
        $certString = "";
188
        openssl_x509_export($cert, $certString);
189
        $parsedCert = $x509->processCertificate($certString);
190
        $loggerInstance->debug(5, "CERTINFO: " . print_r($parsedCert['full_details'], true));
191
        $realExpiryDate = date_create_from_format("U", $parsedCert['full_details']['validTo_time_t'])->format("Y-m-d H:i:s");
192
193
        // store new cert info in DB
194
        $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);
195
        // newborn cert immediately gets its "valid" OCSP response
196
        $certObject = new SilverbulletCertificate($serial);
197
        $certObject->triggerNewOCSPStatement();
198
// return PKCS#12 data stream
199
        return [
200
            "certObject" => $certObject,
201
            "certdata" => $exportedCertProt,
202
            "certdataclear" => $exportedCertClear,
203
            "sha1" => openssl_x509_fingerprint($cert, "sha1"),
204
            "sha256" => openssl_x509_fingerprint($cert, "sha256"),
205
            'importPassword' => $importPassword,
206
            'GUID' => common\Entity::uuid("", $exportedCertProt),
207
        ];
208
    }
209
210
    /**
211
     * triggers a new OCSP statement for the given serial number
212
     * 
213
     * @return string DER-encoded OCSP status info (binary data!)
214
     */
215
    public function triggerNewOCSPStatement() {
216
        $logHandle = new \core\common\Logging();
217
        $logHandle->debug(2, "Triggering new OCSP statement for serial $this->serial.\n");
218
        switch (CONFIG_CONFASSISTANT['SILVERBULLET']['CA']['type']) {
219
            case "embedded":
220
                $certstatus = "";
221
                // get all relevant info from object properties
222
                if ($this->serial >= 0) { // let's start with the assumption that the cert is valid
223
                    if ($this->revocationStatus == "REVOKED") {
224
                        // already revoked, simply return canned OCSP response
225
                        $certstatus = "R";
226
                    } else {
227
                        $certstatus = "V";
228
                    }
229
                }
230
231
                $originalExpiry = date_create_from_format("Y-m-d H:i:s", $this->expiry);
232
                if ($originalExpiry === FALSE) {
233
                    throw new Exception("Unable to calculate original expiry date, input data bogus!");
234
                }
235
                $validity = date_diff(/** @scrutinizer ignore-type */ date_create(), $originalExpiry);
236
                if ($validity->invert == 1) {
237
                    // negative! Cert is already expired, no need to revoke. 
238
                    // No need to return anything really, but do return the last known OCSP statement to prevent special case
239
                    $certstatus = "E";
240
                }
241
                $profile = new ProfileSilverbullet($this->profileId);
242
                $inst = new IdP($profile->institution);
243
                $federation = strtoupper($inst->federation);
244
                // generate stub index.txt file
245
                $tempdirArray = \core\common\Entity::createTemporaryDirectory("test");
246
                $tempdir = $tempdirArray['dir'];
247
                $nowIndexTxt = (new \DateTime())->format("ymdHis") . "Z";
248
                $expiryIndexTxt = $originalExpiry->format("ymdHis") . "Z";
249
                $serialHex = strtoupper(dechex($this->serial));
250
                if (strlen($serialHex) % 2 == 1) {
251
                    $serialHex = "0" . $serialHex;
252
                }
253
254
                $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";
255
                $logHandle->debug(4, "index.txt contents-to-be: $indexStatement");
256
                if (!file_put_contents($tempdir . "/index.txt", $indexStatement)) {
257
                    $logHandle->debug(1, "Unable to write openssl index.txt file for revocation handling!");
258
                }
259
                // index.txt.attr is dull but needs to exist
260
                file_put_contents($tempdir . "/index.txt.attr", "unique_subject = yes\n");
261
                // call "openssl ocsp" to manufacture our own OCSP statement
262
                // adding "-rmd sha1" to the following command-line makes the
263
                // choice of signature algorithm for the response explicit
264
                // but it's only available from openssl-1.1.0 (which we do not
265
                // want to require just for that one thing).
266
                $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";
267
                $logHandle->debug(2, "Calling openssl ocsp with following cmdline: $execCmd\n");
268
                $output = [];
269
                $return = 999;
270
                exec($execCmd, $output, $return);
271
                if ($return !== 0) {
272
                    throw new Exception("Non-zero return value from openssl ocsp!");
273
                }
274
                $ocsp = file_get_contents($tempdir . "/$serialHex.response.der");
275
                // remove the temp dir!
276
                unlink($tempdir . "/$serialHex.response.der");
277
                unlink($tempdir . "/index.txt.attr");
278
                unlink($tempdir . "/index.txt");
279
                rmdir($tempdir);
280
                break;
281
            case "eduPKI":
282
                // nothing to be done here - eduPKI have their own OCSP responder
283
                // and the certs point to it. So we are not in the loop.
284
                break;
285
            default:
286
                /* HTTP POST the serial to the CA. The CA knows about the state of
287
                 * the certificate.
288
                 *
289
                 * $httpResponse = httpRequest("https://clientca.hosted.eduroam.org/ocsp/", ["serial" => $serial ] );
290
                 *
291
                 * The result of this if clause has to be a DER-encoded OCSP statement
292
                 * to be stored in the variable $ocsp
293
                 */
294
                throw new Exception("This type of silverbullet CA is not implemented yet!");
295
        }
296
        // write the new statement into DB
297
        $this->databaseHandle->exec("UPDATE silverbullet_certificate SET OCSP = ?, OCSP_timestamp = NOW() WHERE serial_number = ?", "si", $ocsp, $this->serial);
298
        return $ocsp;
299
    }
300
301
    /**
302
     * revokes a certificate
303
     * @return array with revocation information
304
     */
305
    public function revokeCertificate() {
306
        $nowSql = (new \DateTime())->format("Y-m-d H:i:s");
307
        // regardless if embedded or not, always keep local state in our own DB
308
        $this->databaseHandle->exec("UPDATE silverbullet_certificate SET revocation_status = 'REVOKED', revocation_time = ? WHERE serial_number = ?", "si", $nowSql, $this->serial);
309
        $this->loggerInstance->debug(2, "Certificate revocation status for $this->serial updated, about to call triggerNewOCSPStatement().\n");
310
        // newly instantiate us, DB content has changed...
311
        $certObject = new SilverbulletCertificate($this->serial);
312
        // embedded CA does "nothing special" for revocation: the DB change was the entire thing to do
313
        // but for external CAs, we need to notify explicitly that the cert is now revoked
314
        switch (CONFIG_CONFASSISTANT['SILVERBULLET']['CA']['type']) {
315
            case "embedded":
316
                break;
317
            case "eduPKI":
318
                try {
319
                    $soap = SilverbulletCertificate::initEduPKISoapSession("RA");
320
                    $soapRevocationSerial = $soap->newRevocationRequest($this->serial, "");
321
                    if ($soapRevocationSerial == 0) {
322
                        throw new Exception("Unable to create revocation request, serial number was zero.");
323
                    }
324
                    // retrieve the raw request to prepare for signature and approval
325
                    $soapRawRevRequest = $soap->getRawRevocationRequest($soapRevocationSerial);
326
                    if (strlen($soapRawRevRequest) < 10) { // very basic error handling
327
                        throw new Exception("Suspiciously short data to sign!");
328
                    }
329
                    // for obnoxious reasons, we have to dump the request into a file and let pkcs7_sign read from the file
330
                    // rather than just using the string. Grr.
331
                    $tempdir = \core\common\Entity::createTemporaryDirectory("test");
332
                    file_put_contents($tempdir['dir'] . "/content.txt", $soapRawRevRequest);
333
                    // retrieve our RA cert from filesystem
334
                    $raCertFile = file_get_contents(ROOT . "../edupki-test-ra.pem");
335
                    $raCert = openssl_x509_read($raCertFile);
336
                    $raKey = openssl_pkey_get_private("file://" . ROOT . "../edupki-test-ra.clearkey");
337
                    // sign the data
338
                    if (openssl_pkcs7_sign($tempdir['dir'] . "/content.txt", $tempdir['dir'] . "/signature.txt", $raCert, $raKey, []) === FALSE) {
339
                        throw new Exception("Unable to sign the revocation approval data!");
340
                    }
341
                    // and get the signature blob back from the filesystem
342
                    $detachedSig = file_get_contents($tempdir['dir'] . "/signature.txt");
343
                    $soapIssueRev = $soap->approveRevocationRequest($soapRevocationSerial, $soapRawRevRequest, $detachedSig);
344
                    if ($soapIssueRev === FALSE) {
345
                        throw new Exception("The locally approved revocation request was NOT processed by the CA.");
346
                    }
347
                } catch (Exception $e) {
348
                    // PHP 7.1 can do this much better
349
                    if (is_soap_fault($e)) {
350
                        throw new Exception("Error when sending SOAP request: " . "{$e->faultcode}: {$e->faultstring}\n");
351
                    }
352
                    throw new Exception("Something odd happened while doing the SOAP request:" . $e->getMessage());
353
                }
354
                break;
355
            default:
356
                throw new Exception("Unknown type of CA requested!");
357
        }
358
        // what happens wrt OCSP etc. is really something for the following function to decide. We just call it.
359
        $certObject->triggerNewOCSPStatement();
360
    }
361
362
    /**
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...
363
     * create a CSR
364
     * 
365
     * @param resource $privateKey the private key to create the CSR with
366
     * @return array with the CSR and some meta info
367
     */
368
    private static function generateCsr($privateKey, $fed, $realm) {
369
        $databaseHandle = DBConnection::handle("INST");
370
        $loggerInstance = new common\Logging();
371
        $usernameIsUnique = FALSE;
372
        $username = "";
373
        while ($usernameIsUnique === FALSE) {
374
            $usernameLocalPart = common\Entity::randomString(64 - 1 - strlen($realm), "0123456789abcdefghijklmnopqrstuvwxyz");
375
            $username = $usernameLocalPart . "@" . $realm;
376
            $uniquenessQuery = $databaseHandle->exec("SELECT cn from silverbullet_certificate WHERE cn = ?", "s", $username);
377
            // SELECT -> resource, not boolean
378
            if (mysqli_num_rows(/** @scrutinizer ignore-type */ $uniquenessQuery) == 0) {
379
                $usernameIsUnique = TRUE;
380
            }
381
        }
382
383
        $loggerInstance->debug(5, "generateCertificate: generating CSR.\n");
384
385
        switch (CONFIG_CONFASSISTANT['SILVERBULLET']['CA']['type']) {
386
            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...
387
388
                $newCsr = openssl_csr_new(
389
                        ['O' => CONFIG_CONFASSISTANT['CONSORTIUM']['name'],
390
                    'OU' => $fed,
391
                    'CN' => $username,
392
                    'emailAddress' => $username,
393
                        ], $privateKey, [
394
                    'digest_alg' => 'sha256',
395
                    'req_extensions' => 'v3_req',
396
                        ]
397
                );
398
                break;
399
            case "eduPKI":
400
                $tempdirArray = \core\common\Entity::createTemporaryDirectory("test");
401
                $tempdir = $tempdirArray['dir'];
402
                // dump private key into directly
403
                $outstring = "";
404
                openssl_pkey_export($privateKey, $outstring);
405
                file_put_contents($tempdir . "/pkey.pem", $outstring);
406
                // PHP can only do one DC in the Subject. But we need three.
407
                $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";
408
                $loggerInstance->debug(2, "Calling openssl req with following cmdline: $execCmd\n");
409
                $output = [];
410
                $return = 999;
411
                exec($execCmd, $output, $return);
412
                if ($return !== 0) {
413
                    throw new Exception("Non-zero return value from openssl req!");
414
                }
415
                $newCsr = file_get_contents("$tempdir/request.csr");
416
                // remove the temp dir!
417
                unlink("$tempdir/pkey.pem");
418
                unlink("$tempdir/request.csr");
419
                rmdir($tempdir);
420
                break;
421
            default:
422
                throw new Exception("Unknown CA!");
423
        }
424
        if ($newCsr === FALSE) {
425
            throw new Exception("Unable to create a CSR!");
426
        }
427
        return [
428
            "CSR" => $newCsr, // a resource for embedded, a string for eduPKI
429
            "USERNAME" => $username,
430
            "FED" => $fed
431
        ];
432
    }
433
434
    private static function initEduPKISoapSession($type) {
0 ignored issues
show
Coding Style introduced by
Missing function doc comment
Loading history...
435
        // set context parameters common to both endpoints
436
        $context_params = [
437
            'http' => [
438
                'timeout' => 60,
439
                'user_agent' => 'Stefan',
440
                'protocol_version' => 1.1
441
            ],
442
            'ssl' => [
443
                'verify_peer' => true,
444
                'verify_peer_name' => true,
445
                // below is the CA "/C=DE/O=Deutsche Telekom AG/OU=T-TeleSec Trust Center/CN=Deutsche Telekom Root CA 2"
446
                'cafile' => ROOT . "/config/SilverbulletClientCerts/eduPKI-webserver-root.pem",
447
                'verify_depth' => 5,
448
                'capture_peer_cert' => true,
449
            ],
450
        ];
451
        $url = "";
452
        switch ($type) {
453
            case "PUBLIC":
454
                $url = "https://pki.edupki.org/edupki-test-ca/cgi-bin/pub/soap?wsdl=1";
455
                $context_params['ssl']['peer_name'] = 'pki.edupki.org';
456
                break;
457
            case "RA":
458
                $url = "https://ra.edupki.org/edupki-test-ca/cgi-bin/ra/soap?wsdl=1";
459
                $context_params['ssl']['peer_name'] = 'ra.edupki.org';
460
                break;
461
            default:
462
                throw new Exception("Unknown type of eduPKI interface requested.");
463
        }
464
        if ($type == "RA") { // add client auth parameters to the context
465
            $context_params['ssl']['local_cert'] = ROOT . "/config/SilverbulletClientCerts/edupki-test-ra.pem";
466
            $context_params['ssl']['local_pk'] = ROOT . "/config/SilverbulletClientCerts/edupki-test-ra.clearkey";
467
            // $context_params['ssl']['passphrase'] = SilverbulletCertificate::EDUPKI_RA_PKEY_PASSPHRASE;
468
        }
469
        // initialse connection to eduPKI CA / eduroam RA
470
        $soap = new \SoapClient($url, [
471
            'soap_version' => SOAP_1_1,
472
            'trace' => TRUE,
473
            'exceptions' => false,
474
            'connection_timeout' => 5, // if can't establish the connection within 5 sec, something's wrong
475
            'cache_wsdl' => WSDL_CACHE_NONE,
476
            'user_agent' => 'eduroam CAT to eduPKI SOAP Interface',
477
            'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
478
            'stream_context' => stream_context_create($context_params),
479
                ]
480
        );
481
        return $soap;
482
    }
483
484
    const EDUPKI_RA_ID = 700;
485
    const EDUPKI_CERT_PROFILE = "User SOAP";
486
    const EDUPKI_RA_PKEY_PASSPHRASE = "...";
487
488
    /**
489
     * take a CSR and sign it with our issuing CA's certificate
490
     * 
491
     * @param mixed $csr the CSR
0 ignored issues
show
Coding Style introduced by
Expected 8 spaces after parameter name; 1 found
Loading history...
492
     * @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...
493
     * @return array the cert and some meta info
494
     */
495
    private static function signCsr($csr, $expiryDays) {
496
        $loggerInstance = new common\Logging();
497
        $databaseHandle = DBConnection::handle("INST");
498
        switch (CONFIG_CONFASSISTANT['SILVERBULLET']['CA']['type']) {
499
            case "embedded":
500
                $rootCaPem = file_get_contents(ROOT . "/config/SilverbulletClientCerts/rootca.pem");
501
                $raCertFile = file_get_contents(ROOT . "/config/SilverbulletClientCerts/real.pem");
502
                $raCert = openssl_x509_read($raCertFile);
503
                $raKey = openssl_pkey_get_private("file://" . ROOT . "/config/SilverbulletClientCerts/real.key");
504
                $nonDupSerialFound = FALSE;
505
                do {
506
                    $serial = random_int(1000000000, PHP_INT_MAX);
507
                    $dupeQuery = $databaseHandle->exec("SELECT serial_number FROM silverbullet_certificate WHERE serial_number = ?", "i", $serial);
508
                    // SELECT -> resource, not boolean
509
                    if (mysqli_num_rows(/** @scrutinizer ignore-type */$dupeQuery) == 0) {
510
                        $nonDupSerialFound = TRUE;
511
                    }
512
                } while (!$nonDupSerialFound);
513
                $loggerInstance->debug(5, "generateCertificate: signing imminent with unique serial $serial.\n");
514
                return [
515
                    "CERT" => openssl_csr_sign($csr["CSR"], $raCert, $raKey, $expiryDays, ['digest_alg' => 'sha256'], $serial),
516
                    "SERIAL" => $serial,
517
                    "ISSUER" => $raCertFile,
518
                    "ROOT" => $rootCaPem,
519
                ];
520
            case "eduPKI":
521
                // initialse connection to eduPKI CA / eduroam RA and send the request to them
522
                try {
523
                    $altArray = [# Array mit den Subject Alternative Names
524
                        "email:" . $csr["USERNAME"]
525
                    ];
526
                    $soapPub = SilverbulletCertificate::initEduPKISoapSession("PUBLIC");
527
                    $loggerInstance->debug(5, "FIRST ACTUAL SOAP REQUEST (Public, newRequest)!\n");
528
                    $loggerInstance->debug(5, "PARAM_1: " . SilverbulletCertificate::EDUPKI_RA_ID . "\n");
529
                    $loggerInstance->debug(5, "PARAM_2: " . $csr["CSR"] . "\n");
530
                    $loggerInstance->debug(5, "PARAM_3: ");
531
                    $loggerInstance->debug(5, $altArray);
532
                    $loggerInstance->debug(5, "PARAM_4: " . SilverbulletCertificate::EDUPKI_CERT_PROFILE . "\n");
533
                    $loggerInstance->debug(5, "PARAM_5: " . sha1("notused") . "\n");
534
                    $loggerInstance->debug(5, "PARAM_6: " . $csr["USERNAME"] . "\n");
535
                    $loggerInstance->debug(5, "PARAM_7: " . $csr["USERNAME"] . "\n");
536
                    $loggerInstance->debug(5, "PARAM_8: " . ProfileSilverbullet::PRODUCTNAME . "\n");
537
                    $loggerInstance->debug(5, "PARAM_9: false\n");
538
                    $soapNewRequest = $soapPub->newRequest(
539
                            SilverbulletCertificate::EDUPKI_RA_ID, # RA-ID
540
                            $csr["CSR"], # Request im PEM-Format
541
                            $altArray, # altNames
542
                            SilverbulletCertificate::EDUPKI_CERT_PROFILE, # Zertifikatprofil
543
                            sha1("notused"), # PIN
544
                            $csr["USERNAME"], # Name des Antragstellers
545
                            $csr["USERNAME"], # Kontakt-E-Mail
546
                            ProfileSilverbullet::PRODUCTNAME, # Organisationseinheit des Antragstellers
547
                            false                   # Veröffentlichen des Zertifikats?
548
                    );
549
                    $loggerInstance->debug(5, $soapPub->__getLastRequest());
550
                    $loggerInstance->debug(5, $soapPub->__getLastResponse());
551
                    if ($soapNewRequest == 0) {
552
                        throw new Exception("Error when sending SOAP request (request serial number was zero). No further details available.");
553
                    }
554
                    $soapReqnum = intval($soapNewRequest);
555
                } catch (Exception $e) {
556
                    // PHP 7.1 can do this much better
557
                    if (is_soap_fault($e)) {
558
                        throw new Exception("Error when sending SOAP request: " . "{$e->faultcode}: {$e->faultstring}\n");
559
                    }
560
                    throw new Exception("Something odd happened while doing the SOAP request:" . $e->getMessage());
561
                }
562
                try {
563
                    $soap = SilverbulletCertificate::initEduPKISoapSession("RA");
564
                    // tell the CA the desired expiry date of the new certificate
565
                    $expiry = new \DateTime();
566
                    $expiry->modify("+$expiryDays day");
567
                    $expiry->setTimezone(new \DateTimeZone("UTC"));
568
                    $soapExpiryChange = $soap->setRequestParameters(
569
                            $soapReqnum, [
570
                        "RaID" => SilverbulletCertificate::EDUPKI_RA_ID,
571
                        "Role" => SilverbulletCertificate::EDUPKI_CERT_PROFILE,
572
                        "Subject" => "DC=eduroam,DC=test,DC=test,C=" . $csr["FED"] . ",O=" . CONFIG_CONFASSISTANT['CONSORTIUM']['name'] . ",OU=" . $csr["FED"] . ",CN=" . $csr['USERNAME'] . ",emailAddress=" . $csr['USERNAME'],
573
                        "SubjectAltNames" => ["email:" . $csr["USERNAME"]],
574
                        "NotBefore" => (new \DateTime())->format('c'),
575
                        "NotAfter" => $expiry->format('c'),
576
                            ]
577
                    );
578
                    if ($soapExpiryChange === FALSE) {
579
                        throw new Exception("Error when sending SOAP request (unable to change expiry date).");
580
                    }
581
                    // retrieve the raw request to prepare for signature and approval
582
                    // this seems to come out base64-decoded already; maybe PHP
583
                    // considers this "convenience"? But we need it as sent on
584
                    // the wire, so re-encode it!
585
                    $soapCleartext = $soap->getRawRequest($soapReqnum);
586
                    
587
                    $loggerInstance->debug(5, "Actual received SOAP resonse for getRawRequest was:\n\n");
588
                    $loggerInstance->debug(5, $soap->__getLastResponse());
589
                    // for obnoxious reasons, we have to dump the request into a file and let pkcs7_sign read from the file
590
                    // rather than just using the string. Grr.
591
                    $tempdir = \core\common\Entity::createTemporaryDirectory("test");
592
                    file_put_contents($tempdir['dir'] . "/content.txt", $soapCleartext);
593
                    // retrieve our RA cert from filesystem
594
                    $raCertFile = file_get_contents(ROOT . "/config/SilverbulletClientCerts/edupki-test-ra.pem");
595
                    $raCert = openssl_x509_read($raCertFile);
0 ignored issues
show
Unused Code introduced by
The assignment to $raCert is dead and can be removed.
Loading history...
596
                    $raKey = openssl_pkey_get_private("file://" . ROOT . "/config/SilverbulletClientCerts/edupki-test-ra.clearkey");
0 ignored issues
show
Unused Code introduced by
The assignment to $raKey is dead and can be removed.
Loading history...
597
                    // sign the data, using cmdline because openssl_pkcs7_sign produces strange results
598
                    // -binary didn't help, nor switch -md to sha1 sha256 or sha512
599
                    $loggerInstance->debug(5, "Actual content to be signed is this:\n$soapCleartext\n");
600
                    $execCmd = CONFIG['PATHS']['openssl'] . " smime -sign -in " . $tempdir['dir'] . "/content.txt -out " . $tempdir['dir'] . "/signature.txt -outform pem -inkey " . ROOT . "/config/SilverbulletClientCerts/edupki-test-ra.clearkey -signer " . ROOT . "/config/SilverbulletClientCerts/edupki-test-ra.pem";
601
                    $loggerInstance->debug(2, "Calling openssl smime with following cmdline: $execCmd\n");
602
                    $output = [];
603
                    $return = 999;
604
                    exec($execCmd, $output, $return);
605
                    if ($return !== 0) {
606
                        throw new Exception("Non-zero return value from openssl smime!");
607
                    }
608
                    // and get the signature blob back from the filesystem
609
                    $detachedSig = trim(file_get_contents($tempdir['dir'] . "/signature.txt"));
610
                    $loggerInstance->debug(5, "Request for server approveRequest has parameters:\n");
611
                    $loggerInstance->debug(5, $soapReqnum . "\n");
612
                    $loggerInstance->debug(5, $soapCleartext . "\n"); // PHP magically encodes this as base64 while sending!
613
                    $loggerInstance->debug(5, $detachedSig . "\n");
614
                    $soapIssueCert = $soap->approveRequest($soapReqnum, $soapCleartext, $detachedSig);
615
                    $loggerInstance->debug(5,"approveRequest Request was: \n".$soap->__getLastRequest());
616
                    $loggerInstance->debug(5,"approveRequest Response was: \n".$soap->__getLastResponse());
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 (SoapFault $e) {
642
                    throw new Exception("SoapFault: Error when sending or receiving SOAP message: " . "{$e->faultcode}: {$e->faultname}: {$e->faultstring}: {$e->faultactor}: {$e->detail}: {$e->headerfault}\n");
643
                } catch (Exception $e) {
644
                    throw new Exception("Exception: Something odd happened between the SOAP requests:" . $e->getMessage());
645
                }
646
                return [
647
                    "CERT" => openssl_x509_read($parsedCert['pem']),
648
                    "SERIAL" => $parsedCert['serial'],
649
                    "ISSUER" => $raCertFile, // change this to the actual eduPKI Issuer CA
650
                    "ROOT" => $theRoot, // change this to the actual eduPKI Root CA
651
                ];
652
            default:
653
                /* HTTP POST the CSR to the CA with the $expiryDays as parameter
654
                 * on successful execution, gets back a PEM file which is the
655
                 * certificate (structure TBD)
656
                 * $httpResponse = httpRequest("https://clientca.hosted.eduroam.org/issue/", ["csr" => $csr, "expiry" => $expiryDays ] );
657
                 *
658
                 * The result of this if clause has to be a certificate in PHP's 
659
                 * "openssl_object" style (like the one that openssl_csr_sign would 
660
                 * produce), to be stored in the variable $cert; we also need the
661
                 * serial - which can be extracted from the received cert and has
662
                 * to be stored in $serial.
663
                 */
664
                throw new Exception("External silverbullet CA is not implemented yet!");
665
        }
666
    }
667
668
}
669