Passed
Push — master ( 2bb8d1...bedc70 )
by Stefan
03:11
created

SilverbulletCertificate::generateCsr()   B

Complexity

Conditions 4
Paths 6

Size

Total Lines 33
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 33
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 24
nc 6
nop 3
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
        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 boolean; 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

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