Federation::triggerRevocation()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 15
rs 9.9666
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
/*
4
 * *****************************************************************************
5
 * Contributions to this work were made on behalf of the GÉANT project, a 
6
 * project that has received funding from the European Union’s Framework 
7
 * Programme 7 under Grant Agreements No. 238875 (GN3) and No. 605243 (GN3plus),
8
 * Horizon 2020 research and innovation programme under Grant Agreements No. 
9
 * 691567 (GN4-1) and No. 731122 (GN4-2).
10
 * On behalf of the aforementioned projects, GEANT Association is the sole owner
11
 * of the copyright in all material which was developed by a member of the GÉANT
12
 * project. GÉANT Vereniging (Association) is registered with the Chamber of 
13
 * Commerce in Amsterdam with registration number 40535155 and operates in the 
14
 * UK as a branch of GÉANT Vereniging.
15
 * 
16
 * Registered office: Hoekenrode 3, 1102BR Amsterdam, The Netherlands. 
17
 * UK branch address: City House, 126-130 Hills Road, Cambridge CB2 1PQ, UK
18
 *
19
 * License: see the web/copyright.inc.php file in the file structure or
20
 *          <base_url>/copyright.php after deploying the software
21
 */
22
23
/**
24
 * This file contains the Federation class.
25
 * 
26
 * @author Stefan Winter <[email protected]>
27
 * @author Tomasz Wolniewicz <[email protected]>
28
 * @author Maja Górecka-Wolniewicz <[email protected]>
29
 * 
30
 * @package Developer
31
 * 
32
 */
33
34
namespace core;
35
36
use \Exception;
0 ignored issues
show
Bug introduced by
The type \Exception was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
37
38
/**
39
 * This class represents an consortium federation.
40
 * 
41
 * It is semantically a country(!). Do not confuse this with a TLD; a federation
42
 * may span more than one TLD, and a TLD may be distributed across multiple federations.
43
 *
44
 * Example: a federation "fr" => "France" may also contain other TLDs which
45
 *              belong to France in spite of their different TLD
46
 * Example 2: Domains ending in .edu are present in multiple different
47
 *              federations
48
 *
49
 * @author Stefan Winter <[email protected]>
50
 * @author Tomasz Wolniewicz <[email protected]>
51
 *
52
 * @license see LICENSE file in root directory
53
 *
54
 * @package Developer
55
 */
