Passed
Push — master ( c4e371...cb3b3a )
by Stefan
09:02
created

SilverbulletCertificate::soap_from_xml_integer()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
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`, CONCAT('',`serial_number`) AS sn, `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`, CONCAT('',`serial_number`) AS sn, `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->sn;
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
            // Scrutinizer thinks this needs to be a string, but a resource is just fine
204
            "sha1" => openssl_x509_fingerprint(/** @scrutinizer ignore-type */$cert, "sha1"),
205
            "sha256" => openssl_x509_fingerprint(/** @scrutinizer ignore-type */$cert, "sha256"),
206
            'importPassword' => $importPassword,
207
            'GUID' => common\Entity::uuid("", $exportedCertProt),
208
        ];
209
    }
210
211
    /**
212
     * triggers a new OCSP statement for the given serial number
213
     * 
214
     * @return string DER-encoded OCSP status info (binary data!)
215
     */
216
    public function triggerNewOCSPStatement() {
217
        $logHandle = new \core\common\Logging();
218
        $logHandle->debug(2, "Triggering new OCSP statement for serial $this->serial.\n");
219
        switch (CONFIG_CONFASSISTANT['SILVERBULLET']['CA']['type']) {
220
            case "embedded":
221
                $certstatus = "";
222
                // get all relevant info from object properties
223
                if ($this->serial >= 0) { // let's start with the assumption that the cert is valid
224
                    if ($this->revocationStatus == "REVOKED") {
225
                        // already revoked, simply return canned OCSP response
226
                        $certstatus = "R";
227
                    } else {
228
                        $certstatus = "V";
229
                    }
230
                }
231
232
                $originalExpiry = date_create_from_format("Y-m-d H:i:s", $this->expiry);
233
                if ($originalExpiry === FALSE) {
234
                    throw new Exception("Unable to calculate original expiry date, input data bogus!");
235
                }
236
                $validity = date_diff(/** @scrutinizer ignore-type */ date_create(), $originalExpiry);
237
                if ($validity->invert == 1) {
238
                    // negative! Cert is already expired, no need to revoke. 
239
                    // No need to return anything really, but do return the last known OCSP statement to prevent special case
240
                    $certstatus = "E";
241
                }
242
                $profile = new ProfileSilverbullet($this->profileId);
243
                $inst = new IdP($profile->institution);
244
                $federation = strtoupper($inst->federation);
245
                // generate stub index.txt file
246
                $tempdirArray = \core\common\Entity::createTemporaryDirectory("test");
247
                $tempdir = $tempdirArray['dir'];
248
                $nowIndexTxt = (new \DateTime())->format("ymdHis") . "Z";
249
                $expiryIndexTxt = $originalExpiry->format("ymdHis") . "Z";
250
                $serialHex = strtoupper(dechex($this->serial));
251
                if (strlen($serialHex) % 2 == 1) {
252
                    $serialHex = "0" . $serialHex;
253
                }
254
255
                $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";
256
                $logHandle->debug(4, "index.txt contents-to-be: $indexStatement");
257
                if (!file_put_contents($tempdir . "/index.txt", $indexStatement)) {
258
                    $logHandle->debug(1, "Unable to write openssl index.txt file for revocation handling!");
259
                }
260
                // index.txt.attr is dull but needs to exist
261
                file_put_contents($tempdir . "/index.txt.attr", "unique_subject = yes\n");
262
                // call "openssl ocsp" to manufacture our own OCSP statement
263
                // adding "-rmd sha1" to the following command-line makes the
264
                // choice of signature algorithm for the response explicit
265
                // but it's only available from openssl-1.1.0 (which we do not
266
                // want to require just for that one thing).
267
                $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";
268
                $logHandle->debug(2, "Calling openssl ocsp with following cmdline: $execCmd\n");
269
                $output = [];
270
                $return = 999;
271
                exec($execCmd, $output, $return);
272
                if ($return !== 0) {
273
                    throw new Exception("Non-zero return value from openssl ocsp!");
274
                }
275
                $ocsp = file_get_contents($tempdir . "/$serialHex.response.der");
276
                // remove the temp dir!
277
                unlink($tempdir . "/$serialHex.response.der");
278
                unlink($tempdir . "/index.txt.attr");
279
                unlink($tempdir . "/index.txt");
280
                rmdir($tempdir);
281
                break;
282
            case "eduPKI":
283
                // nothing to be done here - eduPKI have their own OCSP responder
284
                // and the certs point to it. So we are not in the loop.
285
                break;
286
            default:
287
                /* HTTP POST the serial to the CA. The CA knows about the state of
288
                 * the certificate.
289
                 *
290
                 * $httpResponse = httpRequest("https://clientca.hosted.eduroam.org/ocsp/", ["serial" => $serial ] );
291
                 *
292
                 * The result of this if clause has to be a DER-encoded OCSP statement
293
                 * to be stored in the variable $ocsp
294
                 */
295
                throw new Exception("This type of silverbullet CA is not implemented yet!");
296
        }
297
        // write the new statement into DB
298
        $this->databaseHandle->exec("UPDATE silverbullet_certificate SET OCSP = ?, OCSP_timestamp = NOW() WHERE serial_number = ?", "si", $ocsp, $this->serial);
299
        return $ocsp;
300
    }
