Passed
Push — release_2_0 ( 341cc0...210320 )
by Tomasz
22:56 queued 29s
created

SilverbulletCertificate::signCsr()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 48
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 32
dl 0
loc 48
rs 8.7857
c 0
b 0
f 0
cc 6
nc 7
nop 3
1
<?php
2
3
/*
4
 * Contributions to this work were made on behalf of the GÉANT project, a 
5
 * project that has received funding from the European Union’s Horizon 2020 
6
 * research and innovation programme under Grant Agreement No. 731122 (GN4-2).
7
 * 
8
 * On behalf of the GÉANT project, GEANT Association is the sole owner of the 
9
 * copyright in all material which was developed by a member of the GÉANT 
10
 * project. GÉANT Vereniging (Association) is registered with the Chamber of 
11
 * Commerce in Amsterdam with registration number 40535155 and operates in the
12
 * UK as a branch of GÉANT Vereniging. 
13
 * 
14
 * Registered office: Hoekenrode 3, 1102BR Amsterdam, The Netherlands. 
15
 * UK branch address: City House, 126-130 Hills Road, Cambridge CB2 1PQ, UK
16
 * 
17
 * License: see the web/copyright.inc.php file in the file structure or
18
 *          <base_url>/copyright.php after deploying the software
19
 */
20
21
/**
22
 * This file contains the SilverbulletInvitation class.
23
 *
24
 * @author Stefan Winter <[email protected]>
25
 * @author Tomasz Wolniewicz <[email protected]>
26
 *
27
 * @package Developer
28
 *
29
 */