56
class Federation extends EntityWithDBProperties
57
{
58
59
    /**
60
     * the handle to the FRONTEND database (only needed for some stats access)
61
     * 
62
     * @var DBConnection
63
     */
64
    private $frontendHandle;
65
66
    /**
67
     * the top-level domain of the Federation
68
     * 
69
     * @var string
70
     */
71
    public $tld;
72
    
73
    /**
74
     * 
75
     * @var array
76
     */
77
78
    public $adminLogins = [];
79
    
80
    private $idpArray = [];
81
    /**
82
     * retrieve the statistics from the database in an internal array representation
83
     * 
84
     * @param string $detail
85
     * @return array
86
     */
87
    private function downloadStatsCore($detail = '')
88
    {
89
        if ($detail !== 'ORGANISATIONS' && $detail !== 'PROFILES' && $detail !== 'FEDERATION') {
90
            $detail = 'NONE';
91
        }
92
        
93
        $grossAdmin = 0;
94
        $grossUser = 0;
95
        $grossSilverbullet = 0;
96
        $dataArray = [];
97
        $cohesionQuery = [
98
            'ORGANISATIONS' => "SELECT profile.inst_id AS inst_id, downloads.device_id AS dev_id, sum(downloads.downloads_user) AS dl_user, sum(downloads.downloads_silverbullet) as dl_sb, sum(downloads.downloads_admin) AS dl_admin FROM downloads JOIN profile ON downloads.profile_id=profile.profile_id JOIN institution ON profile.inst_id=institution.inst_id WHERE institution.country = ? GROUP BY profile.inst_id, downloads.device_id",
99
            'PROFILES' => "SELECT profile.inst_id AS inst_id, profile.profile_id AS profile_id, downloads.device_id AS dev_id, sum(downloads.downloads_user) AS dl_user, sum(downloads.downloads_silverbullet) as dl_sb, sum(downloads.downloads_admin) AS dl_admin FROM downloads JOIN profile ON downloads.profile_id=profile.profile_id JOIN institution ON profile.inst_id=institution.inst_id WHERE institution.country = ? GROUP BY profile.inst_id, profile.profile_id, downloads.device_id",
100
            'FEDERATION' => "SELECT downloads.device_id AS dev_id, sum(downloads.downloads_user) AS dl_user, sum(downloads.downloads_silverbullet) AS dl_sb, sum(downloads.downloads_admin) AS dl_admin FROM profile JOIN institution ON profile .inst_id = institution.inst_id JOIN downloads ON profile.profile_id = downloads.profile_id WHERE institution.country = ? AND profile.profile_id = downloads.profile_id GROUP BY device_id",
101
            'NONE' => "SELECT downloads.device_id as dev_id, sum(downloads.downloads_user) as dl_user, sum(downloads.downloads_silverbullet) AS dl_sb, sum(downloads.downloads_admin) as dl_admin FROM profile JOIN institution ON profile .inst_id = institution.inst_id JOIN downloads ON profile.profile_id = downloads.profile_id WHERE profile.inst_id = institution.inst_id AND institution.country = ? AND profile.profile_id = downloads.profile_id group by device_id"
102
        ];
103
        // first, find out which profiles belong to this federation
104
        $downloadsList = $this->databaseHandle->exec($cohesionQuery[$detail], "s", $this->tld);
105
        $deviceArray = \devices\Devices::listDevices();
106
        while ($queryResult = mysqli_fetch_object(/** @scrutinizer ignore-type */ $downloadsList)) {
107
            if ($detail === 'NONE' || $detail === 'FEDERATION') {
108
                $grossAdmin = $grossAdmin + $queryResult->dl_admin;
109
                $grossSilverbullet = $grossSilverbullet + $queryResult->dl_sb;
110
                $grossUser = $grossUser + $queryResult->dl_user;
111
                if ($detail === 'NONE') {
112
                    continue;
113
                }
114
            }    
115
            if (isset($deviceArray[$queryResult->dev_id])) {
116
                $displayName = $deviceArray[$queryResult->dev_id]['display'];
117
            } else { // this device has stats, but doesn't exist in current config. We don't even know its display name, so display its raw representation
118
                $displayName = sprintf(_("(discontinued) %s"), $queryResult->dev_id);
119
            }
120
            if ($detail === 'FEDERATION') {
121
                $dataArray[$displayName] = ["ADMIN" => $queryResult->dl_admin, "SILVERBULLET" => $queryResult->dl_sb, "USER" => $queryResult->dl_user];
122
            } else {
123
                $inst_id = $queryResult->inst_id;            
124
                if (!isset($dataArray[$inst_id])) {
125
                    $dataArray[$inst_id] = [];
126
                }            
127
                if ($detail === 'ORGANISATIONS') {       
128
                    $dataArray[$inst_id][$displayName] = ["ADMIN" => $queryResult->dl_admin, "SILVERBULLET" => $queryResult->dl_sb, "USER" => $queryResult->dl_user];
129
                }
130
                if ($detail === 'PROFILES') {
131
                    $profile_id = $queryResult->profile_id;
132
                    if (!isset($dataArray[$inst_id][$profile_id])) {
133
                        $dataArray[$inst_id][$profile_id] = [];
134
                    }
135
                    $dataArray[$inst_id][$profile_id][$displayName] = ["ADMIN" => $queryResult->dl_admin, "SILVERBULLET" => $queryResult->dl_sb, "USER" => $queryResult->dl_user];
136
                }
137
            }
138
        }
139
        if ($detail === 'NONE' || $detail === 'FEDERATION') {
140
            $dataArray["TOTAL"] = ["ADMIN" => $grossAdmin, "SILVERBULLET" => $grossSilverbullet, "USER" => $grossUser];
141
        }
142
        return $dataArray;
143
    }
144
145
    /**
146
     * when a Federation attribute changes, invalidate caches of all IdPs 
147
     * in that federation (e.g. change of fed logo changes the actual 
148
     * installers)
149
     * 
150
     * @return void
151
     */
152
    public function updateFreshness()
153
    {
154
        $idplist = $this->listIdentityProviders();
155
        foreach ($idplist as $idpDetail) {
156
            $idpDetail['instance']->updateFreshness();
157
        }
158
    }
159
160
    /**
161
     * gets the download statistics for the federation
162
     * @param string $format either as an html *table* or *XML* or *JSON*
163
     * @return string|array
164
     * @throws Exception
165
     */
166
    public function downloadStats($format, $detail = '')
167
    {
168
        $data = $this->downloadStatsCore($detail);
169
        $retstring = "";
170
171
        switch ($format) {
172
            case "table":
173
                foreach ($data as $device => $numbers) {
174
                    if ($device == "TOTAL") {
175
                        continue;
176
                    }
177
                    $retstring .= "<tr><td>$device</td><td>".$numbers['ADMIN']."</td><td>".$numbers['SILVERBULLET']."</td><td>".$numbers['USER']."</td></tr>";
178
                }
179
                $retstring .= "<tr><td><strong>TOTAL</strong></td><td><strong>".$data['TOTAL']['ADMIN']."</strong></td><td><strong>".$data['TOTAL']['SILVERBULLET']."</strong></td><td><strong>".$data['TOTAL']['USER']."</strong></td></tr>";
180
                break;
181
            case "XML":
182
                // the calls to date() operate on current date, so there is no chance for a FALSE to be returned. Silencing scrutinizer.
183
                $retstring .= "<federation id='$this->tld' ts='"./** @scrutinizer ignore-type */ date("Y-m-d")."T"./** @scrutinizer ignore-type */ date("H:i:s")."'>\n";
184
                foreach ($data as $device => $numbers) {
185
                    if ($device == "TOTAL") {
186
                        continue;
187
                    }
188
                    $retstring .= "  <device name='".$device."'>\n    <downloads group='admin'>".$numbers['ADMIN']."</downloads>\n    <downloads group='managed_idp'>".$numbers['SILVERBULLET']."</downloads>\n    <downloads group='user'>".$numbers['USER']."</downloads>\n  </device>";
189
                }
190
                $retstring .= "<total>\n  <downloads group='admin'>".$data['TOTAL']['ADMIN']."</downloads>\n  <downloads group='managed_idp'>".$data['TOTAL']['SILVERBULLET']."</downloads>\n  <downloads group='user'>".$data['TOTAL']['USER']."</downloads>\n</total>\n";
191
                $retstring .= "</federation>";
192
                break;
193
            case "array":
194
                return $data;
195
            default:
196
                throw new Exception("Statistics can be requested only in 'table' or 'XML' format!");
197
        }
198
        return $retstring;
199
    }
200
201
    /**
202
     *
203
     * Constructs a Federation object.
204
     *
205
     * @param string $fedname textual representation of the Federation object
206
     *                        Example: "lu" (for Luxembourg)
207
     * @throws Exception
208
     */
209
    public function __construct($fedname)
210
    {
211
        // initialise the superclass variables
212
213
        $this->databaseType = "INST";
214
        $this->entityOptionTable = "federation_option";
215
        $this->entityIdColumn = "federation_id";
216
217
        $cat = new CAT();
218
        if (!isset($cat->knownFederations[$fedname])) {
219
            throw new Exception("This federation is not known to the system!");
220
        }
221
        $this->identifier = 0; // we do not use the numeric ID of a federation
222
        // $fedname is unvetted input. We do know it's correct because of the 
223
        // knownFederations check above - so no security issue - but Scrutinizer
224
        // doesn't realise it because we assign the literal incoming value. 
225
        // Let's make this assignment more dumb so that it passes the SC checks.
226
        // Equivalent to the following line, but assigning processed indexes
227
        // instead of the identical user input.
228
        // $this->tld = $fedname;
229
        $fedIdentifiers = array_keys($cat->knownFederations);
230
        $this->tld = $fedIdentifiers[array_search(strtoupper($fedname), $fedIdentifiers)];
231
        $this->name = $cat->knownFederations[$this->tld]['name'];
232
        // end of spoon-feed
233
        
234
        parent::__construct(); // we now have access to our database handle
235
236
        $handle = DBConnection::handle("FRONTEND");
237
        if ($handle instanceof DBConnection) {
238
            $this->frontendHandle = $handle;
239
        } else {
240
            throw new Exception("This database type is never an array!");
241
        }
242
        $this->loggerInstance->debug(4, $fedname, "Creating federation:", " \n");
243
        // fetch attributes from DB; populates $this->attributes array
244
        $this->attributes = $this->retrieveOptionsFromDatabase("SELECT DISTINCT option_name, option_lang, option_value, row_id 
245
                                            FROM $this->entityOptionTable
246
                                            WHERE $this->entityIdColumn = ?
247
                                            ORDER BY option_name", "FED");
248
249
250
        $this->attributes[] = array("name" => "internal:country",
251
            "lang" => NULL,
252
            "value" => $this->tld,
253
            "level" => Options::LEVEL_FED,
254
            "row_id" => 0,
255
            "flag" => NULL);
256
257
        if (\config\Master::FUNCTIONALITY_LOCATIONS['CONFASSISTANT_RADIUS'] != 'LOCAL' && \config\Master::FUNCTIONALITY_LOCATIONS['CONFASSISTANT_SILVERBULLET'] == 'LOCAL') {
258
            // this instance exclusively does SB, so it is not necessary to ask
259
            // fed ops whether they want to enable it or not. So always add it
260
            // to the list of fed attributes
261
            $this->attributes[] = array("name" => "fed:silverbullet",
262
                "lang" => NULL,
263
                "value" => "on",
264
                "level" => Options::LEVEL_FED,
265
                "row_id" => 0,
266
                "flag" => NULL);
267
        }
268
269
        $this->idpListActive = [];
270
        $this->idpListAll = [];
271
    }
272
273
    /**
274
     * Creates a new IdP inside the federation.
275
     * 
276
     * @param string $type          type of institution - IdP, SP or IdPSP
277
     * @param string $ownerId       Persistent identifier of the user for whom this IdP is created (first administrator)
278
     * @param string $level         Privilege level of the first administrator (was he blessed by a federation admin or a peer?)
279
     * @param string $mail          e-mail address with which the user was invited to administer (useful for later user identification if the user chooses a "funny" real name)
280
     * @param string $bestnameguess name of the IdP, if already known, in the best-match language
281
     * @return integer identifier of the new IdP
282
     * @throws Exception
283
     */
284
    public function newIdP($model, $type, $ownerId, $level, $mail = NULL, $bestnameguess = NULL)
285
    {
286
        $this->databaseHandle->exec("INSERT INTO institution (country, type) VALUES('$this->tld', '$type')");
287
        $identifier = $this->databaseHandle->lastID();
288
289
        if ($identifier == 0 || !$this->loggerInstance->writeAudit($ownerId, "NEW", "Organisation $identifier")) {
290
            $text = "<p>Could not create a new ".common\Entity::$nomenclature_participant."!</p>";
291
            echo $text;
292
            throw new Exception($text);
293
        }
294
295
        if ($ownerId != "PENDING") {
296
            if ($mail === NULL) {
297
                throw new Exception("New IdPs in a federation need a mail address UNLESS created by API without OwnerId");
298
            }
299
            $this->databaseHandle->exec("INSERT INTO ownership (user_id,institution_id, blesslevel, orig_mail) VALUES(?,?,?,?)", "siss", $ownerId, $identifier, $level, $mail);
300
        }
301
        if ($bestnameguess === NULL) {
302
            $bestnameguess = "(no name yet, identifier $identifier)";
303
        }
304
        $admins = $this->listFederationAdmins();
305
306
        switch ($type) {
307
            case IdP::TYPE_IDP:
308
                $prettyPrintType = common\Entity::$nomenclature_idp;
309
                break;
310
            case IdP::TYPE_SP:
311
                $prettyPrintType = common\Entity::$nomenclature_hotspot;
312
                break;
313
            default:
314
                /// IdP and SP
315
                $prettyPrintType = sprintf(_("%s and %s"), common\Entity::$nomenclature_idp, common\Entity::$nomenclature_hotspot);
316
        }
317
318
        $consortium = \config\ConfAssistant::CONSORTIUM['display_name'];
319
        $productShort = \config\Master::APPEARANCE['productname'];
320
        $productLong = \config\Master::APPEARANCE['productname_long'];
321
        if ($model === 'TOKEN') {
322
            // notify the fed admins...
323
            /// arguments are: 1. nomenclature for the type of organisation being created (IdP/SP/both)
324
            ///                2. IdP name; 
325
            ///                3. consortium name (e.g. eduroam); 
326
            ///                4. federation shortname, e.g. "LU"; 
327
            ///                5. nomenclature for "institution"
328
            ///                6. product name (e.g. eduroam CAT); 
329
            ///                7. product long name (e.g. eduroam Configuration Assistant Tool)
330
            $message = sprintf(_("Hi,
331
332
    the invitation for the new %s %s in your %s federation %s has been used and the %s was created in %s.
333
334
    We thought you might want to know.
335
336
    Best regards,
337
338
    %s"),
339
                    $prettyPrintType,
340
                    $bestnameguess,
341
                    $consortium,
342
                    strtoupper($this->tld),
343
                    common\Entity::$nomenclature_participant,
344
                    $productShort,
345
                    $productLong);
346
        }
347
        if ($model === 'SELF') {
348
            // notify the fed admins...
349
            /// arguments are: 1. nomenclature for "institution"
350
            ///                2. IdP name; 
351
            ///                3. consortium name (e.g. eduroam); 
352
            ///                4. federation shortname, e.g. "LU"; 
353
            ///                5. product name (e.g. eduroam CAT);
354
            ///                6. product long name (e.g. eduroam Configuration Assistant Tool)
355
356
            $message = sprintf(_("Hi,
357
358
    the eduGAIN self-registration was used to create a new %s
359
           %s
360
    in your %s federation %s in %s.
361
362
    We thought you might want to know.
363
364
    Best regards,
365
366
    %s"),
367
                    common\Entity::$nomenclature_participant,
368
                    $bestnameguess,
369
                    $consortium,
370
                    strtoupper($this->tld),
371
                    $productShort,
372
                    $productLong);
373
        }
374
        if (\config\Master::MAILSETTINGS['notify_nro']) {
375
            foreach ($admins as $id) {
376
                $user = new User($id);
377
                 /// organisation
378
                $retval = $user->sendMailToUser(sprintf(_("%s in your federation was created"), common\Entity::$nomenclature_participant), $message);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $message does not seem to be defined for all execution paths leading up to this point.
Loading history...
379
                if ($retval === FALSE) {
380
                    $this->loggerInstance->debug(2, "Mail to federation admin was NOT sent!\n");
381
                }
382
            }
383
        }
384
        User::sendMailToCATadmins(sprintf(_("%s in your federation was created"), common\Entity::$nomenclature_participant), $message);
385
        return $identifier;
386
    }
387
388
    /**
389
     * list of all institutions. Fetched once from the DB and then stored in
390
     * this variable
391
     * 
392
     * @var array
393
     */
394
    private $idpListAll;
395
396
    /**
397
     * list of all active institutions. Fetched once from the DB and then stored
398
     * in this variable
399
     * 
400
     * @var array
401
     */
402
    private $idpListActive;
403
404
    /**
405
     * fetches all known certificate information for RADIUS/TLS certs from the DB
406
     * 
407
     * @return array
408
     */
409
    public function listTlsCertificates()
410
    {
411
        $certQuery = "SELECT ca_name, request_serial, distinguished_name, status, expiry, certificate, revocation_pin FROM federation_servercerts WHERE federation_id = ?";
412
        $upperTld = strtoupper($this->tld);
413
        $certList = $this->databaseHandle->exec($certQuery, "s", $upperTld);
414
        $retArray = [];
415
        // SELECT -> resource, not boolean
416
        while ($certListResult = mysqli_fetch_object(/** @scrutinizer ignore-type */ $certList)) {
417
            $retArray[] = [
418
                'CA' => $certListResult->ca_name,
419
                'REQSERIAL' => $certListResult->request_serial,
420
                'DN' => $certListResult->distinguished_name,
421
                'STATUS' => $certListResult->status,
422
                'EXPIRY' => $certListResult->expiry,
423
                'CERT' => $certListResult->certificate,
424
                'REVPIN' => $certListResult->revocation_pin,
425
            ];
426
        }
427
        return$retArray;
428
    }
429
430
    /**
431
     * requests a new certificate
432
     * 
433
     * @param string $user       the user ID requesting the certificate
434
     * @param array  $csr        the CSR with some metainfo in an array
435
     * @param int    $expiryDays how long should the cert be valid, in days
436
     * @return void
437
     */
438
    public function requestCertificate($user, $csr, $expiryDays)
439
    {
440
        $revocationPin = common\Entity::randomString(10, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
441
        $newReq = new CertificationAuthorityEduPkiServer();
442
        $reqserial = $newReq->sendRequestToCa($csr, $revocationPin, $expiryDays);
443
        if ($reqserial > 0) {
444
             $this->loggerInstance->writeAudit($user, "NEW", "Certificate request - NRO: ".$this->tld." - serial: ".$reqserial." - subject: ".$csr['SUBJECT']);
445
            $reqQuery = "INSERT INTO federation_servercerts "
446
                ."(federation_id, ca_name, request_serial, distinguished_name, status, revocation_pin) "
447
                ."VALUES (?, 'eduPKI', ?, ?, 'REQUESTED', ?)";
448
            $this->databaseHandle->exec($reqQuery, "siss", $this->tld, $reqserial, $csr['SUBJECT'], $revocationPin);
449
        } 
450
    }
451
452
    /**
453
     * fetches new cert info from the CA
454
     * 
455
     * @param int $reqSerial the request serial number that is to be updated
456
     * @return void
457
     */
458
    public function updateCertificateStatus($reqSerial)
459
    {
460
        $ca = new CertificationAuthorityEduPkiServer();
461
        $entryInQuestion = $ca->pickupFinalCert($reqSerial, FALSE);
462
        if ($entryInQuestion === FALSE) {
463
            return; // no update to fetch
464
        }
465
        $certDetails = openssl_x509_parse($entryInQuestion['CERT']);
466
        $expiry = "20".$certDetails['validTo'][0].$certDetails['validTo'][1]."-".$certDetails['validTo'][2].$certDetails['validTo'][3]."-".$certDetails['validTo'][4].$certDetails['validTo'][5];
467
        openssl_x509_export($entryInQuestion['CERT'], $pem);
468
        $updateQuery = "UPDATE federation_servercerts SET status = 'ISSUED', certificate = ?, expiry = ? WHERE ca_name = 'eduPKI' AND request_serial = ?";
469
        $this->databaseHandle->exec($updateQuery, "ssi", $pem, $expiry, $reqSerial);
470
    }
471
472
    /**
473
     * revokes a certificate.
474
     * 
475
     * @param int $reqSerial the request serial whose associated cert is to be revoked
476
     * @return void
477
     */
478
    public function triggerRevocation($reqSerial)
479
    {
480
        // revocation at the CA side works with the serial of the certificate, not the request
481
        // so find that out first
482
        // This is a select, so tell Scrutinizer about the type-safety of the result
483
        $certInfoResource = $this->databaseHandle->exec("SELECT certificate FROM federation_servercerts WHERE ca_name = 'eduPKI' AND request_serial = ?", "i", $reqSerial);
484
        $certInfo = mysqli_fetch_row(/** @scrutinizer ignore-type */ $certInfoResource);
485
        if ($certInfo === NULL) {
486
            return; // cert not found, nothing to revoke
487
        }
488
        $certData = openssl_x509_parse($certInfo[0]);
489
        $serial = $certData['full_details']['serialNumber'];
490
        $eduPki = new CertificationAuthorityEduPkiServer();
491
        $eduPki->revokeCertificate($serial);
492
        $this->databaseHandle->exec("UPDATE federation_servercerts SET status = 'REVOKED' WHERE ca_name = 'eduPKI' AND request_serial = ?", "i", $reqSerial);
493
    }
494
    /**
495
     * Gets an array of certificate status (as most critical) from all profiles
496
     * per IdP - passing over the non-active profiles
497
     */
498
    public function getIdentityProvidersCertStatus() {
499
        $query = "SELECT distinct profile.profile_id  FROM profile JOIN profile_option ON profile.profile_id = profile_option.profile_id WHERE option_name='profile:production' AND profile.sufficient_config = 1";
500
        $activeProfiles = [];
501
        $result = $this->databaseHandle->exec($query);
502
        $rows = $result->fetch_all();
503
        foreach ($rows as $row) {
504
           $activeProfiles[] = $row[0];
505
        }
506
        $query = "SELECT institution.inst_id AS inst_id, profile.profile_id AS profile_id, profile_option.option_value AS cert FROM profile_option JOIN profile ON profile_option.profile_id=profile.profile_id JOIN institution ON profile.inst_id=institution.inst_id WHERE profile_option.option_name='eap:ca_file' and institution.country='".$this->tld."'";        
507
        $result = $this->databaseHandle->exec($query);
508
        $rows = $result->fetch_all();
509
        $x509 = new \core\common\X509();
510
        $certsStatus = [];
511
        $idpCertStatus = [];
512
        foreach ($rows as $row) {
513
            $inst = $row[0];
514
            $profile = $row[1];
515
            // pass any rofile which is not active
516
            if (!in_array($profile, $activeProfiles)) {
517
                continue;
518
            }
519
            $encodedCert = $row[2];
520
            if (!isset($idpCertStatus[$inst])) {
521
                $idpCertStatus[$inst] = \core\AbstractProfile::CERT_STATUS_OK;
522
            }
523
            
524
            // check if we have already seen this cert if not, continue analysis
525
            if (!isset($certsStatus[$encodedCert])) {
526
                $tm = $x509->processCertificate(base64_decode($encodedCert))['full_details']['validTo_time_t'] - time();
527
                if ($tm < \config\ConfAssistant::CERT_WARNINGS['expiry_critical']) {
528
                    $certsStatus[$encodedCert] = \core\AbstractProfile::CERT_STATUS_ERROR;
529
                } elseif ($tm < \config\ConfAssistant::CERT_WARNINGS['expiry_warning']) {
530
                    $certsStatus[$encodedCert] = \core\AbstractProfile::CERT_STATUS_WARN;
531
                } else {
532
                    $certsStatus[$encodedCert] = \core\AbstractProfile::CERT_STATUS_OK;
533
                }
534
            }
535
            $idpCertStatus[$inst] = max($idpCertStatus[$inst], $certsStatus[$encodedCert]);
536
        }
537
        return $idpCertStatus;
538
    }
539
    
540
    /**
541
     * Lists all Identity Providers in this federation
542
     *
543
     * @param int $activeOnly if set to non-zero will list only those institutions which have some valid profiles defined.
544
     * @return array (Array of IdP instances)
545
     *
546
     */
547
    public function listIdentityProviders($activeOnly = 0)
548
    {
549
        // maybe we did this exercise before?
550
        if ($activeOnly != 0 && count($this->idpListActive) > 0) {
551
            return $this->idpListActive;
552
        }
553
        if ($activeOnly == 0 && count($this->idpListAll) > 0) {
554
            return $this->idpListAll;
555
        }
556
        // the one for activeOnly is much more complex:
557
        if ($activeOnly != 0) {
558
            $allIDPs = $this->databaseHandle->exec("SELECT distinct institution.inst_id AS inst_id
559
               FROM institution
560
               JOIN profile ON institution.inst_id = profile.inst_id
561
               WHERE institution.country = '$this->tld' 
562
               AND profile.showtime = 1
563
               ORDER BY inst_id");
564
        } else {         // default query is:
565
        $allIDPs = $this->databaseHandle->exec("SELECT institution.inst_id AS inst_id,
566
            GROUP_CONCAT(DISTINCT REGEXP_REPLACE(profile.realm, '.*@', '') SEPARATOR '===') AS realms
567
            FROM institution LEFT JOIN profile ON institution.inst_id = profile.inst_id
568
               WHERE country = '$this->tld' GROUP BY institution.inst_id ORDER BY inst_id");
569
570
        }
571
        $returnarray = [];
572
        // SELECT -> resource, not boolean
573
        while ($idpQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $allIDPs)) {
574
            if (isset($this->idpArray[$idpQuery->inst_id])) {
575
                $idp = $this->idpArray[$idpQuery->inst_id];
576
            } else {
577
                $idp = new IdP($idpQuery->inst_id);
578
                $this->idpArray[$idpQuery->inst_id] = $idp;
579
            }
580
            if (!isset($idpQuery->realms)) {
581
                $idpQuery->realms = '';
582
            }
583
            $name = $idp->name;
584
            $idpInfo = ['entityID' => $idp->identifier,
585
                'title' => $name,
586
                'country' => strtoupper($idp->federation),
587
                'instance' => $idp,
588
                'realms' => $idpQuery->realms]
589
                 ;
590
            $returnarray[$idp->identifier] = $idpInfo;
591
        }
592
        if ($activeOnly != 0) { // we're only doing this once.
593
            $this->idpListActive = $returnarray;
594
        } else {
595
            $this->idpListAll = $returnarray;
596
        }
597
        return $returnarray;
598
    }
599
600
    /**
601
     * returns an array with information about the authorised administrators of the federation
602
     * 
603
     * @return array list of the admins of this federation
604
     */
605
    public function listFederationAdmins()
606
    {
607
        $returnarray = [];
608
        $query = "SELECT user_id FROM user_options WHERE option_name = 'user:fedadmin' AND option_value = ?";
609
        if (\config\ConfAssistant::CONSORTIUM['name'] == "eduroam" && isset(\config\ConfAssistant::CONSORTIUM['deployment-voodoo']) && \config\ConfAssistant::CONSORTIUM['deployment-voodoo'] == "Operations Team") { // SW: APPROVED
610
            $query = "SELECT eptid as user_id FROM view_admin WHERE role = 'fedadmin' AND realm = ?";
611
        }
612
        $userHandle = DBConnection::handle("USER"); // we need something from the USER database for a change
613
        $upperFed = strtoupper($this->tld);
614
        // SELECT -> resource, not boolean
615
        $admins = $userHandle->exec($query, "s", $upperFed);
616
617
        while ($fedAdminQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $admins)) {
618
            $returnarray[] = $fedAdminQuery->user_id;
619
        }
620
        return $returnarray;
621
    }
622
623
    /**
624
     * cross-checks in the EXTERNAL customer DB which institutions exist there for the federations
625
     * 
626
     * @param bool   $unmappedOnly if set to TRUE, only returns those which do not have a known mapping to our internally known institutions
627
     * @param string $type         which type of entity to search for
628
     * @return array
629
     */
630
    public function listExternalEntities($unmappedOnly, $type = NULL)
631
    {
632
        $allExternals = [];
633
        $usedarray = [];
634
        $returnarray = [];
635
        if ($unmappedOnly) { // find out which entities are already mapped
636
            $syncstate = IdP::EXTERNAL_DB_SYNCSTATE_SYNCED;
637
            $alreadyUsed = $this->databaseHandle->exec("SELECT DISTINCT external_db_id FROM institution 
638
                                                                                                     WHERE external_db_id IS NOT NULL 
639
                                                                                                     AND external_db_syncstate = ?", "i", $syncstate);
640
            $pendingInvite = $this->databaseHandle->exec("SELECT DISTINCT external_db_uniquehandle FROM invitations 
641
                                                                                                      WHERE external_db_uniquehandle IS NOT NULL 
642
                                                                                                      AND invite_created >= TIMESTAMPADD(DAY, -1, NOW()) 
643
                                                                                                      AND used = 0");
644
            // SELECT -> resource, no boolean
645
            while ($alreadyUsedQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $alreadyUsed)) {
646
                $usedarray[] = $alreadyUsedQuery->external_db_id;
647
            }
648
            // SELECT -> resource, no boolean
649
            while ($pendingInviteQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $pendingInvite)) {
650
                if (!in_array($pendingInviteQuery->external_db_uniquehandle, $usedarray)) {
651
                    $usedarray[] = $pendingInviteQuery->external_db_uniquehandle;
652
                }
653
            }
654
        }
655
656
        if (\config\ConfAssistant::CONSORTIUM['name'] == "eduroam" && isset(\config\ConfAssistant::CONSORTIUM['deployment-voodoo']) && \config\ConfAssistant::CONSORTIUM['deployment-voodoo'] == "Operations Team") { // SW: APPROVED
657
            $externalDB = CAT::determineExternalConnection();
658
            // need to convert our internal notion of participant types to those of eduroam DB
659
            $allExternals = $externalDB->listExternalEntities($this->tld, $type);
660
        }
661
        foreach ($allExternals as $oneExternal) {
662
            if (!in_array($oneExternal["ID"], $usedarray)) {
663
                $returnarray[] = $oneExternal;
664
            }
665
        }
666
        return $returnarray;
667
    }
668
669
    const UNKNOWN_IDP = -1;
670
    const AMBIGUOUS_IDP = -2;
671
672
    /**
673
     * for a MySQL list of institutions, find an institution or find out that
674
     * there is no single best match
675
     * 
676
     * @param \mysqli_result $dbResult the query object to work with
677
     * @param string         $country  used to return the country of the inst, if can be found out
678
     * @return int the identifier of the inst, or one of the special return values if unsuccessful
679
     */
680
    private static function findCandidates(\mysqli_result $dbResult, &$country)
681
    {
682
        $retArray = [];
683
        while ($row_id = mysqli_fetch_object($dbResult)) {
684
            if (!in_array($row_id->id, $retArray)) {
685
                $retArray[] = $row_id->id;
686
                $country = strtoupper($row_id->country);
687
            }
688
        }
689
        if (count($retArray) <= 0) {
690
            return Federation::UNKNOWN_IDP;
691
        }
692
        /* No AMBIGUOUS_IDP
693
         if (count($retArray) > 1) {
694
            return Federation::AMBIGUOUS_IDP;
695
        }
696
        */
697
698
        return array_pop($retArray);
699
    }
700
701
    /**
702
     * If we are running diagnostics, our input from the user is the realm. We
703
     * need to find out which IdP this realm belongs to.
704
     * @param string $realm the realm to search for
705
     * @return array an array with two entries, CAT ID and DB ID, with either the respective ID of the IdP in the system, or UNKNOWN_IDP or AMBIGUOUS_IDP
706
     */
707
    public static function determineIdPIdByRealm($realm)
708
    {
709
        $country = NULL;
710
        $candidatesExternalDb = Federation::UNKNOWN_IDP;
711
        $dbHandle = DBConnection::handle("INST");
712
        $realmSearchStringCat = "%@$realm";
713
        $candidateCatQuery = $dbHandle->exec("SELECT p.profile_id as id, i.country as country FROM profile p, institution i WHERE p.inst_id = i.inst_id AND p.realm LIKE ? and p.showtime = 1", "s", $realmSearchStringCat);
714
        // this is a SELECT returning a resource, not a boolean
715
        $candidatesCat = Federation::findCandidates(/** @scrutinizer ignore-type */ $candidateCatQuery, $country);
716
717
        if (\config\ConfAssistant::CONSORTIUM['name'] == "eduroam" && isset(\config\ConfAssistant::CONSORTIUM['deployment-voodoo']) && \config\ConfAssistant::CONSORTIUM['deployment-voodoo'] == "Operations Team") { // SW: APPROVED        
718
            $externalHandle = DBConnection::handle("EXTERNAL");
719
            $realmSearchStringDb1 = "$realm";
720
            $realmSearchStringDb2 = "%,$realm";
721
            $realmSearchStringDb3 = "$realm,%";
722
            $realmSearchStringDb4 = "%,$realm,%";
723
            $candidateExternalQuery = $externalHandle->exec("SELECT instid as id, country FROM view_active_institution WHERE type != 2 AND inst_realm LIKE ? or inst_realm LIKE ? or inst_realm LIKE ? or inst_realm LIKE ?", "ssss", $realmSearchStringDb1, $realmSearchStringDb2, $realmSearchStringDb3, $realmSearchStringDb4);
724
            // SELECT -> resource, not boolean
725
            $candidatesExternalDb = Federation::findCandidates(/** @scrutinizer ignore-type */ $candidateExternalQuery, $country);
726
        }
727
728
        return ["CAT" => $candidatesCat, "EXTERNAL" => $candidatesExternalDb, "FEDERATION" => $country];
729
    }
730
    
731
    /**
732
     * Loads existing admins in all institutions of a given federation and check if some have been
733
     * inactive for a time longet that allowed threshold. Marks institutions as 0 - all good
734
     * or 1 - inactive admin(s) found
735
     * Sets the results in $this->adminLogins array
736
     */    
737
    public function loadAdminsLogins() {
738
        $inactivityOverride = $this->getAttributes('fed:max-inactivity');
739
        $hideWarningsFlag = $this->getAttributes('fed:hide-admin-warnings');
740
        if ($hideWarningsFlag !== []) {
741
            $active = -1;
742
        } else {
743
            if ($inactivityOverride == []) {
744
                $inactivityTimestamp = time() - \config\ConfAssistant::ADMIN_LOGINS['allowed_inactivity_days'] * 24 * 3600;
745
            } else {
746
                $inactivityTimestamp = time() - $inactivityOverride[0]['value'] * 24 * 3600;
747
            }
748
            // $active shows the time difference between the moment when a login thime would be considered as inactive
749
            // and the start of the recording system. If this is negative then we we cannot tell that someone who
750
            // was not recorded was not actually active within the allowed period
751
            $active = $inactivityTimestamp - strtotime(\config\ConfAssistant::ADMIN_LOGINS['startday']);
752
        }
753
        $query = "SELECT admin_logins.user_id AS user_id, ownership.institution_id as inst_id, admin_logins.last_login as last_login FROM admin_logins join ownership on admin_logins.user_id=ownership.user_id join institution on ownership.institution_id=institution.inst_id where country=?";
754
        $handle = DBConnection::handle("INST"); // we need something from the USER database for a change
755
        $upperFed = strtoupper($this->tld);
756
        // SELECT -> resource, not boolean
757
        $admins = $handle->exec($query, "s", $upperFed);
758
        while ($adminLoginQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $admins)) {
759
            $idp = $adminLoginQuery->inst_id;
760
            if ($active < 0) { // we are still in the silent period for this fed
761
                $this->adminLogins[$idp] = 0;
762
                continue;
763
            }
764
            if (isset($this->adminLogins[$idp]) && $this->adminLogins[$idp] == 1) {
765
                continue;
766
            }
767
            if ($adminLoginQuery->last_login == NULL) {
768
                $this->adminLogins[$idp] = 1;
769
                continue;
770
            }
771
            if (strtotime($adminLoginQuery->last_login) < $inactivityTimestamp) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $inactivityTimestamp does not seem to be defined for all execution paths leading up to this point.
Loading history...
772
                $this->adminLogins[$idp] = 1;
773
                continue;
774
            }
775
            $this->adminLogins[$idp] = 0;            
776
        }
777
        \core\common\Logging::debug_s(4, $this->adminLogins, "LOGINS:\n", "\n");
778
    }
779
}