301
302
    /**
303
     * revokes a certificate
304
     * @return array with revocation information
305
     */
306
    public function revokeCertificate() {
307
        $nowSql = (new \DateTime())->format("Y-m-d H:i:s");
308
        // regardless if embedded or not, always keep local state in our own DB
309
        $this->databaseHandle->exec("UPDATE silverbullet_certificate SET revocation_status = 'REVOKED', revocation_time = ? WHERE serial_number = ?", "si", $nowSql, $this->serial);
310
        $this->loggerInstance->debug(2, "Certificate revocation status for $this->serial updated, about to call triggerNewOCSPStatement().\n");
311
        // newly instantiate us, DB content has changed...
312
        $certObject = new SilverbulletCertificate((string)$this->serial);
313
        // embedded CA does "nothing special" for revocation: the DB change was the entire thing to do
314
        // but for external CAs, we need to notify explicitly that the cert is now revoked
315
        switch (CONFIG_CONFASSISTANT['SILVERBULLET']['CA']['type']) {
316
            case "embedded":
317
                break;
318
            case "eduPKI":
319
                try {
320
                    $soap = SilverbulletCertificate::initEduPKISoapSession("RA");
321
                    $soapRevocationSerial = $soap->newRevocationRequest(["Serial", $certObject->serial], "");
322
                    if ($soapRevocationSerial == 0) {
323
                        throw new Exception("Unable to create revocation request, serial number was zero.");
324
                    }
325
                    // retrieve the raw request to prepare for signature and approval
326
                    $soapRawRevRequest = $soap->getRawRevocationRequest($soapRevocationSerial);
327
                    if (strlen($soapRawRevRequest) < 10) { // very basic error handling
328
                        throw new Exception("Suspiciously short data to sign!");
329
                    }
330
                    // for obnoxious reasons, we have to dump the request into a file and let pkcs7_sign read from the file
331
                    // rather than just using the string. Grr.
332
                    $tempdir = \core\common\Entity::createTemporaryDirectory("test");
333
                    file_put_contents($tempdir['dir'] . "/content.txt", $soapRawRevRequest);
334
                    // retrieve our RA cert from filesystem
335
                    // sign the data, using cmdline because openssl_pkcs7_sign produces strange results
336
                    // -binary didn't help, nor switch -md to sha1 sha256 or sha512
337
                    $this->loggerInstance->debug(5, "Actual content to be signed is this:\n$soapRawRevRequest\n");
338
                    $execCmd = CONFIG['PATHS']['openssl'] . " smime -sign -binary -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";
339
                    $this->loggerInstance->debug(2, "Calling openssl smime with following cmdline: $execCmd\n");
340
                    $output = [];
341
                    $return = 999;
342
                    exec($execCmd, $output, $return);
343
                    if ($return !== 0) {
344
                        throw new Exception("Non-zero return value from openssl smime!");
345
                    }
346
                    // and get the signature blob back from the filesystem
347
                    $detachedSig = trim(file_get_contents($tempdir['dir'] . "/signature.txt"));
348
                    $soapIssueRev = $soap->approveRevocationRequest($soapRevocationSerial, $soapRawRevRequest, $detachedSig);
349
                    if ($soapIssueRev === FALSE) {
350
                        throw new Exception("The locally approved revocation request was NOT processed by the CA.");
351
                    }
352
                } catch (Exception $e) {
353
                    // PHP 7.1 can do this much better
354
                    if (is_soap_fault($e)) {
355
                        throw new Exception("Error when sending SOAP request: " . "{$e->faultcode}: {$e->faultstring}\n");
356
                    }
357
                    throw new Exception("Something odd happened while doing the SOAP request:" . $e->getMessage());
358
                }
359
                break;
360
            default:
361
                throw new Exception("Unknown type of CA requested!");
362
        }
363
        // what happens wrt OCSP etc. is really something for the following function to decide. We just call it.
364
        $certObject->triggerNewOCSPStatement();
365
    }
