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