Passed
Branch master (bf41b2)
by Stefan
04:13
created

SilverbulletCertificate   B

Complexity

Total Complexity 36

Size/Duplication

Total Lines 370
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 36
dl 0
loc 370
rs 8.8
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
C triggerNewOCSPStatement() 0 78 10
C __construct() 0 48 8
C issueCertificate() 0 79 7
B generateCsr() 0 33 4
A revokeCertificate() 0 16 2
B signCsr() 0 38 4
A updateFreshness() 0 1 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
26
class SilverbulletCertificate extends EntityWithDBProperties {
27
28
    public $username;
29
    public $expiry;
30
    public $serial;
31
    public $dbId;
32
    public $invitationId;
33
    public $userId;
34
    public $profileId;
35
    public $issued;
36
    public $device;
37
    public $revocationStatus;
38
    public $revocationTime;
39
    public $ocsp;
40
    public $ocspTimestamp;
41
    public $status;
42
43
    const CERTSTATUS_VALID = 1;
44
    const CERTSTATUS_EXPIRED = 2;
45
    const CERTSTATUS_REVOKED = 3;
46
    const CERTSTATUS_INVALID = 4;
47
48
    /**
49
     * instantiates an existing certificate, identified either by its serial
50
     * number or the username. 
51
     * 
52
     * Use static issueCertificate() to generate a whole new cert.
53
     * 
54
     * @param int|string $identifier
55
     */
56
    public function __construct($identifier) {
57
        $this->databaseType = "INST";
58
        parent::__construct();
59
        $this->username = "";
60
        $this->expiry = "2000-01-01 00:00:00";
61
        $this->serial = -1;
62
        $this->dbId = -1;
63
        $this->invitationId = -1;
64
        $this->userId = -1;
65
        $this->profileId = -1;
66
        $this->issued = "2000-01-01 00:00:00";
67
        $this->device = NULL;
68
        $this->revocationStatus = "REVOKED";
69
        $this->revocationTime = "2000-01-01 00:00:00";
70
        $this->ocsp = NULL;
71
        $this->ocspTimestamp = "2000-01-01 00:00:00";
72
        $this->status = SilverbulletCertificate::CERTSTATUS_INVALID;
73
74
        $incoming = FALSE;
75
        if (is_numeric($identifier)) {
76
            $incoming = $this->databaseHandle->exec("SELECT `id`, `profile_id`, `silverbullet_user_id`, `silverbullet_invitation_id`, `serial_number`, `cn` ,`expiry`, `issued`, `device`, `revocation_status`, `revocation_time`, `OCSP`, `OCSP_timestamp` FROM `silverbullet_certificate` WHERE serial_number = ?", "i", $identifier);
77
        } elseif (is_string($identifier)) {
78
            $incoming = $this->databaseHandle->exec("SELECT `id`, `profile_id`, `silverbullet_user_id`, `silverbullet_invitation_id`, `serial_number`, `cn` ,`expiry`, `issued`, `device`, `revocation_status`, `revocation_time`, `OCSP`, `OCSP_timestamp` FROM `silverbullet_certificate` WHERE cn = ?", "s", $identifier);
79
        }
80
        // if no result, foreach doesn't get executed and class members stay as they are
81
        if ($incoming !== FALSE) {
82
            while ($oneResult = mysqli_fetch_object($incoming)) { // there is only at most one
0 ignored issues
show
Bug introduced by
It seems like $incoming can also be of type true; however, parameter $result of mysqli_fetch_object() does only seem to accept mysqli_result, maybe add an additional type check? ( Ignorable by Annotation )

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

82
            while ($oneResult = mysqli_fetch_object(/** @scrutinizer ignore-type */ $incoming)) { // there is only at most one
Loading history...
83
                $this->username = $oneResult->cn;
84
                $this->expiry = $oneResult->expiry;
85
                $this->serial = $oneResult->serial_number;
86
                $this->dbId = $oneResult->id;
87
                $this->invitationId = $oneResult->silverbullet_invitation_id;
88
                $this->userId = $oneResult->silverbullet_user_id;
89
                $this->profileId = $oneResult->profile_id;
90
                $this->issued = $oneResult->issued;
91
                $this->device = $oneResult->device;
92
                $this->revocationStatus = $oneResult->revocation_status;
93
                $this->revocationTime = $oneResult->revocation_time;
94
                $this->ocsp = $oneResult->OCSP;
95
                $this->ocspTimestamp = $oneResult->OCSP_timestamp;
96
                // is the cert expired?
97
                $now = new \DateTime();
98
                $cert_expiry = new \DateTime($this->expiry);
99
                $delta = $now->diff($cert_expiry);
100
                $this->status = ($delta->invert == 1 ? SilverbulletCertificate::CERTSTATUS_EXPIRED : SilverbulletCertificate::CERTSTATUS_VALID);
101
                // expired is expired; even if it was previously revoked. But do update status for revoked ones...
102
                if ($this->status == SilverbulletCertificate::CERTSTATUS_VALID && $this->revocationStatus == "REVOKED") {
103
                    $this->status = SilverbulletCertificate::CERTSTATUS_REVOKED;
104
                }
105
            }
106
        }
107
    }
108
109
    public function updateFreshness() {
110
        // nothing to be done here.
111
    }
112
113
    /**
114
     * issue a certificate based on a token
115
     *
116
     * @param string $token
117
     * @param string $importPassword
118
     * @return array
119
     */
120
    public static function issueCertificate($token, $importPassword) {
121
        $loggerInstance = new common\Logging();
122
        $databaseHandle = DBConnection::handle("INST");
123
        $loggerInstance->debug(5, "generateCertificate() - starting.\n");
124
        $invitationObject = new SilverbulletInvitation($token);
125
        $profile = new ProfileSilverbullet($invitationObject->profile);
126
        $inst = new IdP($profile->institution);
127
        $loggerInstance->debug(5, "tokenStatus: done, got " . $invitationObject->invitationTokenStatus . ", " . $invitationObject->profile . ", " . $invitationObject->userId . ", " . $invitationObject->expiry . ", " . $invitationObject->invitationTokenString . "\n");
128
        if ($invitationObject->invitationTokenStatus != SilverbulletInvitation::SB_TOKENSTATUS_VALID && $invitationObject->invitationTokenStatus != SilverbulletInvitation::SB_TOKENSTATUS_PARTIALLY_REDEEMED) {
129
            throw new Exception("Attempt to generate a SilverBullet installer with an invalid/redeemed/expired token. The user should never have gotten that far!");
130
        }
131
132
        // SQL query to find the expiry date of the *user* to find the correct ValidUntil for the cert
133
        $user = $invitationObject->userId;
134
        $userrow = $databaseHandle->exec("SELECT expiry FROM silverbullet_user WHERE id = ?", "i", $user);
135
        // SELECT -> resource, not boolean
136
        if ($userrow->num_rows != 1) {
137
            throw new Exception("Despite a valid token, the corresponding user was not found in database or database query error!");
138
        }
139
        $expiryObject = mysqli_fetch_object(/** @scrutinizer ignore-type */ $userrow);
140
        $loggerInstance->debug(5, "EXP: " . $expiryObject->expiry . "\n");
141
        $expiryDateObject = date_create_from_format("Y-m-d H:i:s", $expiryObject->expiry);
142
        if ($expiryDateObject === FALSE) {
143
            throw new Exception("The expiry date we got from the DB is bogus!");
144
        }
145
        $loggerInstance->debug(5, $expiryDateObject->format("Y-m-d H:i:s") . "\n");
146
        // date_create with no parameters can't fail, i.e. is never FALSE
147
        $validity = date_diff(/** @scrutinizer ignore-type */ date_create(), $expiryDateObject);
148
        $expiryDays = $validity->days + 1;
149
        if ($validity->invert == 1) { // negative! That should not be possible
150
            throw new Exception("Attempt to generate a certificate for a user which is already expired!");
151
        }
152
153
        $privateKey = openssl_pkey_new(['private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA, 'encrypt_key' => FALSE]);
154
155
        $csr = SilverbulletCertificate::generateCsr($privateKey, strtoupper($inst->federation), $profile->getAttributes("internal:realm")[0]['value']);
156
157
        $loggerInstance->debug(5, "generateCertificate: proceeding to sign cert.\n");
158
159
        $certMeta = SilverbulletCertificate::signCsr($csr["CSR"], $expiryDays);
160
        $cert = $certMeta["CERT"];
161
        $issuingCaPem = $certMeta["ISSUER"];
162
        $rootCaPem = $certMeta["ROOT"];
163
        $serial = $certMeta["SERIAL"];
164
165
        $loggerInstance->debug(5, "generateCertificate: post-processing certificate.\n");
166
167
        // get the SHA1 fingerprint, this will be handy for Windows installers
168
        $sha1 = openssl_x509_fingerprint($cert, "sha1");
169
        // with the cert, our private key and import password, make a PKCS#12 container out of it
170
        $exportedCertProt = "";
171
        openssl_pkcs12_export($cert, $exportedCertProt, $privateKey, $importPassword, ['extracerts' => [$issuingCaPem /* , $rootCaPem */]]);
172
        $exportedCertClear = "";
173
        openssl_pkcs12_export($cert, $exportedCertClear, $privateKey, "", ['extracerts' => [$issuingCaPem, $rootCaPem]]);
174
        // 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!
175
        // we need the *real* expiry date, not just the day-approximation
176
        $x509 = new \core\common\X509();
177
        $certString = "";
178
        openssl_x509_export($cert, $certString);
179
        $parsedCert = $x509->processCertificate($certString);
180
        $loggerInstance->debug(5, "CERTINFO: " . print_r($parsedCert['full_details'], true));
181
        $realExpiryDate = date_create_from_format("U", $parsedCert['full_details']['validTo_time_t'])->format("Y-m-d H:i:s");
182
183
        // store new cert info in DB
184
        $newCertificateResult = $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);
185
        if ($newCertificateResult === false) {
186
            throw new Exception("Unable to update database with new cert details!");
187
        }
188
        // newborn cert immediately gets its "valid" OCSP response
189
        $certObject = new SilverbulletCertificate($serial);
190
        $certObject->triggerNewOCSPStatement();
191
// return PKCS#12 data stream
192
        return [
193
            "certObject" => $certObject,
194
            "certdata" => $exportedCertProt,
195
            "certdataclear" => $exportedCertClear,
196
            "sha1" => $sha1,
197
            'importPassword' => $importPassword,
198
            'GUID' => common\Entity::uuid("", $exportedCertProt),
199
        ];
200
    }
201
202
    /**
203
     * triggers a new OCSP statement for the given serial number
204
     * 
205
     * @return string DER-encoded OCSP status info (binary data!)
206
     */
207
    public function triggerNewOCSPStatement() {
208
        $logHandle = new \core\common\Logging();
209
        $logHandle->debug(2, "Triggering new OCSP statement for serial $this->serial.\n");
210
        switch (CONFIG_CONFASSISTANT['SILVERBULLET']['CA']['type']) {
211
            case "embedded":
212
                $certstatus = "";
213
                // get all relevant info from object properties
214
                if ($this->serial >= 0) { // let's start with the assumption that the cert is valid
215
                    if ($this->revocationStatus == "REVOKED") {
216
                        // already revoked, simply return canned OCSP response
217
                        $certstatus = "R";
218
                    } else {
219
                        $certstatus = "V";
220
                    }
221
                }
222
223
                $originalExpiry = date_create_from_format("Y-m-d H:i:s", $this->expiry);
224
                if ($originalExpiry === FALSE) {
225
                    throw new Exception("Unable to calculate original expiry date, input data bogus!");
226
                }
227
                $validity = date_diff(/** @scrutinizer ignore-type */ date_create(), $originalExpiry);
228
                if ($validity->invert == 1) {
229
                    // negative! Cert is already expired, no need to revoke. 
230
                    // No need to return anything really, but do return the last known OCSP statement to prevent special case
231
                    $certstatus = "E";
232
                }
233
                $profile = new ProfileSilverbullet($this->profileId);
234
                $inst = new IdP($profile->institution);
235
                $federation = strtoupper($inst->federation);
236
                // generate stub index.txt file
237
                $cat = new CAT();
238
                $tempdirArray = $cat->createTemporaryDirectory("test");
239
                $tempdir = $tempdirArray['dir'];
240
                $nowIndexTxt = (new \DateTime())->format("ymdHis") . "Z";
241
                $expiryIndexTxt = $originalExpiry->format("ymdHis") . "Z";
242
                $serialHex = strtoupper(dechex($this->serial));
243
                if (strlen($serialHex) % 2 == 1) {
244
                    $serialHex = "0" . $serialHex;
245
                }
246
247
                $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";
248
                $logHandle->debug(4, "index.txt contents-to-be: $indexStatement");
249
                if (!file_put_contents($tempdir . "/index.txt", $indexStatement)) {
250
                    $logHandle->debug(1, "Unable to write openssl index.txt file for revocation handling!");
251
                }
252
                // index.txt.attr is dull but needs to exist
253
                file_put_contents($tempdir . "/index.txt.attr", "unique_subject = yes\n");
254
                // call "openssl ocsp" to manufacture our own OCSP statement
255
                // adding "-rmd sha1" to the following command-line makes the
256
                // choice of signature algorithm for the response explicit
257
                // but it's only available from openssl-1.1.0 (which we do not
258
                // want to require just for that one thing).
259
                $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";
260
                $logHandle->debug(2, "Calling openssl ocsp with following cmdline: $execCmd\n");
261
                $output = [];
262
                $return = 999;
263
                exec($execCmd, $output, $return);
264
                if ($return !== 0) {
1 ignored issue
show
introduced by
The condition $return !== 0 can never be false.
Loading history...
265
                    throw new Exception("Non-zero return value from openssl ocsp!");
266
                }
267
                $ocspFile = fopen($tempdir . "/$serialHex.response.der", "r");
268
                $ocsp = fread($ocspFile, 1000000);
269
                fclose($ocspFile);
270
                break;
271
            default:
272
                /* HTTP POST the serial to the CA. The CA knows about the state of
273
                 * the certificate.
274
                 *
275
                 * $httpResponse = httpRequest("https://clientca.hosted.eduroam.org/ocsp/", ["serial" => $serial ] );
276
                 *
277
                 * The result of this if clause has to be a DER-encoded OCSP statement
278
                 * to be stored in the variable $ocsp
279
                 */
280
                throw new Exception("External silverbullet CA is not implemented yet!");
281
        }
282
        // write the new statement into DB
283
        $this->databaseHandle->exec("UPDATE silverbullet_certificate SET OCSP = ?, OCSP_timestamp = NOW() WHERE serial_number = ?", "si", $ocsp, $this->serial);
284
        return $ocsp;
285
    }
286
287
    /**
288
     * revokes a certificate
289
     * @return array with revocation information
290
     */
291
    public function revokeCertificate() {
292
293
294
// TODO for now, just mark as revoked in the certificates table (and use the stub OCSP updater)
295
        $nowSql = (new \DateTime())->format("Y-m-d H:i:s");
296
        if (CONFIG_CONFASSISTANT['SILVERBULLET']['CA']['type'] != "embedded") {
297
            // send revocation request to CA.
298
            // $httpResponse = httpRequest("https://clientca.hosted.eduroam.org/revoke/", ["serial" => $serial ] );
299
            throw new Exception("External silverbullet CA is not implemented yet!");
300
        }
301
        // regardless if embedded or not, always keep local state in our own DB
302
        $this->databaseHandle->exec("UPDATE silverbullet_certificate SET revocation_status = 'REVOKED', revocation_time = ? WHERE serial_number = ?", "si", $nowSql, $this->serial);
303
        $this->loggerInstance->debug(2, "Certificate revocation status for $this->serial updated, about to call triggerNewOCSPStatement().\n");
304
        // newly instantiate us, DB content has changed...
305
        $certObject = new SilverbulletCertificate($this->serial);
306
        $certObject->triggerNewOCSPStatement();
307
    }
308
309
    /**
310
     * create a CSR
311
     * 
312
     * @param resource $privateKey the private key to create the CSR with
313
     * @return array with the CSR and some meta info
314
     */
315
    private static function generateCsr($privateKey, $fed, $realm) {
316
        $databaseHandle = DBConnection::handle("INST");
317
        $loggerInstance = new common\Logging();
318
        $usernameIsUnique = FALSE;
319
        $username = "";
320
        while ($usernameIsUnique === FALSE) {
1 ignored issue
show
introduced by
The condition $usernameIsUnique === FALSE can never be false.
Loading history...
321
            $usernameLocalPart = common\Entity::randomString(64 - 1 - strlen($realm), "0123456789abcdefghijklmnopqrstuvwxyz");
322
            $username = $usernameLocalPart . "@" . $realm;
323
            $uniquenessQuery = $databaseHandle->exec("SELECT cn from silverbullet_certificate WHERE cn = ?", "s", $username);
324
            // SELECT -> resource, not boolean
325
            if (mysqli_num_rows(/** @scrutinizer ignore-type */ $uniquenessQuery) == 0) {
326
                $usernameIsUnique = TRUE;
327
            }
328
        }
329
330
        $loggerInstance->debug(5, "generateCertificate: generating private key.\n");
331
332
        $newCsr = openssl_csr_new(
333
                ['O' => CONFIG_CONFASSISTANT['CONSORTIUM']['name'],
334
            'OU' => $fed,
335
            'CN' => $username,
336
            'emailAddress' => $username,
337
                ], $privateKey, [
338
            'digest_alg' => 'sha256',
339
            'req_extensions' => 'v3_req',
340
                ]
341
        );
342
        if ($newCsr === FALSE) {
343
            throw new Exception("Unable to create a CSR!");
344
        }
345
        return [
346
            "CSR" => $newCsr,
347
            "USERNAME" => $username
348
        ];
349
    }
350
351
    /**
352
     * take a CSR and sign it with our issuing CA's certificate
353
     * 
354
     * @param mixed $csr the CSR
355
     * @param int $expiryDays the number of days until the cert is going to expire
356
     * @return array the cert and some meta info
357
     */
358
    private static function signCsr($csr, $expiryDays) {
359
        $loggerInstance = new common\Logging();
360
        $databaseHandle = DBConnection::handle("INST");
361
        switch (CONFIG_CONFASSISTANT['SILVERBULLET']['CA']['type']) {
362
            case "embedded":
363
                $rootCaPem = file_get_contents(ROOT . "/config/SilverbulletClientCerts/rootca.pem");
364
                $issuingCaPem = file_get_contents(ROOT . "/config/SilverbulletClientCerts/real.pem");
365
                $issuingCa = openssl_x509_read($issuingCaPem);
366
                $issuingCaKey = openssl_pkey_get_private("file://" . ROOT . "/config/SilverbulletClientCerts/real.key");
367
                $nonDupSerialFound = FALSE;
368
                do {
369
                    $serial = random_int(1000000000, PHP_INT_MAX);
370
                    $dupeQuery = $databaseHandle->exec("SELECT serial_number FROM silverbullet_certificate WHERE serial_number = ?", "i", $serial);
371
                    // SELECT -> resource, not boolean
372
                    if (mysqli_num_rows(/** @scrutinizer ignore-type */$dupeQuery) == 0) {
373
                        $nonDupSerialFound = TRUE;
374
                    }
375
                } while (!$nonDupSerialFound);
376
                $loggerInstance->debug(5, "generateCertificate: signing imminent with unique serial $serial.\n");
377
                return [
378
                    "CERT" => openssl_csr_sign($csr, $issuingCa, $issuingCaKey, $expiryDays, ['digest_alg' => 'sha256'], $serial),
379
                    "SERIAL" => $serial,
380
                    "ISSUER" => $issuingCaPem,
381
                    "ROOT" => $rootCaPem,
382
                ];
383
            default:
384
                /* HTTP POST the CSR to the CA with the $expiryDays as parameter
385
                 * on successful execution, gets back a PEM file which is the
386
                 * certificate (structure TBD)
387
                 * $httpResponse = httpRequest("https://clientca.hosted.eduroam.org/issue/", ["csr" => $csr, "expiry" => $expiryDays ] );
388
                 *
389
                 * The result of this if clause has to be a certificate in PHP's 
390
                 * "openssl_object" style (like the one that openssl_csr_sign would 
391
                 * produce), to be stored in the variable $cert; we also need the
392
                 * serial - which can be extracted from the received cert and has
393
                 * to be stored in $serial.
394
                 */
395
                throw new Exception("External silverbullet CA is not implemented yet!");
396
        }
397
    }
398
399
}
400