Passed
Push — master ( 0adbbf...5c1c26 )
by Stefan
04:55
created

ProfileSilverbullet::randomString()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 9
nc 3
nop 2
dl 0
loc 13
rs 9.4285
c 0
b 0
f 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 ProfileSilverbullet 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
/**
27
 * Silverbullet (marketed as "Managed IdP") is a RADIUS profile which 
28
 * corresponds directly to a built-in RADIUS server and CA. 
29
 * It provides all functions needed for a admin-side web interface where users
30
 * can be added and removed, and new devices be enabled.
31
 * 
32
 * When downloading a Silverbullet based profile, the profile includes per-user
33
 * per-device client certificates which can be immediately used to log into 
34
 * eduroam.
35
 *
36
 * @author Stefan Winter <[email protected]>
37
 * @author Tomasz Wolniewicz <[email protected]>
38
 *
39
 * @license see LICENSE file in root directory
40
 *
41
 * @package Developer
42
 */
43
class ProfileSilverbullet extends AbstractProfile {
44
45
    const SB_CERTSTATUS_VALID = 1;
46
    const SB_CERTSTATUS_EXPIRED = 2;
47
    const SB_CERTSTATUS_REVOKED = 3;
48
    const SB_ACKNOWLEDGEMENT_REQUIRED_DAYS = 365;
49
50
    public $termsAndConditions;
51
52
    /*
53
     * 
54
     */
55
56
    const PRODUCTNAME = "Managed IdP";
57
58
    /**
59
     * produces a random string
60
     * @param int $length the length of the string to produce
61
     * @param string $keyspace the pool of characters to use for producing the string
62
     * @return string
63
     * @throws Exception
64
     */
65
    public static function randomString(
66
    $length, $keyspace = '23456789abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
67
    ) {
68
        $str = '';
69
        $max = strlen($keyspace) - 1;
70
        if ($max < 1) {
71
            throw new Exception('$keyspace must be at least two characters long');
72
        }
73
        for ($i = 0; $i < $length; ++$i) {
74
            $str .= $keyspace[random_int(0, $max)];
75
        }
76
        return $str;
77
    }
78
79
    /**
80
     * Class constructor for existing profiles (use IdP::newProfile() to actually create one). Retrieves all attributes and 
81
     * supported EAP types from the DB and stores them in the priv_ arrays.
82
     * 
83
     * @param int $profileId identifier of the profile in the DB
84
     * @param IdP $idpObject optionally, the institution to which this Profile belongs. Saves the construction of the IdP instance. If omitted, an extra query and instantiation is executed to find out.
85
     */
86
    public function __construct($profileId, $idpObject = NULL) {
87
        parent::__construct($profileId, $idpObject);
88
89
        $this->entityOptionTable = "profile_option";
90
        $this->entityIdColumn = "profile_id";
91
        $this->attributes = [];
92
93
        $tempMaxUsers = 200; // abolutely last resort fallback if no per-fed and no config option
94
// set to global config value
95
96
        if (isset(CONFIG_CONFASSISTANT['SILVERBULLET']['default_maxusers'])) {
97
            $tempMaxUsers = CONFIG_CONFASSISTANT['SILVERBULLET']['default_maxusers'];
98
        }
99
        $myInst = new IdP($this->institution);
100
        $myFed = new Federation($myInst->federation);
101
        $fedMaxusers = $myFed->getAttributes("fed:silverbullet-maxusers");
102
        if (isset($fedMaxusers[0])) {
103
            $tempMaxUsers = $fedMaxusers[0]['value'];
104
        }
105
106
// realm is automatically calculated, then stored in DB
107
108
        $this->realm = "opaquehash@$myInst->identifier-$this->identifier." . strtolower($myInst->federation) . CONFIG_CONFASSISTANT['SILVERBULLET']['realm_suffix'];
109
        $localValueIfAny = "";
110
111
// but there's some common internal attributes populated directly
112
        $internalAttributes = [
113
            "internal:profile_count" => $this->idpNumberOfProfiles,
114
            "internal:realm" => preg_replace('/^.*@/', '', $this->realm),
115
            "internal:use_anon_outer" => FALSE,
116
            "internal:checkuser_outer" => TRUE,
117
            "internal:checkuser_value" => "anonymous",
118
            "internal:anon_local_value" => $localValueIfAny,
119
            "internal:silverbullet_maxusers" => $tempMaxUsers,
120
            "profile:production" => "on",
121
        ];
122
123
// and we need to populate eap:server_name and eap:ca_file with the NRO-specific EAP information
124
        $silverbulletAttributes = [
125
            "eap:server_name" => "auth." . strtolower($myFed->tld) . CONFIG_CONFASSISTANT['SILVERBULLET']['server_suffix'],
126
        ];
127
        $x509 = new \core\common\X509();
128
        $caHandle = fopen(dirname(__FILE__) . "/../config/SilverbulletServerCerts/" . strtoupper($myFed->tld) . "/root.pem", "r");
129
        if ($caHandle !== FALSE) {
130
            $cAFile = fread($caHandle, 16000000);
131
            $silverbulletAttributes["eap:ca_file"] = $x509->der2pem(($x509->pem2der($cAFile)));
132
        }
133
134
        $temp = array_merge($this->addInternalAttributes($internalAttributes), $this->addInternalAttributes($silverbulletAttributes));
135
        $tempArrayProfLevel = array_merge($this->addDatabaseAttributes(), $temp);
136
137
// now, fetch and merge IdP-wide attributes
138
139
        $this->attributes = $this->levelPrecedenceAttributeJoin($tempArrayProfLevel, $this->idpAttributes, "IdP");
140
141
        $this->privEaptypes = $this->fetchEAPMethods();
142
143
        $this->name = ProfileSilverbullet::PRODUCTNAME;
144
145
        $this->loggerInstance->debug(3, "--- END Constructing new Profile object ... ---\n");
146
147
        $this->termsAndConditions = "<h2>Product Definition</h2>
148
        <p>" . \core\ProfileSilverbullet::PRODUCTNAME . " outsources the technical setup of " . CONFIG_CONFASSISTANT['CONSORTIUM']['display_name'] . " " . CONFIG_CONFASSISTANT['CONSORTIUM']['nomenclature_institution'] . " functions to the " . CONFIG_CONFASSISTANT['CONSORTIUM']['display_name'] . " Operations Team. The system includes</p>
149
            <ul>
150
                <li>a web-based user management interface where user accounts and access credentials can be created and revoked (there is a limit to the number of active users)</li>
151
                <li>a technical infrastructure ('CA') which issues and revokes credentials</li>
152
                <li>a technical infrastructure ('RADIUS') which verifies access credentials and subsequently grants access to " . CONFIG_CONFASSISTANT['CONSORTIUM']['display_name'] . "</li>
153
                <li><span style='color: red;'>TBD: a lookup/notification system which informs you of network abuse complaints by " . CONFIG_CONFASSISTANT['CONSORTIUM']['display_name'] . " Service Providers that pertain to your users</span></li>
154
            </ul>
155
        <h2>User Account Liability</h2>
156
        <p>As an " . CONFIG_CONFASSISTANT['CONSORTIUM']['display_name'] . " " . CONFIG_CONFASSISTANT['CONSORTIUM']['nomenclature_institution'] . " administrator using this system, you are authorized to create user accounts according to your local " . CONFIG_CONFASSISTANT['CONSORTIUM']['nomenclature_institution'] . " policy. You are fully responsible for the accounts you issue and are the data controller for all user information you deposit in this system; the system is a data processor.</p>";
157
        $this->termsAndConditions .= "<p>Your responsibilities include that you</p>
158
        <ul>
159
            <li>only issue accounts to members of your " . CONFIG_CONFASSISTANT['CONSORTIUM']['nomenclature_institution'] . ", as defined by your local policy.</li>
160
            <li>must make sure that all accounts that you issue can be linked by you to actual human end users</li>
161
            <li>have to immediately revoke accounts of users when they leave or otherwise stop being a member of your " . CONFIG_CONFASSISTANT['CONSORTIUM']['nomenclature_institution'] . "</li>
162
            <li>will act upon notifications about possible network abuse by your users and will appropriately sanction them</li>
163
        </ul>
164
        <p>";
165
        $this->termsAndConditions .= "Failure to comply with these requirements may make your " . CONFIG_CONFASSISTANT['CONSORTIUM']['nomenclature_federation'] . " act on your behalf, which you authorise, and will ultimately lead to the deletion of your " . CONFIG_CONFASSISTANT['CONSORTIUM']['nomenclature_institution'] . " (and all the users you create inside) in this system.";
166
        $this->termsAndConditions .= "</p>
167
        <h2>Privacy</h2>
168
        <p>With " . \core\ProfileSilverbullet::PRODUCTNAME . ", we are necessarily storing personally identifiable information about the end users you create. While the actual human is only identifiable with your help, we consider all the user data as relevant in terms of privacy jurisdiction. Please note that</p>
169
        <ul>
170
            <li>You are the only one who needs to be able to make a link to the human behind the usernames you create. The usernames you create in the system have to be rich enough to allow you to make that identification step. Also consider situations when you are unavailable or leave the organisation and someone else needs to perform the matching to an individual.</li>
171
            <li>The identifiers we create in the credentials are not linked to the usernames you add to the system; they are randomly generated pseudonyms.</li>
172
            <li>Each access credential carries a different pseudonym, even if it pertains to the same username.</li>
173
            <li>If you choose to deposit users' email addresses in the system, you authorise the system to send emails on your behalf regarding operationally relevant events to the users in question (e.g. notification of nearing expiry dates of credentials, notification of access revocation).
174
        </ul>";
175
    }
176
    
177
    /**
178
     * Updates database with new installer location; NOOP because we do not
179
     * cache anything in Silverbullet
180
     * 
181
     * @param string $device the device identifier string
182
     * @param string $path the path where the new installer can be found
183
     * @param string $mime the mime type of the new installer
184
     * @param int $integerEapType the inter-representation of the EAP type that is configured in this installer
185
     */
186
    public function updateCache($device, $path, $mime, $integerEapType) {
187
        // caching is not supported in SB (private key in installers)
188
        // the following merely makes the "unused parameter" warnings go away
189
        // the FALSE in condition one makes sure it never gets executed
190
        if (FALSE || $device == "Macbeth" || $path == "heath" || $mime == "application/witchcraft" || $integerEapType == 0) {
191
            throw new Exception("FALSE is TRUE, and TRUE is FALSE! Hover through the browser and filthy code!");
192
        }
193
    }
194
195
    /**
196
     * register new supported EAP method for this profile
197
     *
198
     * @param \core\common\EAP $type The EAP Type, as defined in class EAP
199
     * @param int $preference preference of this EAP Type. If a preference value is re-used, the order of EAP types of the same preference level is undefined.
200
     *
201
     */
202
    public function addSupportedEapMethod(\core\common\EAP $type, $preference) {
203
        // the parameters really should only list SB and with prio 1 - otherwise,
204
        // something fishy is going on
205
        if ($type->getIntegerRep() != \core\common\EAP::INTEGER_SILVERBULLET || $preference != 1) {
206
            throw new Exception("Silverbullet::addSupportedEapMethod was called for a non-SP EAP type or unexpected priority!");
207
        }
208
        parent::addSupportedEapMethod($type, 1);
209
    }
210
211
    /**
212
     * It's EAP-TLS and there is no point in anonymity
213
     * @param boolean $shallwe
214
     */
215
    public function setAnonymousIDSupport($shallwe) {
216
        // we don't do anonymous outer IDs in SB
217
        if ($shallwe === TRUE) {
218
            throw new Exception("Silverbullet: attempt to add anonymous outer ID support to a SB profile!");
219
        }
220
        $this->databaseHandle->exec("UPDATE profile SET use_anon_outer = 0 WHERE profile_id = $this->identifier");
221
    }
222
223
    /**
224
     * create a CSR
225
     * 
226
     * @param resource $privateKey the private key to create the CSR with
227
     * @return array with the CSR and some meta info
228
     */
229
    private function generateCsr($privateKey) {
230
        // token leads us to the NRO, to set the OU property of the cert
231
        $inst = new IdP($this->institution);
232
        $federation = strtoupper($inst->federation);
233
        $usernameIsUnique = FALSE;
234
        $username = "";
235
        while ($usernameIsUnique === FALSE) {
236
            $usernameLocalPart = self::randomString(64 - 1 - strlen($this->realm), "0123456789abcdefghijklmnopqrstuvwxyz");
237
            $username = $usernameLocalPart . "@" . $this->realm;
238
            $uniquenessQuery = $this->databaseHandle->exec("SELECT cn from silverbullet_certificate WHERE cn = ?", "s", $username);
239
            // SELECT -> resource, not boolean
240
            if (mysqli_num_rows(/** @scrutinizer ignore-type */ $uniquenessQuery) == 0) {
241
                $usernameIsUnique = TRUE;
242
            }
243
        }
244
245
        $this->loggerInstance->debug(5, "generateCertificate: generating private key.\n");
246
247
        $newCsr = openssl_csr_new(
248
                    ['O' => CONFIG_CONFASSISTANT['CONSORTIUM']['name'],
249
                'OU' => $federation,
250
                'CN' => $username,
251
                'emailAddress' => $username,
252
                    ], $privateKey, [
253
                'digest_alg' => 'sha256',
254
                'req_extensions' => 'v3_req',
255
                    ]
256
            );
257
        if ($newCsr === FALSE) {
258
            throw new Exception("Unable to create a CSR!");
259
        }
260
        return [
261
            "CSR" => $newCsr,
262
            "USERNAME" => $username
263
        ];
264
    }
265
266
    /**
267
     * take a CSR and sign it with our issuing CA's certificate
268
     * 
269
     * @param mixed $csr the CSR
270
     * @param int $expiryDays the number of days until the cert is going to expire
271
     * @return array the cert and some meta info
272
     */
273
    private function signCsr($csr, $expiryDays) {
274
        switch (CONFIG_CONFASSISTANT['SILVERBULLET']['CA']['type']) {
275
            case "embedded":
276
                $rootCaPem = file_get_contents(ROOT . "/config/SilverbulletClientCerts/rootca.pem");
277
                $issuingCaPem = file_get_contents(ROOT . "/config/SilverbulletClientCerts/real.pem");
278
                $issuingCa = openssl_x509_read($issuingCaPem);
279
                $issuingCaKey = openssl_pkey_get_private("file://" . ROOT . "/config/SilverbulletClientCerts/real.key");
280
                $nonDupSerialFound = FALSE;
281
                do {
282
                    $serial = random_int(1000000000, PHP_INT_MAX);
283
                    $dupeQuery = $this->databaseHandle->exec("SELECT serial_number FROM silverbullet_certificate WHERE serial_number = ?", "i", $serial);
284
                    // SELECT -> resource, not boolean
285
                    if (mysqli_num_rows(/** @scrutinizer ignore-type */$dupeQuery) == 0) {
286
                        $nonDupSerialFound = TRUE;
287
                    }
288
                } while (!$nonDupSerialFound);
289
                $this->loggerInstance->debug(5, "generateCertificate: signing imminent with unique serial $serial.\n");
290
                return [
291
                    "CERT" => openssl_csr_sign($csr, $issuingCa, $issuingCaKey, $expiryDays, ['digest_alg' => 'sha256'], $serial),
292
                    "SERIAL" => $serial,
293
                    "ISSUER" => $issuingCaPem,
294
                    "ROOT" => $rootCaPem,
295
                ];
296
            default:
297
                /* HTTP POST the CSR to the CA with the $expiryDays as parameter
298
                 * on successful execution, gets back a PEM file which is the
299
                 * certificate (structure TBD)
300
                 * $httpResponse = httpRequest("https://clientca.hosted.eduroam.org/issue/", ["csr" => $csr, "expiry" => $expiryDays ] );
301
                 *
302
                 * The result of this if clause has to be a certificate in PHP's 
303
                 * "openssl_object" style (like the one that openssl_csr_sign would 
304
                 * produce), to be stored in the variable $cert; we also need the
305
                 * serial - which can be extracted from the received cert and has
306
                 * to be stored in $serial.
307
                 */
308
                throw new Exception("External silverbullet CA is not implemented yet!");
309
        }
310
    }
311
312
    /**
313
     * issue a certificate based on a token
314
     *
315
     * @param string $token
316
     * @param string $importPassword
317
     * @return array
318
     */
319
    public function issueCertificate($token, $importPassword) {
320
        $this->loggerInstance->debug(5, "generateCertificate() - starting.\n");
321
        $invitationObject = new SilverbulletInvitation($token);
322
        $this->loggerInstance->debug(5, "tokenStatus: done, got " . $invitationObject->invitationTokenStatus . ", " . $invitationObject->profile . ", " . $invitationObject->userId . ", " . $invitationObject->invitationTokenExpiry . ", " . $invitationObject->invitationTokenString . "\n");
323
        if ($invitationObject->invitationTokenStatus != SilverbulletInvitation::SB_TOKENSTATUS_VALID && $invitationObject->invitationTokenStatus != SilverbulletInvitation::SB_TOKENSTATUS_PARTIALLY_REDEEMED) {
324
            throw new Exception("Attempt to generate a SilverBullet installer with an invalid/redeemed/expired token. The user should never have gotten that far!");
325
        }
326
        if ($invitationObject->profile != $this->identifier) {
327
            throw new Exception("Attempt to generate a SilverBullet installer, but the profile ID (constructor) and the profile from token do not match!");
328
        }
329
        // SQL query to find the expiry date of the *user* to find the correct ValidUntil for the cert
330
        $user = $invitationObject->userId;
331
        $userrow = $this->databaseHandle->exec("SELECT expiry FROM silverbullet_user WHERE id = ?", "i", $user);
332
        // SELECT -> resource, not boolean
333
        if ($userrow->num_rows != 1) {
334
            throw new Exception("Despite a valid token, the corresponding user was not found in database or database query error!");
335
        }
336
        $expiryObject = mysqli_fetch_object(/** @scrutinizer ignore-type */ $userrow);
337
        $this->loggerInstance->debug(5, "EXP: " . $expiryObject->expiry . "\n");
338
        $expiryDateObject = date_create_from_format("Y-m-d H:i:s", $expiryObject->expiry);
339
        if ($expiryDateObject === FALSE) {
340
            throw new Exception("The expiry date we got from the DB is bogus!");
341
        }
342
        $this->loggerInstance->debug(5, $expiryDateObject->format("Y-m-d H:i:s") . "\n");
343
        // date_create with no parameters can't fail, i.e. is never FALSE
344
        $validity = date_diff(/** @scrutinizer ignore-type */ date_create(), $expiryDateObject);
345
        $expiryDays = $validity->days + 1;
346
        if ($validity->invert == 1) { // negative! That should not be possible
347
            throw new Exception("Attempt to generate a certificate for a user which is already expired!");
348
        }
349
350
        $privateKey = openssl_pkey_new(['private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA, 'encrypt_key' => FALSE]);
351
        $csr = $this->generateCsr($privateKey);
352
353
        $this->loggerInstance->debug(5, "generateCertificate: proceeding to sign cert.\n");
354
355
        $certMeta = $this->signCsr($csr["CSR"], $expiryDays);
356
        $cert = $certMeta["CERT"];
357
        $issuingCaPem = $certMeta["ISSUER"];
358
        $rootCaPem = $certMeta["ROOT"];
359
        $serial = $certMeta["SERIAL"];
360
361
        $this->loggerInstance->debug(5, "generateCertificate: post-processing certificate.\n");
362
363
        // get the SHA1 fingerprint, this will be handy for Windows installers
364
        $sha1 = openssl_x509_fingerprint($cert, "sha1");
365
        // with the cert, our private key and import password, make a PKCS#12 container out of it
366
        $exportedCertProt = "";
367
        openssl_pkcs12_export($cert, $exportedCertProt, $privateKey, $importPassword, ['extracerts' => [$issuingCaPem /* , $rootCaPem */]]);
368
        $exportedCertClear = "";
369
        openssl_pkcs12_export($cert, $exportedCertClear, $privateKey, "", ['extracerts' => [$issuingCaPem, $rootCaPem]]);
370
        // 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!
371
        // we need the *real* expiry date, not just the day-approximation
372
        $x509 = new \core\common\X509();
373
        $certString = "";
374
        openssl_x509_export($cert, $certString);
375
        $parsedCert = $x509->processCertificate($certString);
376
        $this->loggerInstance->debug(5, "CERTINFO: " . print_r($parsedCert['full_details'], true));
377
        $realExpiryDate = date_create_from_format("U", $parsedCert['full_details']['validTo_time_t'])->format("Y-m-d H:i:s");
378
379
        // store new cert info in DB
380
        $newCertificateResult = $this->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);
381
        if ($newCertificateResult === false) {
382
            throw new Exception("Unable to update database with new cert details!");
383
        }
384
        $certificateId = $this->databaseHandle->lastID();
385
386
        // newborn cert immediately gets its "valid" OCSP response
387
        ProfileSilverbullet::triggerNewOCSPStatement((int) $serial);
388
// return PKCS#12 data stream
389
        return [
390
            "username" => $csr["USERNAME"],
391
            "certdata" => $exportedCertProt,
392
            "certdataclear" => $exportedCertClear,
393
            "expiry" => $expiryDateObject->format("Y-m-d\TH:i:s\Z"),
394
            "sha1" => $sha1,
395
            'importPassword' => $importPassword,
396
            'serial' => $serial,
397
            'certificateId' => $certificateId,
398
        ];
399
    }
400
401
    /**
402
     * triggers a new OCSP statement for the given serial number
403
     * 
404
     * @param int $serial the serial number of the cert in question (decimal)
405
     * @return string DER-encoded OCSP status info (binary data!)
406
     */
407
    public static function triggerNewOCSPStatement($serial) {
408
        $logHandle = new \core\common\Logging();
409
        $logHandle->debug(2, "Triggering new OCSP statement for serial $serial.\n");
410
        switch (CONFIG_CONFASSISTANT['SILVERBULLET']['CA']['type']) {
411
            case "embedded":
412
                // get all relevant info from DB
413
                $cn = "";
414
                $federation = NULL;
415
                $certstatus = "";
416
                $originalExpiry = date_create_from_format("Y-m-d H:i:s", "2000-01-01 00:00:00");
417
                $dbHandle = DBConnection::handle("INST");
418
                $originalStatusQuery = $dbHandle->exec("SELECT profile_id, cn, revocation_status, expiry, revocation_time, OCSP FROM silverbullet_certificate WHERE serial_number = ?", "i", $serial);
419
                // SELECT -> resource, not boolean
420
                if (mysqli_num_rows(/** @scrutinizer ignore-type */ $originalStatusQuery) > 0) {
421
                    $certstatus = "V";
422
                }
423
                while ($runner = mysqli_fetch_object(/** @scrutinizer ignore-type */ $originalStatusQuery)) { // there can be only one row
424
                    if ($runner->revocation_status == "REVOKED") {
425
                        // already revoked, simply return canned OCSP response
426
                        $certstatus = "R";
427
                    }
428
                    $originalExpiry = date_create_from_format("Y-m-d H:i:s", $runner->expiry);
429
                    if ($originalExpiry === FALSE) {
430
                        throw new Exception("Unable to calculate original expiry date, input data bogus!");
431
                    }
432
                    $validity = date_diff(/** @scrutinizer ignore-type */ date_create(), $originalExpiry);
433
                    if ($validity->invert == 1) {
434
                        // negative! Cert is already expired, no need to revoke. 
435
                        // No need to return anything really, but do return the last known OCSP statement to prevent special case
436
                        $certstatus = "E";
437
                    }
438
                    $cn = $runner->cn;
439
                    $profile = new ProfileSilverbullet($runner->profile_id);
440
                    $inst = new IdP($profile->institution);
441
                    $federation = strtoupper($inst->federation);
442
                }
443
444
                // generate stub index.txt file
445
                $cat = new CAT();
446
                $tempdirArray = $cat->createTemporaryDirectory("test");
447
                $tempdir = $tempdirArray['dir'];
448
                $nowIndexTxt = (new \DateTime())->format("ymdHis") . "Z";
449
                $expiryIndexTxt = $originalExpiry->format("ymdHis") . "Z";
450
                $serialHex = strtoupper(dechex($serial));
451
                if (strlen($serialHex) % 2 == 1) {
452
                    $serialHex = "0" . $serialHex;
453
                }
454
                
455
                $indexStatement = "$certstatus\t$expiryIndexTxt\t" . ($certstatus == "R" ? "$nowIndexTxt,unspecified" : "") . "\t$serialHex\tunknown\t/O=" . CONFIG_CONFASSISTANT['CONSORTIUM']['name'] . "/OU=$federation/CN=$cn/emailAddress=$cn\n";
456
                $logHandle->debug(4, "index.txt contents-to-be: $indexStatement");
457
                if (!file_put_contents($tempdir . "/index.txt", $indexStatement)) {
458
                $logHandle->debug(1,"Unable to write openssl index.txt file for revocation handling!");
459
                }
460
                // index.txt.attr is dull but needs to exist
461
                file_put_contents($tempdir . "/index.txt.attr", "unique_subject = yes\n");
462
                // call "openssl ocsp" to manufacture our own OCSP statement
463
                // adding "-rmd sha1" to the following command-line makes the
464
                // choice of signature algorithm for the response explicit
465
                // but it's only available from openssl-1.1.0 (which we do not
466
                // want to require just for that one thing).
467
                $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";
468
                $logHandle->debug(2, "Calling openssl ocsp with following cmdline: $execCmd\n");
469
                $output = [];
470
                $return = 999;
471
                exec($execCmd, $output, $return);
472
                if ($return !== 0) {
473
                    throw new Exception("Non-zero return value from openssl ocsp!");
474
                }
475
                $ocspFile = fopen($tempdir . "/$serialHex.response.der", "r");
476
                $ocsp = fread($ocspFile, 1000000);
477
                fclose($ocspFile);
478
                break;
479
            default:
480
                /* HTTP POST the serial to the CA. The CA knows about the state of
481
                 * the certificate.
482
                 *
483
                 * $httpResponse = httpRequest("https://clientca.hosted.eduroam.org/ocsp/", ["serial" => $serial ] );
484
                 *
485
                 * The result of this if clause has to be a DER-encoded OCSP statement
486
                 * to be stored in the variable $ocsp
487
                 */
488
                throw new Exception("External silverbullet CA is not implemented yet!");
489
        }
490
        // write the new statement into DB
491
        $dbHandle->exec("UPDATE silverbullet_certificate SET OCSP = ?, OCSP_timestamp = NOW() WHERE serial_number = ?", "si", $ocsp, $serial);
492
        return $ocsp;
493
    }
494
495
    /**
496
     * revokes a certificate
497
     * @param int $serial the serial number of the cert to revoke (decimal!)
498
     * @return array with revocation information
499
     */
500
    public function revokeCertificate($serial) {
501
502
503
// TODO for now, just mark as revoked in the certificates table (and use the stub OCSP updater)
504
        $nowSql = (new \DateTime())->format("Y-m-d H:i:s");
505
        if (CONFIG_CONFASSISTANT['SILVERBULLET']['CA']['type'] != "embedded") {
506
            // send revocation request to CA.
507
            // $httpResponse = httpRequest("https://clientca.hosted.eduroam.org/revoke/", ["serial" => $serial ] );
0 ignored issues
show
Unused Code Comprehensibility introduced by
53% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
508
            throw new Exception("External silverbullet CA is not implemented yet!");
509
        }
510
        // regardless if embedded or not, always keep local state in our own DB
511
        $this->databaseHandle->exec("UPDATE silverbullet_certificate SET revocation_status = 'REVOKED', revocation_time = ? WHERE serial_number = ?", "si", $nowSql, $serial);
512
        $this->loggerInstance->debug(2, "Certificate revocation status updated, about to call triggerNewOCSPStatement($serial).\n");
513
        $ocsp = ProfileSilverbullet::triggerNewOCSPStatement($serial);
514
        return ["OCSP" => $ocsp];
515
    }
516
517
    /**
518
     * performs an HTTP request. Currently unused, will be for external CA API calls.
519
     * 
520
     * @param string $url the URL to send the request to
521
     * @param array $postValues POST values to send
522
     * @return string the returned HTTP content
523
     */
524
    private function httpRequest($url, $postValues) {
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
525
        $options = [
526
            'http' => ['header' => 'Content-type: application/x-www-form-urlencoded\r\n', "method" => 'POST', 'content' => http_build_query($postValues)]
527
        ];
528
        $context = stream_context_create($options);
529
        return file_get_contents($url, false, $context);
530
    }
531
532
    /**
533
     * checks a certificate's status in the database and delivers its properties in an array
534
     * 
535
     * @param \mysqli_result $certQuery
536
     * @return array properties of the cert in questions
537
     */
538
    public static function enumerateCertDetails($certQuery) {
539
        $retval = [];
540
        while ($resource = mysqli_fetch_object($certQuery)) {
541
            // is the cert expired?
542
            $now = new \DateTime();
543
            $cert_expiry = new \DateTime($resource->expiry);
544
            $delta = $now->diff($cert_expiry);
545
            $certStatus = ($delta->invert == 1 ? self::SB_CERTSTATUS_EXPIRED : self::SB_CERTSTATUS_VALID);
546
            // expired is expired; even if it was previously revoked. But do update status for revoked ones...
547
            if ($certStatus == self::SB_CERTSTATUS_VALID && $resource->revocation_status == "REVOKED") {
548
                $certStatus = self::SB_CERTSTATUS_REVOKED;
549
            }
550
            $retval[] = [
551
                "status" => $certStatus,
552
                "serial" => $resource->serial_number,
553
                "name" => $resource->cn,
554
                "issued" => $resource->issued,
555
                "expiry" => $resource->expiry,
556
                "device" => $resource->device,
557
            ];
558
        }
559
        return $retval;
560
    }
561
562
    /**
563
     * For a given certificate username, find the profile and username in CAT
564
     * this needs to be static because we do not have a known profile instance
565
     * 
566
     * @param string $certUsername a username from CN or sAN:email
567
     * @return array
568
     */
569
    public static function findUserIdFromCert($certUsername) {
570
        $dbHandle = \core\DBConnection::handle("INST");
571
        $userrows = $dbHandle->exec("SELECT silverbullet_user_id AS user_id, profile_id AS profile FROM silverbullet_certificate WHERE cn = ?", "s", $certUsername);
572
        // SELECT -> resource, not boolean
573
        while ($returnedData = mysqli_fetch_object(/** @scrutinizer ignore-type */ $userrows)) { // only one
574
            return ["profile" => $returnedData->profile, "user" => $returnedData->user_id];
575
        }
576
    }
577
578
    /**
579
     * find out about the status of a given SB user; retrieves the info regarding all his tokens (and thus all his certificates)
580
     * @param int $userId
581
     * @return array of invitationObjects
582
     */
583 View Code Duplication
    public function userStatus($userId) {
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
584
        $retval = [];
585
        $userrows = $this->databaseHandle->exec("SELECT `token` FROM `silverbullet_invitation` WHERE `silverbullet_user_id` = ? AND `profile_id` = ? ", "ii", $userId, $this->identifier);
586
        // SELECT -> resource, not boolean
587
        while ($returnedData = mysqli_fetch_object(/** @scrutinizer ignore-type */ $userrows)) {
588
            $retval[] = new SilverbulletInvitation($returnedData->token);
589
        }
590
        return $retval;
591
    }
592
593
    /**
594
     * finds out the expiry date of a given user
595
     * @param int $userId
596
     * @return string
597
     */
598
    public function getUserExpiryDate($userId) {
599
        $query = $this->databaseHandle->exec("SELECT expiry FROM silverbullet_user WHERE id = ? AND profile_id = ? ", "ii", $userId, $this->identifier);
600
        // SELECT -> resource, not boolean
601
        while ($returnedData = mysqli_fetch_object(/** @scrutinizer ignore-type */ $query)) {
602
            return $returnedData->expiry;
603
        }
604
    }
605
    
606
    /**
607
     * sets the expiry date of a user to a new date of choice
608
     * @param int $userId
609
     * @param \DateTime $date
610
     */
611
    public function setUserExpiryDate($userId, $date) {
612
        $query = "UPDATE silverbullet_user SET expiry = ? WHERE profile_id = ? AND id = ?";
613
        $theDate = $date->format("Y-m-d");
614
        $this->databaseHandle->exec($query, "sii", $theDate, $this->identifier, $userId);
615
    }
616
617
    /**
618
     * lists all users of this SB profile
619
     * @return array
620
     */
621 View Code Duplication
    public function listAllUsers() {
1 ignored issue
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
622
        $userArray = [];
623
        $users = $this->databaseHandle->exec("SELECT `id`, `username` FROM `silverbullet_user` WHERE `profile_id` = ? ", "i", $this->identifier);
624
        // SELECT -> resource, not boolean
625
        while ($res = mysqli_fetch_object(/** @scrutinizer ignore-type */ $users)) {
626
            $userArray[$res->id] = $res->username;
627
        }
628
        return $userArray;
629
    }
630
631
    /**
632
     * lists all users which are currently active (i.e. have pending invitations and/or valid certs)
633
     * @return array
634
     */
635
    public function listActiveUsers() {
636
        // users are active if they have a non-expired invitation OR a non-expired, non-revoked certificate
637
        $userCount = [];
638
        $users = $this->databaseHandle->exec("SELECT DISTINCT u.id AS usercount FROM silverbullet_user u, silverbullet_invitation i, silverbullet_certificate c "
639
                . "WHERE u.profile_id = ? "
640
                . "AND ( "
641
                . "( u.id = i.silverbullet_user_id AND i.expiry >= NOW() )"
642
                . "     OR"
643
                . "  ( u.id = c.silverbullet_user_id AND c.expiry >= NOW() AND c.revocation_status != 'REVOKED' ) "
644
                . ")", "i", $this->identifier);
645
        // SELECT -> resource, not boolean
646
        while ($res = mysqli_fetch_object(/** @scrutinizer ignore-type */ $users)) {
647
            $userCount[] = $res->usercount;
648
        }
649
        return $userCount;
650
    }
651
652
    /**
653
     * adds a new user to the profile
654
     * 
655
     * @param string $username
656
     * @param \DateTime $expiry
657
     * @return int row ID of the new user in the database
658
     */
659
    public function addUser($username, \DateTime $expiry) {
660
        $query = "INSERT INTO silverbullet_user (profile_id, username, expiry) VALUES(?,?,?)";
661
        $date = $expiry->format("Y-m-d");
662
        $this->databaseHandle->exec($query, "iss", $this->identifier, $username, $date);
663
        return $this->databaseHandle->lastID();
664
    }
665
666
    /**
667
     * revoke all active certificates and pending invitations of a user
668
     * @param int $userId
669
     */
670
    public function deactivateUser($userId) {
671
        // set the expiry date of any still valid invitations to NOW()
672
        $query = "SELECT id FROM silverbullet_invitation WHERE profile_id = $this->identifier AND silverbullet_user_id = ? AND expiry >= NOW()";
673
        $exec = $this->databaseHandle->exec($query, "i", $userId);
674
        // SELECT -> resource, not boolean
675
        while ($result = mysqli_fetch_object(/** @scrutinizer ignore-type */ $exec)) {
676
            $this->revokeInvitation($result->id);
0 ignored issues
show
Bug introduced by
The method revokeInvitation() does not seem to exist on object<core\ProfileSilverbullet>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
677
        }
678
        // and revoke all certificates
679
        $query2 = "SELECT serial_number FROM silverbullet_certificate WHERE profile_id = $this->identifier AND silverbullet_user_id = ? AND expiry >= NOW() AND revocation_status = 'NOT_REVOKED'";
680
        $exec2 = $this->databaseHandle->exec($query2, "i", $userId);
681
        // SELECT -> resource, not boolean
682
        while ($result = mysqli_fetch_object(/** @scrutinizer ignore-type */ $exec2)) {
683
            $this->revokeCertificate($result->serial_number);
684
        }
685
        // and finally set the user expiry date to NOW(), too
686
        $query3 = "UPDATE silverbullet_user SET expiry = NOW() WHERE profile_id = $this->identifier AND id = ?";
687
        $this->databaseHandle->exec($query3, "i", $userId);
688
    }
689
    
690
    /**
691
     * updates the last_ack for all users (invoked when the admin claims to have re-verified continued eligibility of all users)
692
     */
693
    public function refreshEligibility() {
694
        $query = "UPDATE silverbullet_user SET last_ack = NOW() WHERE profile_id = ?";
695
        $this->databaseHandle->exec($query, "i", $this->identifier);
696
    }
697
}
698