366
367
    /**
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...
368
     * create a CSR
369
     * 
370
     * @param resource $privateKey the private key to create the CSR with
371
     * @return array with the CSR and some meta info
372
     */
373
    private static function generateCsr($privateKey, $fed, $realm) {
374
        $databaseHandle = DBConnection::handle("INST");
375
        $loggerInstance = new common\Logging();
376
        $usernameIsUnique = FALSE;
377
        $username = "";
378
        while ($usernameIsUnique === FALSE) {
379
            $usernameLocalPart = common\Entity::randomString(64 - 1 - strlen($realm), "0123456789abcdefghijklmnopqrstuvwxyz");
380
            $username = $usernameLocalPart . "@" . $realm;
381
            $uniquenessQuery = $databaseHandle->exec("SELECT cn from silverbullet_certificate WHERE cn = ?", "s", $username);
382
            // SELECT -> resource, not boolean
383
            if (mysqli_num_rows(/** @scrutinizer ignore-type */ $uniquenessQuery) == 0) {
384
                $usernameIsUnique = TRUE;
385
            }
386
        }
387
388
        $loggerInstance->debug(5, "generateCertificate: generating CSR.\n");
389
390
        switch (CONFIG_CONFASSISTANT['SILVERBULLET']['CA']['type']) {
391
            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...
392
393
                $newCsr = openssl_csr_new(
394
                        ['O' => CONFIG_CONFASSISTANT['CONSORTIUM']['name'],
395
                    'OU' => $fed,
396
                    'CN' => $username,
397
                    'emailAddress' => $username,
398
                        ], $privateKey, [
399
                    'digest_alg' => 'sha256',
400
                    'req_extensions' => 'v3_req',
401
                        ]
402
                );
403
                break;
404
            case "eduPKI":
405
                $tempdirArray = \core\common\Entity::createTemporaryDirectory("test");
406
                $tempdir = $tempdirArray['dir'];
407
                // dump private key into directly
408
                $outstring = "";
409
                openssl_pkey_export($privateKey, $outstring);
410
                file_put_contents($tempdir . "/pkey.pem", $outstring);
411
                // PHP can only do one DC in the Subject. But we need three.
412
                $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";
413
                $loggerInstance->debug(2, "Calling openssl req with following cmdline: $execCmd\n");
414
                $output = [];
415
                $return = 999;
416
                exec($execCmd, $output, $return);
417
                if ($return !== 0) {
418
                    throw new Exception("Non-zero return value from openssl req!");
419
                }
420
                $newCsr = file_get_contents("$tempdir/request.csr");
421
                // remove the temp dir!
422
                unlink("$tempdir/pkey.pem");
423
                unlink("$tempdir/request.csr");
424
                rmdir($tempdir);
425
                break;
426
            default:
427
                throw new Exception("Unknown CA!");
428
        }
429
        if ($newCsr === FALSE) {
430
            throw new Exception("Unable to create a CSR!");
431
        }
432
        return [
433
            "CSR" => $newCsr, // a resource for embedded, a string for eduPKI
434
            "USERNAME" => $username,
435
            "FED" => $fed
436
        ];
437
    }