30
31
namespace core;
32
33
use \Exception;
34
35
class SilverbulletCertificate extends EntityWithDBProperties {
36
37
    public $username;
38
    public $expiry;
39
    public $serial;
40
    public $dbId;
41
    public $invitationId;
42
    public $userId;
43
    public $profileId;
44
    public $issued;
45
    public $device;
46
    public $revocationStatus;
47
    public $revocationTime;
48
    public $ocsp;
49
    public $ocspTimestamp;
50
    public $status;
51
    public $ca_type;
52
    public $annotation;
53
54
    const CERTSTATUS_VALID = 1;
55
    const CERTSTATUS_EXPIRED = 2;
56
    const CERTSTATUS_REVOKED = 3;
57
    const CERTSTATUS_INVALID = 4;
58
59
    /**
60
     * instantiates an existing certificate, identified either by its serial
61
     * number or the username. 
62
     * 
63
     * Use static issueCertificate() to generate a whole new cert.
64
     * 
65
     * @param int|string $identifier identify certificate either by CN or by serial
66
     * @param string     $certtype   RSA or ECDSA?
67
     */
68
    public function __construct($identifier, $certtype) {
69
        $this->databaseType = "INST";
70
        parent::__construct();
71
        $this->username = "";
72
        $this->expiry = "2000-01-01 00:00:00";
73
        $this->serial = -1;
74
        $this->dbId = -1;
75
        $this->invitationId = -1;
76
        $this->userId = -1;
77
        $this->profileId = -1;
78
        $this->issued = "2000-01-01 00:00:00";
79
        $this->device = NULL;
80
        $this->revocationStatus = "REVOKED";
81
        $this->revocationTime = "2000-01-01 00:00:00";
82
        $this->ocsp = NULL;
83
        $this->ocspTimestamp = "2000-01-01 00:00:00";
84
        $this->ca_type = $certtype;
85
        $this->status = SilverbulletCertificate::CERTSTATUS_INVALID;
86
        $this->annotation = NULL;
87
88
        $incoming = FALSE;
89
        if (is_numeric($identifier)) {
90
            $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`, `extrainfo` FROM `silverbullet_certificate` WHERE serial_number = ? AND ca_type = ?", "is", $identifier, $certtype);
91
        } else { // it's a string instead
92
            $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`, `extrainfo` FROM `silverbullet_certificate` WHERE cn = ? AND ca_type = ?", "ss", $identifier, $certtype);
93
        }
94
95
        // SELECT -> mysqli_resource, not boolean
96
        while ($oneResult = mysqli_fetch_object(/** @scrutinizer ignore-type */ $incoming)) { // there is only at most one
97
            $this->username = $oneResult->cn;
98
            $this->expiry = $oneResult->expiry;
99
            $this->serial = $oneResult->serial_number;
100
            $this->dbId = $oneResult->id;
101
            $this->invitationId = $oneResult->silverbullet_invitation_id;
102
            $this->userId = $oneResult->silverbullet_user_id;
103
            $this->profileId = $oneResult->profile_id;
104
            $this->issued = $oneResult->issued;
105
            $this->device = $oneResult->device;
106
            $this->revocationStatus = $oneResult->revocation_status;
107
            $this->revocationTime = $oneResult->revocation_time;
108
            $this->ocsp = $oneResult->OCSP;
109
            $this->ocspTimestamp = $oneResult->OCSP_timestamp;
110
            $this->annotation = $oneResult->extrainfo;
111
            // is the cert expired?
112
            $now = new \DateTime();
113
            $cert_expiry = new \DateTime($this->expiry);
114
            $delta = $now->diff($cert_expiry);
115
            $this->status = ($delta->invert == 1 ? SilverbulletCertificate::CERTSTATUS_EXPIRED : SilverbulletCertificate::CERTSTATUS_VALID);
116
            // expired is expired; even if it was previously revoked. But do update status for revoked ones...
117
            if ($this->status == SilverbulletCertificate::CERTSTATUS_VALID && $this->revocationStatus == "REVOKED") {
118
                $this->status = SilverbulletCertificate::CERTSTATUS_REVOKED;
119
            }
120
        }
121
    }
122
123
    /**
124
     * retrieve basic information about the certificate
125
     * 
126
     * @return array of basic certificate details
127
     */
128
    public function getBasicInfo() {
129
        $returnArray = []; // unnecessary because the iterator below is never empty, but Scrutinizer gets excited nontheless
130
        foreach (['status', 'serial', 'username', 'issued', 'expiry', 'ca_type', 'annotation'] as $key) {
131
            $returnArray[$key] = $this->$key;
132
        }
133
        $returnArray['device'] = \devices\Devices::listDevices()[$this->device]['display'] ?? $this->device;
134
        return $returnArray;
135
    }
136
137
    /**
138
     * adds extra information about the certificate to the DB
139
     * 
140
     * @param array $annotation information to be stored
141
     * @return void
142
     */
143
    public function annotate($annotation) {
144
        $encoded = json_encode($annotation);
145
        $this->annotation = $encoded;
146
        $this->databaseHandle->exec("UPDATE silverbullet_certificate SET annotation = '$annotation' WHERE serial_number = ?", "i", $this->serial);
147
    }
148
    /**
149
     * we don't use caching in SB, so this function does nothing
150
     * 
151
     * @return void
152
     */
153
    public function updateFreshness() {
154
        // nothing to be done here.
155
    }
156
157
    /**
158
     * issue a certificate based on a token
159
     *
160
     * @param string $token          the token string
161
     * @param string $importPassword the PIN
162
     * @param string $certtype       is this for the RSA or ECDSA CA?
163
     * @return array
164
     */
165
    public static function issueCertificate($token, $importPassword, $certtype) {
166
        $loggerInstance = new common\Logging();
167
        $databaseHandle = DBConnection::handle("INST");
168
        $loggerInstance->debug(5, "generateCertificate() - starting.\n");
169
        $invitationObject = new SilverbulletInvitation($token);
170
        $profile = new ProfileSilverbullet($invitationObject->profile);
171
        $inst = new IdP($profile->institution);
172
        $loggerInstance->debug(5, "tokenStatus: done, got " . $invitationObject->invitationTokenStatus . ", " . $invitationObject->profile . ", " . $invitationObject->userId . ", " . $invitationObject->expiry . ", " . $invitationObject->invitationTokenString . "\n");
173
        if ($invitationObject->invitationTokenStatus != SilverbulletInvitation::SB_TOKENSTATUS_VALID && $invitationObject->invitationTokenStatus != SilverbulletInvitation::SB_TOKENSTATUS_PARTIALLY_REDEEMED) {
174
            throw new Exception("Attempt to generate a SilverBullet installer with an invalid/redeemed/expired token. The user should never have gotten that far!");
175
        }
176
177
        // SQL query to find the expiry date of the *user* to find the correct ValidUntil for the cert
178
        $user = $invitationObject->userId;
179
        $userrow = $databaseHandle->exec("SELECT expiry FROM silverbullet_user WHERE id = ?", "i", $user);
180
        // SELECT -> resource, not boolean
181
        if ($userrow->num_rows != 1) {
182
            throw new Exception("Despite a valid token, the corresponding user was not found in database or database query error!");
183
        }
184
        $expiryObject = mysqli_fetch_object(/** @scrutinizer ignore-type */ $userrow);
185
        $loggerInstance->debug(5, "EXP: " . $expiryObject->expiry . "\n");
186
        $expiryDateObject = date_create_from_format("Y-m-d H:i:s", $expiryObject->expiry);
187
        if ($expiryDateObject === FALSE) {
188
            throw new Exception("The expiry date we got from the DB is bogus!");
189
        }
190
        $loggerInstance->debug(5, $expiryDateObject->format("Y-m-d H:i:s") . "\n");
191
        // date_create with no parameters can't fail, i.e. is never FALSE
192
        $validity = date_diff(/** @scrutinizer ignore-type */ date_create(), $expiryDateObject);
193
        $expiryDays = $validity->days + 1;
194
        if ($validity->invert == 1) { // negative! That should not be possible
195
            throw new Exception("Attempt to generate a certificate for a user which is already expired!");
196
        }
197
        switch ($certtype) {
198
            case \devices\Devices::SUPPORT_RSA:
199
                $privateKey = openssl_pkey_new(['private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA, 'encrypt_key' => FALSE]);
200
                break;
201
            case \devices\Devices::SUPPORT_ECDSA:
202
                $privateKey = openssl_pkey_new(['curve_name' => 'secp384r1', 'private_key_type' => OPENSSL_KEYTYPE_EC, 'encrypt_key' => FALSE]);
203
                break;
204
            default:
205
                throw new Exception("Unknown certificate type!");
206
        }
207
208
        $csr = SilverbulletCertificate::generateCsr($privateKey, strtoupper($inst->federation), $profile->getAttributes("internal:realm")[0]['value'], $certtype);
209
210
        $loggerInstance->debug(5, "generateCertificate: proceeding to sign cert.\n");
211
212
        $certMeta = SilverbulletCertificate::signCsr($csr["CSR"], $expiryDays, $certtype);
213
        $cert = $certMeta["CERT"];
214
        $issuingCaPem = $certMeta["ISSUER"];
215
        $rootCaPem = $certMeta["ROOT"];
216
        $serial = $certMeta["SERIAL"];
217
218
        if ($cert === FALSE) {
219
            throw new Exception("The CA did not generate a certificate.");
220
        }
221
        $loggerInstance->debug(5, "generateCertificate: post-processing certificate.\n");
222
223
        // get the SHA1 fingerprint, this will be handy for Windows installers
224
        $sha1 = openssl_x509_fingerprint($cert, "sha1");
225
        // with the cert, our private key and import password, make a PKCS#12 container out of it
226
        $exportedCertProt = "";
227
        openssl_pkcs12_export($cert, $exportedCertProt, $privateKey, $importPassword, ['extracerts' => [$issuingCaPem /* , $rootCaPem */]]);
228
        // and without intermediate, to keep EAP conversation short where possible
229
        $exportedNoInterm = "";
230
        openssl_pkcs12_export($cert, $exportedNoInterm, $privateKey, $importPassword, []);
231
        $exportedCertClear = "";
232
        openssl_pkcs12_export($cert, $exportedCertClear, $privateKey, "", ['extracerts' => [$issuingCaPem, $rootCaPem]]);
233
        // 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!
234
        // we need the *real* expiry date, not just the day-approximation
235
        $x509 = new \core\common\X509();
236
        $certString = "";
237
        openssl_x509_export($cert, $certString);
238
        $parsedCert = $x509->processCertificate($certString);
239
        $loggerInstance->debug(5, "CERTINFO: " . print_r($parsedCert['full_details'], true));
240
        $realExpiryDate = date_create_from_format("U", $parsedCert['full_details']['validTo_time_t'])->format("Y-m-d H:i:s");
241
242
        // store new cert info in DB
243
        $databaseHandle->exec("INSERT INTO `silverbullet_certificate` (`profile_id`, `silverbullet_user_id`, `silverbullet_invitation_id`, `serial_number`, `cn` ,`expiry`, `ca_type`) VALUES (?, ?, ?, ?, ?, ?, ?)", "iiissss", $invitationObject->profile, $invitationObject->userId, $invitationObject->identifier, $serial, $csr["USERNAME"], $realExpiryDate, $certtype);
244
        // newborn cert immediately gets its "valid" OCSP response
245
        $certObject = new SilverbulletCertificate($serial, $certtype);
246
        $certObject->triggerNewOCSPStatement();
247
// return PKCS#12 data stream
248
        return [
249
            "certObject" => $certObject,
250
            "certdata" => $exportedCertProt,
251
            "certdata_nointermediate" => $exportedNoInterm,
252
            "certdataclear" => $exportedCertClear,
253
            "sha1" => $sha1,
254
            'importPassword' => $importPassword,
255
            'GUID' => common\Entity::uuid("", $exportedCertProt),
256
        ];
257
    }
258
259
    /**
260
     * triggers a new OCSP statement for the given serial number
261
     * 
262
     * @return string DER-encoded OCSP status info (binary data!)
263
     */
264
    public function triggerNewOCSPStatement() {
265
        $logHandle = new \core\common\Logging();
266
        $logHandle->debug(2, "Triggering new OCSP statement for serial $this->serial.\n");
267
        switch (CONFIG_CONFASSISTANT['SILVERBULLET']['CA']['type']) {
268
            case "embedded":
269
                $certstatus = "";
270
                // get all relevant info from object properties
271
                if ($this->serial >= 0) { // let's start with the assumption that the cert is valid
272
                    if ($this->revocationStatus == "REVOKED") {
273
                        // already revoked, simply return canned OCSP response
274
                        $certstatus = "R";
275
                    } else {
276
                        $certstatus = "V";
277
                    }
278
                }
279
280
                $originalExpiry = date_create_from_format("Y-m-d H:i:s", $this->expiry);
281
                if ($originalExpiry === FALSE) {
282
                    throw new Exception("Unable to calculate original expiry date, input data bogus!");
283
                }
284
                $validity = date_diff(/** @scrutinizer ignore-type */ date_create(), $originalExpiry);
285
                if ($validity->invert == 1) {
286
                    // negative! Cert is already expired, no need to revoke. 
287
                    // No need to return anything really, but do return the last known OCSP statement to prevent special case
288
                    $certstatus = "E";
289
                }
290
                $profile = new ProfileSilverbullet($this->profileId);
291
                $inst = new IdP($profile->institution);
292
                $federation = strtoupper($inst->federation);
293
                // generate stub index.txt file
294
                $cat = new CAT();
295
                $tempdirArray = $cat->createTemporaryDirectory("test");
296
                $tempdir = $tempdirArray['dir'];
297
                $nowIndexTxt = (new \DateTime())->format("ymdHis") . "Z";
298
                $expiryIndexTxt = $originalExpiry->format("ymdHis") . "Z";
299
                $serialHex = strtoupper(dechex($this->serial));
300
                if (strlen($serialHex) % 2 == 1) {
301
                    $serialHex = "0" . $serialHex;
302
                }
303
304
                $indexStatement = "$certstatus\t$expiryIndexTxt\t" . ($certstatus == "R" ? "$nowIndexTxt,unspecified" : "") . "\t$serialHex\tunknown\t/O=" . CONFIG_CONFASSISTANT['CONSORTIUM']['name'] . "/OU=$federation/CN=$this->username\n";
305
                $logHandle->debug(4, "index.txt contents-to-be: $indexStatement");
306
                if (!file_put_contents($tempdir . "/index.txt", $indexStatement)) {
307
                    $logHandle->debug(1, "Unable to write openssl index.txt file for revocation handling!");
308
                }
309
                // index.txt.attr is dull but needs to exist
310
                file_put_contents($tempdir . "/index.txt.attr", "unique_subject = yes\n");
311
                // call "openssl ocsp" to manufacture our own OCSP statement
312
                // adding "-rmd sha1" to the following command-line makes the
313
                // choice of signature algorithm for the response explicit
314
                // but it's only available from openssl-1.1.0 (which we do not
315
                // want to require just for that one thing).
316
                $execCmd = CONFIG['PATHS']['openssl'] . " ocsp -issuer " . ROOT . "/config/SilverbulletClientCerts/real-".$this->ca_type.".pem -sha1 -ndays 10 -no_nonce -serial 0x$serialHex -CA " . ROOT . "/config/SilverbulletClientCerts/real-".$this->ca_type.".pem -rsigner " . ROOT . "/config/SilverbulletClientCerts/real-".$this->ca_type.".pem -rkey " . ROOT . "/config/SilverbulletClientCerts/real-".$this->ca_type.".key -index $tempdir/index.txt -no_cert_verify -respout $tempdir/$serialHex.response.der";
317
                $logHandle->debug(2, "Calling openssl ocsp with following cmdline: $execCmd\n");
318
                $output = [];
319
                $return = 999;
320
                exec($execCmd, $output, $return);
321
                if ($return !== 0) {
322
                    throw new Exception("Non-zero return value from openssl ocsp!");
323
                }
324
                $ocsp = file_get_contents($tempdir . "/$serialHex.response.der");
325
                // remove the temp dir!
326
                unlink($tempdir . "/$serialHex.response.der");
327
                unlink($tempdir . "/index.txt.attr");
328
                unlink($tempdir . "/index.txt");
329
                rmdir($tempdir);
330
                break;
331
            default:
332
                /* HTTP POST the serial to the CA. The CA knows about the state of
333
                 * the certificate.
334
                 *
335
                 * $httpResponse = httpRequest("https://clientca.hosted.eduroam.org/ocsp/", ["serial" => $serial ] );
336
                 *
337
                 * The result of this if clause has to be a DER-encoded OCSP statement
338
                 * to be stored in the variable $ocsp
339
                 */
340
                throw new Exception("External silverbullet CA is not implemented yet!");
341
        }
342
        // write the new statement into DB
343
        $this->databaseHandle->exec("UPDATE silverbullet_certificate SET OCSP = ?, OCSP_timestamp = NOW() WHERE serial_number = ?", "si", $ocsp, $this->serial);
344
        return $ocsp;
345
    }
346
347
    /**
348
     * revokes a certificate
349
     * @return array with revocation information
350
     */
351
    public function revokeCertificate() {
352
        $nowSql = (new \DateTime())->format("Y-m-d H:i:s");
353
        if (CONFIG_CONFASSISTANT['SILVERBULLET']['CA']['type'] != "embedded") {
354
            // send revocation request to CA.
355
            // $httpResponse = httpRequest("https://clientca.hosted.eduroam.org/revoke/", ["serial" => $serial ] );
356
            throw new Exception("External silverbullet CA is not implemented yet!");
357
        }
358
        // regardless if embedded or not, always keep local state in our own DB
359
        $this->databaseHandle->exec("UPDATE silverbullet_certificate SET revocation_status = 'REVOKED', revocation_time = ? WHERE serial_number = ? AND ca_type = ?", "sis", $nowSql, $this->serial, $this->ca_type);
360
        $this->loggerInstance->debug(2, "Certificate revocation status for $this->serial updated, about to call triggerNewOCSPStatement().\n");
361
        // newly instantiate us, DB content has changed...
362
        $certObject = new SilverbulletCertificate($this->serial, $this->ca_type);
363
        $certObject->triggerNewOCSPStatement();
364
    }
365
366
    /**
367
     * create a CSR
368
     * 
369
     * @param resource $privateKey the private key to create the CSR with
370
     * @param string   $fed        the federation to which the certificate belongs
371
     * @param string   $realm      the realm for the future username
372
     * @param string   $certtype   which type of certificate to generate: RSA or ECDSA
373
     * @return array with the CSR and some meta info
374
     */
375
    private static function generateCsr($privateKey, $fed, $realm, $certtype) {
376
        $databaseHandle = DBConnection::handle("INST");
377
        $loggerInstance = new common\Logging();
378
        $usernameIsUnique = FALSE;
379
        $username = "";
380
        while ($usernameIsUnique === FALSE) {
381
            $usernameLocalPart = common\Entity::randomString(64 - 1 - strlen($realm), "0123456789abcdefghijklmnopqrstuvwxyz");
382
            $username = $usernameLocalPart . "@" . $realm;
383
            $uniquenessQuery = $databaseHandle->exec("SELECT cn from silverbullet_certificate WHERE cn = ?", "s", $username);
384
            // SELECT -> resource, not boolean
385
            if (mysqli_num_rows(/** @scrutinizer ignore-type */ $uniquenessQuery) == 0) {
386
                $usernameIsUnique = TRUE;
387
            }
388
        }
389
390
        $loggerInstance->debug(5, "generateCertificate: generating private key.\n");
391
392
        switch ($certtype) {
393
            case \devices\Devices::SUPPORT_RSA:
394
                $alg = "sha256";
395
                break;
396
            case \devices\Devices::SUPPORT_ECDSA:
397
                $alg = "ecdsa-with-SHA1";
398
                break;
399
            default:
400
                throw new Exception("Unknown certificate type!");
401
        }
402
        $newCsr = openssl_csr_new(
403
                ['O' => CONFIG_CONFASSISTANT['CONSORTIUM']['name'],
404
            'OU' => $fed,
405
            'CN' => $username,
406
            // 'emailAddress' => $username,
407
                ], $privateKey, [
408
            'digest_alg' => $alg,
409
            'req_extensions' => 'v3_req',
410
                ]
411
        );
412
        if ($newCsr === FALSE) {
413
            throw new Exception("Unable to create a CSR!");
414
        }
415
        return [
416
            "CSR" => $newCsr,
417
            "USERNAME" => $username
418
        ];
419
    }
420
421
    /**
422
     * take a CSR and sign it with our issuing CA's certificate
423
     * 
424
     * @param mixed  $csr        the CSR
425
     * @param int    $expiryDays the number of days until the cert is going to expire
426
     * @param string $certtype   which type of certificate to use for signing
427
     * @return array the cert and some meta info
428
     */
429
    private static function signCsr($csr, $expiryDays, $certtype) {
430
        $loggerInstance = new common\Logging();
431
        $databaseHandle = DBConnection::handle("INST");
432
        switch (CONFIG_CONFASSISTANT['SILVERBULLET']['CA']['type']) {
433
            case "embedded":
434
                $rootCaPem = file_get_contents(ROOT . "/config/SilverbulletClientCerts/rootca-$certtype.pem");
435
                $issuingCaPem = file_get_contents(ROOT . "/config/SilverbulletClientCerts/real-$certtype.pem");
436
                $issuingCa = openssl_x509_read($issuingCaPem);
437
                $issuingCaKey = openssl_pkey_get_private("file://" . ROOT . "/config/SilverbulletClientCerts/real-$certtype.key");
438
                $nonDupSerialFound = FALSE;
439
                do {
440
                    $serial = random_int(1000000000, PHP_INT_MAX);
441
                    $dupeQuery = $databaseHandle->exec("SELECT serial_number FROM silverbullet_certificate WHERE serial_number = ? AND ca_type = ?", "is", $serial, $certtype);
442
                    // SELECT -> resource, not boolean
443
                    if (mysqli_num_rows(/** @scrutinizer ignore-type */$dupeQuery) == 0) {
444
                        $nonDupSerialFound = TRUE;
445
                    }
446
                } while (!$nonDupSerialFound);
447
                $loggerInstance->debug(5, "generateCertificate: signing imminent with unique serial $serial, cert type $certtype.\n");
448
                switch ($certtype) {
449
                    case \devices\Devices::SUPPORT_RSA:
450
                        $alg = "sha256";
451
                        break;
452
                    case \devices\Devices::SUPPORT_ECDSA:
453
                        $alg = "ecdsa-with-SHA1";
454
                        break;
455
                    default:
456
                        throw new Exception("Unknown cert type!");
457
                }
458
                return [
459
                    "CERT" => openssl_csr_sign($csr, $issuingCa, $issuingCaKey, $expiryDays, ['digest_alg' => $alg, 'config' => dirname(__DIR__) . "/config/SilverbulletClientCerts/openssl-$certtype.cnf"], $serial),
460
                    "SERIAL" => $serial,
461
                    "ISSUER" => $issuingCaPem,
462
                    "ROOT" => $rootCaPem,
463
                ];
464
            default:
465
                /* HTTP POST the CSR to the CA with the $expiryDays as parameter
466
                 * on successful execution, gets back a PEM file which is the
467
                 * certificate (structure TBD)
468
                 * $httpResponse = httpRequest("https://clientca.hosted.eduroam.org/issue/", ["csr" => $csr, "expiry" => $expiryDays ] );
469
                 *
470
                 * The result of this if clause has to be a certificate in PHP's 
471
                 * "openssl_object" style (like the one that openssl_csr_sign would 
472
                 * produce), to be stored in the variable $cert; we also need the
473
                 * serial - which can be extracted from the received cert and has
474
                 * to be stored in $serial.
475
                 */
476
                throw new Exception("External silverbullet CA is not implemented yet!");
477
        }
478
    }
479
480
}
481