Passed
Push — master ( 7952b7...10cdca )
by Tomasz
03:16
created

SilverbulletCertificate::getBasicInfo()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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