438
439
    // taken and adapted from 
440
    // https://www.uni-muenster.de/WWUCA/de/howto-special-phpsoap.html
441
    
442
    public static function soap_from_xml_integer($x) {
0 ignored issues
show
Coding Style introduced by
Method name "SilverbulletCertificate::soap_from_xml_integer" is not in camel caps format
Loading history...
Coding Style introduced by
You must use "/**" style comments for a function comment
Loading history...
443
        $y = simplexml_load_string($x);
444
        return array(
445
            $y->getName(),
446
            $y->__toString()
447
        );
448
    }
449
450
    public static function soap_to_xml_integer($x) {
0 ignored issues
show
Coding Style introduced by
Method name "SilverbulletCertificate::soap_to_xml_integer" is not in camel caps format
Loading history...
Coding Style introduced by
Missing function doc comment
Loading history...
451
        return '<' . $x[0] . '>'
452
                . htmlentities($x[1], ENT_NOQUOTES | ENT_XML1)
453
                . '</' . $x[0] . '>';
454
    }
455
456
    private static function initEduPKISoapSession($type) {
0 ignored issues
show
Coding Style introduced by
Missing function doc comment
Loading history...
457
        // set context parameters common to both endpoints
458
        $context_params = [
459
            'http' => [
460
                'timeout' => 60,
461
                'user_agent' => 'Stefan',
462
                'protocol_version' => 1.1
463
            ],
464
            'ssl' => [
465
                'verify_peer' => true,
466
                'verify_peer_name' => true,
467
                // below is the CA "/C=DE/O=Deutsche Telekom AG/OU=T-TeleSec Trust Center/CN=Deutsche Telekom Root CA 2"
468
                'cafile' => ROOT . "/config/SilverbulletClientCerts/eduPKI-webserver-root.pem",
469
                'verify_depth' => 5,
470
                'capture_peer_cert' => true,
471
            ],
472
        ];
473
        $url = "";
474
        switch ($type) {
475
            case "PUBLIC":
476
                $url = "https://pki.edupki.org/edupki-test-ca/cgi-bin/pub/soap?wsdl=1";
477
                $context_params['ssl']['peer_name'] = 'pki.edupki.org';
478
                break;
479
            case "RA":
480
                $url = "https://ra.edupki.org/edupki-test-ca/cgi-bin/ra/soap?wsdl=1";
481
                $context_params['ssl']['peer_name'] = 'ra.edupki.org';
482
                break;
483
            default:
484
                throw new Exception("Unknown type of eduPKI interface requested.");
485
        }
486
        if ($type == "RA") { // add client auth parameters to the context
487
            $context_params['ssl']['local_cert'] = ROOT . "/config/SilverbulletClientCerts/edupki-test-ra.pem";
488
            $context_params['ssl']['local_pk'] = ROOT . "/config/SilverbulletClientCerts/edupki-test-ra.clearkey";
489
            // $context_params['ssl']['passphrase'] = SilverbulletCertificate::EDUPKI_RA_PKEY_PASSPHRASE;
490
        }
491
        // initialse connection to eduPKI CA / eduroam RA
492
        $soap = new \SoapClient($url, [
493
            'soap_version' => SOAP_1_1,
494
            'trace' => TRUE,
495
            'exceptions' => TRUE,
496
            'connection_timeout' => 5, // if can't establish the connection within 5 sec, something's wrong
497
            'cache_wsdl' => WSDL_CACHE_NONE,
498
            'user_agent' => 'eduroam CAT to eduPKI SOAP Interface',
499
            'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
500
            'stream_context' => stream_context_create($context_params),
501
            'typemap' => [
502
                [
503
                    'type_ns' => 'http://www.w3.org/2001/XMLSchema',
504
                    'type_name' => 'integer',
505
                    'from_xml' => 'core\SilverbulletCertificate::soap_from_xml_integer',
506
                    'to_xml' => 'core\SilverbulletCertificate::soap_to_xml_integer',
507
                ],
508
            ],
509
                ]
510
        );
511
        return $soap;
512
    }
513
514
    const EDUPKI_RA_ID = 700;
515
    const EDUPKI_CERT_PROFILE = "User SOAP";
516
    const EDUPKI_RA_PKEY_PASSPHRASE = "...";
517
518
    /**
519
     * take a CSR and sign it with our issuing CA's certificate
520
     * 
521
     * @param mixed $csr the CSR
0 ignored issues
show
Coding Style introduced by
Expected 8 spaces after parameter name; 1 found
Loading history...
522
     * @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...
523
     * @return array the cert and some meta info
524
     */
525
    private static function signCsr($csr, $expiryDays) {
526
        $loggerInstance = new common\Logging();
527
        $databaseHandle = DBConnection::handle("INST");
528
        switch (CONFIG_CONFASSISTANT['SILVERBULLET']['CA']['type']) {
529
            case "embedded":
530
                $rootCaPem = file_get_contents(ROOT . "/config/SilverbulletClientCerts/rootca.pem");
531
                $raCertFile = file_get_contents(ROOT . "/config/SilverbulletClientCerts/real.pem");
532
                $raCert = openssl_x509_read($raCertFile);
533
                $raKey = openssl_pkey_get_private("file://" . ROOT . "/config/SilverbulletClientCerts/real.key");
534
                $nonDupSerialFound = FALSE;
535
                do {
536
                    $serial = random_int(1000000000, PHP_INT_MAX);
537
                    $dupeQuery = $databaseHandle->exec("SELECT serial_number FROM silverbullet_certificate WHERE serial_number = ?", "i", $serial);
538
                    // SELECT -> resource, not boolean
539
                    if (mysqli_num_rows(/** @scrutinizer ignore-type */$dupeQuery) == 0) {
540
                        $nonDupSerialFound = TRUE;
541
                    }
542
                } while (!$nonDupSerialFound);
543
                $loggerInstance->debug(5, "generateCertificate: signing imminent with unique serial $serial.\n");
544
                return [
545
                    "CERT" => openssl_csr_sign($csr["CSR"], $raCert, $raKey, $expiryDays, ['digest_alg' => 'sha256'], $serial),
546
                    "SERIAL" => $serial,
547
                    "ISSUER" => $raCertFile,
548
                    "ROOT" => $rootCaPem,
549
                ];
550
            case "eduPKI":
551
                // initialse connection to eduPKI CA / eduroam RA and send the request to them
552
                try {
553
                    $altArray = [# Array mit den Subject Alternative Names
554
                        "email:" . $csr["USERNAME"]
555
                    ];
556
                    $soapPub = SilverbulletCertificate::initEduPKISoapSession("PUBLIC");
557
                    $loggerInstance->debug(5, "FIRST ACTUAL SOAP REQUEST (Public, newRequest)!\n");
558
                    $loggerInstance->debug(5, "PARAM_1: " . SilverbulletCertificate::EDUPKI_RA_ID . "\n");
559
                    $loggerInstance->debug(5, "PARAM_2: " . $csr["CSR"] . "\n");
560
                    $loggerInstance->debug(5, "PARAM_3: ");
561
                    $loggerInstance->debug(5, $altArray);
562
                    $loggerInstance->debug(5, "PARAM_4: " . SilverbulletCertificate::EDUPKI_CERT_PROFILE . "\n");
563
                    $loggerInstance->debug(5, "PARAM_5: " . sha1("notused") . "\n");
564
                    $loggerInstance->debug(5, "PARAM_6: " . $csr["USERNAME"] . "\n");
565
                    $loggerInstance->debug(5, "PARAM_7: " . $csr["USERNAME"] . "\n");
566
                    $loggerInstance->debug(5, "PARAM_8: " . ProfileSilverbullet::PRODUCTNAME . "\n");
567
                    $loggerInstance->debug(5, "PARAM_9: false\n");
568
                    $soapNewRequest = $soapPub->newRequest(
569
                            SilverbulletCertificate::EDUPKI_RA_ID, # RA-ID
570
                            $csr["CSR"], # Request im PEM-Format
571
                            $altArray, # altNames
572
                            SilverbulletCertificate::EDUPKI_CERT_PROFILE, # Zertifikatprofil
573
                            sha1("notused"), # PIN
574
                            $csr["USERNAME"], # Name des Antragstellers
575
                            $csr["USERNAME"], # Kontakt-E-Mail
576
                            ProfileSilverbullet::PRODUCTNAME, # Organisationseinheit des Antragstellers
577
                            false                   # Veröffentlichen des Zertifikats?
578
                    );
579
                    $loggerInstance->debug(5, $soapPub->__getLastRequest());
580
                    $loggerInstance->debug(5, $soapPub->__getLastResponse());
581
                    if ($soapNewRequest == 0) {
582
                        throw new Exception("Error when sending SOAP request (request serial number was zero). No further details available.");
583
                    }
584
                    $soapReqnum = intval($soapNewRequest);
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
                try {
593
                    $soap = SilverbulletCertificate::initEduPKISoapSession("RA");
594
                    // tell the CA the desired expiry date of the new certificate
595
                    $expiry = new \DateTime();
596
                    $expiry->modify("+$expiryDays day");
597
                    $expiry->setTimezone(new \DateTimeZone("UTC"));
598
                    $soapExpiryChange = $soap->setRequestParameters(
599
                            $soapReqnum, [
600
                        "RaID" => SilverbulletCertificate::EDUPKI_RA_ID,
601
                        "Role" => SilverbulletCertificate::EDUPKI_CERT_PROFILE,
602
                        "Subject" => "DC=eduroam,DC=test,DC=test,C=" . $csr["FED"] . ",O=" . CONFIG_CONFASSISTANT['CONSORTIUM']['name'] . ",OU=" . $csr["FED"] . ",CN=" . $csr['USERNAME'] . ",emailAddress=" . $csr['USERNAME'],
603
                        "SubjectAltNames" => ["email:" . $csr["USERNAME"]],
604
                        "NotBefore" => (new \DateTime())->format('c'),
605
                        "NotAfter" => $expiry->format('c'),
606
                            ]
607
                    );
608
                    if ($soapExpiryChange === FALSE) {
609
                        throw new Exception("Error when sending SOAP request (unable to change expiry date).");
610
                    }
611
                    // retrieve the raw request to prepare for signature and approval
612
                    // this seems to come out base64-decoded already; maybe PHP
613
                    // considers this "convenience"? But we need it as sent on
614
                    // the wire, so re-encode it!
615
                    $soapCleartext = $soap->getRawRequest($soapReqnum);
616
617
                    $loggerInstance->debug(5, "Actual received SOAP resonse for getRawRequest was:\n\n");
618
                    $loggerInstance->debug(5, $soap->__getLastResponse());
619
                    // for obnoxious reasons, we have to dump the request into a file and let pkcs7_sign read from the file
620
                    // rather than just using the string. Grr.
621
                    $tempdir = \core\common\Entity::createTemporaryDirectory("test");
622
                    file_put_contents($tempdir['dir'] . "/content.txt", $soapCleartext);
623
                    // retrieve our RA cert from filesystem
624
                    $raCertFile = file_get_contents(ROOT . "/config/SilverbulletClientCerts/edupki-test-ra.pem");
625
                    $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...
626
                    $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...
627
                    // sign the data, using cmdline because openssl_pkcs7_sign produces strange results
628
                    // -binary didn't help, nor switch -md to sha1 sha256 or sha512
629
                    $loggerInstance->debug(5, "Actual content to be signed is this:\n$soapCleartext\n");
630
                    $execCmd = CONFIG['PATHS']['openssl'] . " smime -sign -binary -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";
631
                    $loggerInstance->debug(2, "Calling openssl smime with following cmdline: $execCmd\n");
632
                    $output = [];
633
                    $return = 999;
634
                    exec($execCmd, $output, $return);
635
                    if ($return !== 0) {
636
                        throw new Exception("Non-zero return value from openssl smime!");
637
                    }
638
                    // and get the signature blob back from the filesystem
639
                    $detachedSig = trim(file_get_contents($tempdir['dir'] . "/signature.txt"));
640
                    $loggerInstance->debug(5, "Request for server approveRequest has parameters:\n");
641
                    $loggerInstance->debug(5, $soapReqnum . "\n");
642
                    $loggerInstance->debug(5, $soapCleartext . "\n"); // PHP magically encodes this as base64 while sending!
643
                    $loggerInstance->debug(5, $detachedSig . "\n");
644
                    $soapIssueCert = $soap->approveRequest($soapReqnum, $soapCleartext, $detachedSig);
645
                    $loggerInstance->debug(5, "approveRequest Request was: \n" . $soap->__getLastRequest());
646
                    $loggerInstance->debug(5, "approveRequest Response was: \n" . $soap->__getLastResponse());
647
                    if ($soapIssueCert === FALSE) {
648
                        throw new Exception("The locally approved request was NOT processed by the CA.");
649
                    }
650
                    // now, get the actual cert from the CA
651
                    sleep(55);
652
                    $counter = 55;
653
                    $parsedCert = NULL;
654
                    do {
655
                        $counter += 5;
656
                        sleep(5); // always start with a wait. Signature round-trip on the server side is at least one minute.
657
                        $soapCert = $soap->getCertificateByRequestSerial($soapReqnum);
658
                        $x509 = new common\X509();
659
                        if (strlen($soapCert) > 10) {
660
                            $parsedCert = $x509->processCertificate($soapCert);
661
                        }
662
                    } while (!is_array($parsedCert) && $counter < 500);
663
664
                    if (!is_array($parsedCert)) {
1 ignored issue
show
introduced by
The condition is_array($parsedCert) is always false.
Loading history...
665
                        throw new Exception("We did not actually get a certificate after waiting for 5 minutes.");
666
                    }
667
                    // let's get the CA certificate chain
668
669
                    $caInfo = $soap->getCAInfo();
670
                    $certList = $x509->splitCertificate($caInfo->CAChain[0]);
671
                    // find the root
672
                    $theRoot = "";
673
                    foreach ($certList as $oneCert) {
674
                        $content = $x509->processCertificate($oneCert);
675
                        if ($content['root'] == 1) {
676
                            $theRoot = $content;
677
                        }
678
                    }
679
                    if ($theRoot == "") {
680
                        throw new Exception("CAInfo has no root certificate for us!");
681
                    }
682
                } catch (SoapFault $e) {
683
                    throw new Exception("SoapFault: Error when sending or receiving SOAP message: " . "{$e->faultcode}: {$e->faultname}: {$e->faultstring}: {$e->faultactor}: {$e->detail}: {$e->headerfault}\n");
684
                } catch (Exception $e) {
685
                    throw new Exception("Exception: Something odd happened between the SOAP requests:" . $e->getMessage());
686
                }
687
                return [
688
                    "CERT" => openssl_x509_read($parsedCert['pem']),
689
                    "SERIAL" => $parsedCert['full_details']['serialNumber'],
690
                    "ISSUER" => $theRoot, // change this to the actual eduPKI Issuer CA
691
                    "ROOT" => $theRoot, // change this to the actual eduPKI Root CA
692
                ];
693
            default:
694
                /* HTTP POST the CSR to the CA with the $expiryDays as parameter
695
                 * on successful execution, gets back a PEM file which is the
696
                 * certificate (structure TBD)
697
                 * $httpResponse = httpRequest("https://clientca.hosted.eduroam.org/issue/", ["csr" => $csr, "expiry" => $expiryDays ] );
698
                 *
699
                 * The result of this if clause has to be a certificate in PHP's 
700
                 * "openssl_object" style (like the one that openssl_csr_sign would 
701
                 * produce), to be stored in the variable $cert; we also need the
702
                 * serial - which can be extracted from the received cert and has
703
                 * to be stored in $serial.
704
                 */
705
                throw new Exception("External silverbullet CA is not implemented yet!");
706
        }
707
    }
708
709
}
710