Passed
Push — release_2_1 ( 101877...251144 )
by Tomasz
09:31
created

AbstractProfile::setOpenRoamingReadinessInfo()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
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 AbstractProfile class. It contains common methods for
25
 * both RADIUS/EAP profiles and SilverBullet profiles
26
 *
27
 * @author Stefan Winter <[email protected]>
28
 * @author Tomasz 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 EAP Profile.
40
 * Profiles can inherit attributes from their IdP, if the IdP has some. Otherwise,
41
 * one can set attribute in the Profile directly. If there is a conflict between
42
 * IdP-wide and Profile-wide attributes, the more specific ones (i.e. Profile) win.
43
 * 
44
 * @author Stefan Winter <[email protected]>
45
 * @author Tomasz Wolniewicz <[email protected]>
46
 *
47
 * @license see LICENSE file in root directory
48
 *
49
 * @package Developer
50
 */
51
abstract class AbstractProfile extends EntityWithDBProperties
52
{
53
54
    const HIDDEN = -1;
55
    const AVAILABLE = 0;
56
    const UNAVAILABLE = 1;
57
    const INCOMPLETE = 2;
58
    const NOTCONFIGURED = 3;
59
    const PROFILETYPE_RADIUS = "RADIUS";
60
    const PROFILETYPE_SILVERBULLET = "SILVERBULLET";
61
    public const SERVERNAME_ADDED = 2;
62
    public const CA_ADDED = 3;
63
    public const CA_CLASH_ADDED = 4;
64
    public const SERVER_CERT_ADDED = 5;
65
    public const CA_ROOT_NO_EXT = 6;
66
67
    /**
68
     * DB identifier of the parent institution of this profile
69
     * @var integer
70
     */
71
    public $institution;
72
73
    /**
74
     * name of the parent institution of this profile in the current language
75
     * @var string
76
     */
77
    public $instName;
78
79
    /**
80
     * realm of this profile (empty string if unset)
81
     * @var string
82
     */
83
    public $realm;
84
85
    /**
86
     * This array holds the supported EAP types (in object representation). 
87
     * 
88
     * They are not synced against the DB after instantiation.
89
     * 
90
     * @var array
91
     */
92
    protected $privEaptypes;
93
94
    /**
95
     * number of profiles of the IdP this profile is attached to
96
     * 
97
     * @var integer
98
     */
99
    protected $idpNumberOfProfiles;
100
101
    /**
102
     * IdP-wide attributes of the IdP this profile is attached to
103
     * 
104
     * @var array
105
     */
106
    protected $idpAttributes;
107
108
    /**
109
     * Federation level attributes that this profile is attached to via its IdP
110
     * 
111
     * @var array
112
     */
113
    protected $fedAttributes;
114
115
    /**
116
     * This class also needs to handle frontend operations, so needs its own
117
     * access to the FRONTEND database. This member stores the corresponding 
118
     * handle.
119
     * 
120
     * @var DBConnection
121
     */
122
    protected $frontendHandle;
123
124
    /**
125
     * readiness levels for OpenRoaming column in profiles)
126
     */
127
    const OVERALL_OPENROAMING_LEVEL_NO = 4;
128
    const OVERALL_OPENROAMING_LEVEL_GOOD = 3;
129
    const OVERALL_OPENROAMING_LEVEL_NOTE = 2;
130
    const OVERALL_OPENROAMING_LEVEL_WARN = 1;
131
    const OVERALL_OPENROAMING_LEVEL_ERROR = 0;
132
    
133
    /**
134
     *  generates a detailed log of which installer was downloaded
135
     * 
136
     * @param int    $idpIdentifier the IdP identifier
137
     * @param int    $profileId     the Profile identifier
138
     * @param string $deviceId      the Device identifier
139
     * @param string $area          the download area (user, silverbullet, admin)
140
     * @param string $lang          the language of the installer
141
     * @param int    $eapType       the EAP type of the installer
142
     * @return void
143
     * @throws Exception
144
     */
145
    protected function saveDownloadDetails($idpIdentifier, $profileId, $deviceId, $area, $lang, $eapType, $openRoaming)
146
    {
147
        if (\config\Master::PATHS['logdir']) {
148
            $file = fopen(\config\Master::PATHS['logdir']."/download_details.log", "a");
149
            if ($file === FALSE) {
150
                throw new Exception("Unable to open file for append: $file");
151
            }
152
            fprintf($file, "%-015s;%d;%d;%s;%s;%s;%d;%d\n", microtime(TRUE), $idpIdentifier, $profileId, $deviceId, $area, $lang, $eapType, $openRoaming);
153
            fclose($file);
154
        }
155
    }
156
157
    /**
158
     * checks if security-relevant parameters have changed
159
     * 
160
     * @param AbstractProfile $old old instantiation of a profile to compare against
161
     * @param AbstractProfile $new new instantiation of a profile 
162
     * @return array there are never any user-induced changes in SB
163
     */
164
    public static function significantChanges($old, $new)
165
    {
166
        $retval = [];
167
        // check if a CA was added
168
        $x509 = new common\X509();
169
        $baselineCA = [];
170
        $baselineCApublicKey = [];
171
        foreach ($old->getAttributes("eap:ca_file") as $oldCA) {
172
            $ca = $x509->processCertificate($oldCA['value']);
173
            $baselineCA[$ca['sha1']] = $ca['name'];
174
            $baselineCApublicKey[$ca['sha1']] = $ca['full_details']['public_key'];
175
        }
176
        // remove the new ones that are identical to the baseline
177
        foreach ($new->getAttributes("eap:ca_file") as $newCA) {
178
            $ca = $x509->processCertificate($newCA['value']);
179
            if (array_key_exists($ca['sha1'], $baselineCA) || $ca['root'] != 1) {
180
                // do nothing; we assume here that SHA1 doesn't clash
181
                continue;
182
            }
183
            // check if a CA with identical DN was added - alert NRO if so
184
            $foundSHA1 = array_search($ca['name'], $baselineCA);
185
            if ($foundSHA1 !== FALSE) {
186
                // but only if the public key does not match
187
                if ($baselineCApublicKey[$foundSHA1] === $ca['full_details']['public_key']) {
188
                    continue;
189
                }
190
                $retval[AbstractProfile::CA_CLASH_ADDED] .= "#SHA1 for CA with DN '".$ca['name']."' has SHA1 fingerprints (pre-existing) "./** @scrutinizer ignore-type */ array_search($ca['name'], $baselineCA)." and (added) ".$ca['sha1'];
191
            } else {
192
                $retval[AbstractProfile::CA_ADDED] .= "#CA with DN '"./** @scrutinizer ignore-type */ print_r($ca['name'], TRUE)."' and SHA1 fingerprint ".$ca['sha1']." was added as trust anchor";
193
            }
194
        }
195
        // check if a servername was added
196
        $baselineNames = [];
197
        foreach ($old->getAttributes("eap:server_name") as $oldName) {
198
            $baselineNames[] = $oldName['value'];
199
        }
200
        foreach ($new->getAttributes("eap:server_name") as $newName) {
201
            if (!in_array($newName['value'], $baselineNames)) {
202
                $retval[AbstractProfile::SERVERNAME_ADDED] .= "#New server name '".$newName['value']."' added";
203
            }
204
        }
205
        return $retval;
206
    }
207
208
    /**
209
     * Takes note of the OpenRoaming participation and conformance level
210
     * 
211
     * @param int $level the readiness level, as determined by RFC7585Tests
212
     * @return void
213
     */
214
    public function setOpenRoamingReadinessInfo(int $level)
215
    {
216
            $this->databaseHandle->exec("UPDATE profile SET openroaming = ? WHERE profile_id = ?", "ii", $level, $this->identifier);
217
    }
218
219
    /**
220
     * each profile has supported EAP methods, so get this from DB, Silver Bullet has one
221
     * static EAP method.
222
     * 
223
     * @return array list of supported EAP methods
224
     */
225
    protected function fetchEAPMethods()
226
    {
227
        $eapMethod = $this->databaseHandle->exec("SELECT eap_method_id 
228
                                                        FROM supported_eap supp 
229
                                                        WHERE supp.profile_id = $this->identifier 
230
                                                        ORDER by preference");
231
        $eapTypeArray = [];
232
        // SELECTs never return a boolean, it's always a resource
233
        while ($eapQuery = (mysqli_fetch_object(/** @scrutinizer ignore-type */ $eapMethod))) {
234
            $eaptype = new common\EAP($eapQuery->eap_method_id);
235
            $eapTypeArray[] = $eaptype;
236
        }
237
        $this->loggerInstance->debug(4, "This profile supports the following EAP types:\n"./** @scrutinizer ignore-type */ print_r($eapTypeArray, true));
238
        return $eapTypeArray;
239
    }
240
241
    /**
242
     * Class constructor for existing profiles (use IdP::newProfile() to actually create one). Retrieves all attributes and 
243
     * supported EAP types from the DB and stores them in the priv_ arrays.
244
     * 
245
     * sub-classes need to set the property $realm, $name themselves!
246
     * 
247
     * @param int $profileIdRaw identifier of the profile in the DB
248
     * @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.
249
     * @throws Exception
250
     */
251
    public function __construct($profileIdRaw, $idpObject = NULL)
252
    {
253
        $this->databaseType = "INST";
254
        parent::__construct(); // we now have access to our INST database handle and logging
255
        $handle = DBConnection::handle("FRONTEND");
256
        if ($handle instanceof DBConnection) {
257
            $this->frontendHandle = $handle;
258
        } else {
259
            throw new Exception("This database type is never an array!");
260
        }
261
        $profile = $this->databaseHandle->exec("SELECT inst_id FROM profile WHERE profile_id = ?", "i", $profileIdRaw);
262
        // SELECT always yields a resource, never a boolean
263
        if ($profile->num_rows == 0) {
264
            $this->loggerInstance->debug(2, "Profile $profileIdRaw not found in database!\n");
265
            throw new Exception("Profile $profileIdRaw not found in database!");
266
        }
267
        $this->identifier = $profileIdRaw;
268
        $profileQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $profile);
269
        if (!($idpObject instanceof IdP)) {
270
            $this->institution = $profileQuery->inst_id;
271
            $idp = new IdP($this->institution);
272
        } else {
273
            $idp = $idpObject;
274
            $this->institution = $idp->identifier;
275
        }
276
277
        $this->instName = $idp->name;
278
        $this->idpNumberOfProfiles = $idp->profileCount();
279
        $this->idpAttributes = $idp->getAttributes();
280
        $fedObject = new Federation($idp->federation);
281
        $this->fedAttributes = $fedObject->getAttributes();
282
        $this->loggerInstance->debug(4, "--- END Constructing new AbstractProfile object ... ---\n");
283
    }
284
285
    /**
286
     * find a profile, given its realm
287
     * 
288
     * @param string $realm the realm for which we are trying to find a profile
289
     * @return int|false the profile identifier, if any
290
     */
291
    public static function profileFromRealm($realm)
292
    {
293
        // static, need to create our own handle
294
        $handle = DBConnection::handle("INST");
295
        $execQuery = $handle->exec("SELECT profile_id FROM profile WHERE realm LIKE '%@$realm'");
296
        // a SELECT query always yields a resource, not a boolean
297
        if ($profileIdQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $execQuery)) {
298
            return $profileIdQuery->profile_id;
299
        }
300
        return FALSE;
301
    }
302
303
    /**
304
     * Constructs the outer ID which should be used during realm tests. Obviously
305
     * can only do something useful if the realm is known to the system.
306
     * 
307
     * @return string the outer ID to use for realm check operations
308
     * @throws Exception
309
     */
310
    public function getRealmCheckOuterUsername()
311
    {
312
        $realm = $this->getAttributes("internal:realm")[0]['value'] ?? FALSE;
313
        if ($realm == FALSE) { // we can't really return anything useful here
314
            throw new Exception("Unable to construct a realmcheck username if the admin did not tell us the realm. You shouldn't have called this function in this context.");
315
        }
316
        if (count($this->getAttributes("internal:checkuser_outer")) > 0) {
317
            // we are supposed to use a specific outer username for checks, 
318
            // which is different from the outer username we put into installers
319
            return $this->getAttributes("internal:checkuser_value")[0]['value']."@".$realm;
320
        }
321
        if (count($this->getAttributes("internal:use_anon_outer")) > 0) {
322
            // no special check username, but there is an anon outer ID for
323
            // installers - so let's use that one
324
            return $this->getAttributes("internal:anon_local_value")[0]['value']."@".$realm;
325
        }
326
        // okay, no guidance on outer IDs at all - but we need *something* to
327
        // test with for the RealmChecks. So:
328
        return "@".$realm;
329
    }
330
331
    /**
332
     * update the last_changed timestamp for this profile
333
     * 
334
     * @return void
335
     */
336
    public function updateFreshness()
337
    {
338
        $this->databaseHandle->exec("UPDATE profile SET last_change = CURRENT_TIMESTAMP WHERE profile_id = $this->identifier");
339
    }
340
341
    /**
342
     * gets the last-modified timestamp (useful for caching "dirty" check)
343
     * 
344
     * @return string the date in string form, as returned by SQL
345
     */
346
    public function getFreshness()
347
    {
348
        $execLastChange = $this->databaseHandle->exec("SELECT last_change FROM profile WHERE profile_id = $this->identifier");
349
        // SELECT always returns a resource, never a boolean
350
        if ($freshnessQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $execLastChange)) {
351
            return $freshnessQuery->last_change;
352
        }
353
    }
354
    /**
355
     * tests if the configurator needs to be regenerated
356
     * returns the configurator path or NULL if regeneration is required
357
     */
358
    /**
359
     * This function tests if the configurator needs to be regenerated 
360
     * (properties of the Profile may have changed since the last configurator 
361
     * generation).
362
     * SilverBullet will always return NULL here because all installers are new!
363
     * 
364
     * @param string $device device ID to check
365
     * @return mixed a string with the path to the configurator download, or NULL if it needs to be regenerated
366
     */
367
368
    /**
369
     * This function tests if the configurator needs to be regenerated (properties of the Profile may have changed since the last configurator generation).
370
     * 
371
     * @param string $device device ID to check
372
     * @return mixed a string with the path to the configurator download, or NULL if it needs to be regenerated
373
     */
374
    public function testCache($device, $openRoaming)
375
    {
376
        $returnValue = ['cache' => NULL, 'mime' => NULL];
377
        $lang = $this->languageInstance->getLang();
378
        $result = $this->frontendHandle->exec("SELECT download_path, mime, UNIX_TIMESTAMP(installer_time) AS tm FROM downloads WHERE profile_id = ? AND device_id = ? AND lang = ? AND openroaming = ?", "issi", $this->identifier, $device, $lang, $openRoaming);
379
        // SELECT queries always return a resource, not a boolean
380
        if ($result && $cache = mysqli_fetch_object(/** @scrutinizer ignore-type */ $result)) {
381
            $execUpdate = $this->databaseHandle->exec("SELECT UNIX_TIMESTAMP(last_change) AS last_change FROM profile WHERE profile_id = $this->identifier");
382
            // SELECT queries always return a resource, not a boolean
383
            if ($lastChange = mysqli_fetch_object(/** @scrutinizer ignore-type */ $execUpdate)->last_change) {
384
                if ($lastChange < $cache->tm) {
385
                    $this->loggerInstance->debug(4, "Installer cached:$cache->download_path\n");
386
                    $returnValue = ['cache' => $cache->download_path, 'mime' => $cache->mime];
387
                }
388
            }
389
        }
390
        return $returnValue;
391
    }
392
393
    /**
394
     * Updates database with new installer location. Actually does stuff when
395
     * caching is possible; is a noop if not
396
     * 
397
     * @param string $device         the device identifier string
398
     * @param string $path           the path where the new installer can be found
399
     * @param string $mime           the mime type of the new installer
400
     * @param int    $integerEapType the inter-representation of the EAP type that is configured in this installer
401
     * @return void
402
     */
403
    abstract public function updateCache($device, $path, $mime, $integerEapType, $openRoaming);
404
405
    /** Toggle anonymous outer ID support.
406
     *
407
     * @param boolean $shallwe TRUE to enable outer identities (needs valid $realm), FALSE to disable
408
     * @return void
409
     */
410
    abstract public function setAnonymousIDSupport($shallwe);
411
412
    /**
413
     * Log a new download for our stats
414
     * 
415
     * @param string $device the device id string
416
     * @param string $area   either admin or user
417
     * @return boolean TRUE if incrementing worked, FALSE if not
418
     */
419
    public function incrementDownloadStats($device, $area, $openRoaming)
420
    {
421
        if ($area == "admin" || $area == "user" || $area == "silverbullet") {
422
            $lang = $this->languageInstance->getLang();
423
            $this->frontendHandle->exec("INSERT INTO downloads (profile_id, device_id, lang, openroaming, downloads_$area) VALUES (? ,?, ?, ?, 1) ON DUPLICATE KEY UPDATE downloads_$area = downloads_$area + 1", "issi", $this->identifier, $device, $lang, $openRoaming);
424
            // get eap_type from the downloads table
425
            $eapTypeQuery = $this->frontendHandle->exec("SELECT eap_type FROM downloads WHERE profile_id = ? AND device_id = ? AND lang = ?", "iss", $this->identifier, $device, $lang);
426
            // SELECT queries always return a resource, not a boolean
427
            if (!$eapTypeQuery || !$eapO = mysqli_fetch_object(/** @scrutinizer ignore-type */ $eapTypeQuery)) {
428
                $this->loggerInstance->debug(2, "Error getting EAP_type from the database\n");
429
            } else {
430
                if ($eapO->eap_type == NULL) {
431
                    $this->loggerInstance->debug(2, "EAP_type not set in the database\n");
432
                } else {
433
                    $this->saveDownloadDetails($this->institution, $this->identifier, $device, $area, $this->languageInstance->getLang(), $eapO->eap_type, $openRoaming);
434
                }
435
            }
436
            return TRUE;
437
        }
438
        return FALSE;
439
    }
440
441
    /**
442
     * Retrieve current download stats from database, either for one specific device or for all devices
443
     * 
444
     * @param string $device the device id string
445
     * @return mixed user downloads of this profile; if device is given, returns the counter as int, otherwise an array with devicename => counter
446
     */
447
    public function getUserDownloadStats($device = NULL)
448
    {
449
        $columnName = "downloads_user";
450
        if ($this instanceof \core\ProfileSilverbullet) {
451
            $columnName = "downloads_silverbullet";
452
        }
453
        $returnarray = [];
454
        $numbers = $this->frontendHandle->exec("SELECT device_id, SUM($columnName) AS downloads_user FROM downloads WHERE profile_id = ? GROUP BY device_id", "i", $this->identifier);
455
        // SELECT queries always return a resource, not a boolean
456
        while ($statsQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $numbers)) {
457
            $returnarray[$statsQuery->device_id] = $statsQuery->downloads_user;
458
        }
459
        if ($device !== NULL) {
460
            if (isset($returnarray[$device])) {
461
                return $returnarray[$device];
462
            }
463
            return 0;
464
        }
465
        // we should pretty-print the device names
466
        $finalarray = [];
467
        $devlist = \devices\Devices::listDevices($this->identifier);
468
        foreach ($returnarray as $devId => $count) {
469
            if (isset($devlist[$devId])) {
470
                $finalarray[$devlist[$devId]['display']] = $count;
471
            }
472
        }
473
        return $finalarray;
474
    }
475
476
    /**
477
     * Deletes the profile from database and uninstantiates itself.
478
     * Works fine also for Silver Bullet; the first query will simply do nothing
479
     * because there are no stored options
480
     * 
481
     * @return void
482
     */
483
    public function destroy()
484
    {
485
        $this->databaseHandle->exec("DELETE FROM profile_option WHERE profile_id = $this->identifier");
486
        $this->databaseHandle->exec("DELETE FROM supported_eap WHERE profile_id = $this->identifier");
487
        $this->databaseHandle->exec("DELETE FROM profile WHERE profile_id = $this->identifier");
488
    }
489
490
    /**
491
     * Specifies the realm of this profile.
492
     * 
493
     * Forcefully type-hinting $realm parameter to string - Scrutinizer seems to
494
     * think that it can alternatively be an array<integer,?> which looks like a
495
     * false positive. If there really is an issue, let PHP complain about it at
496
     * runtime.
497
     * 
498
     * @param string $realm the realm (potentially with the local@ part that should be used for anonymous identities)
499
     * @return void
500
     */
501
    public function setRealm(string $realm)
502
    {
503
        $this->databaseHandle->exec("UPDATE profile SET realm = ? WHERE profile_id = ?", "si", $realm, $this->identifier);
504
        $this->realm = $realm;
505
    }
506
507
    /**
508
     * register new supported EAP method for this profile
509
     *
510
     * @param \core\common\EAP $type       The EAP Type, as defined in class EAP
511
     * @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.
512
     * @return void
513
     */
514
    public function addSupportedEapMethod(\core\common\EAP $type, $preference)
515
    {
516
        $eapInt = $type->getIntegerRep();
517
        $this->databaseHandle->exec("INSERT INTO supported_eap (profile_id, eap_method_id, preference) VALUES (?, ?, ?)", "iii", $this->identifier, $eapInt, $preference);
518
        $this->updateFreshness();
519
    }
520
521
    /**
522
     * Produces an array of EAP methods supported by this profile, ordered by preference
523
     * 
524
     * @param int $completeOnly if set and non-zero limits the output to methods with complete information
525
     * @return array list of EAP methods, (in object representation)
526
     */
527
    public function getEapMethodsinOrderOfPreference($completeOnly = 0)
528
    {
529
        $temparray = [];
530
531
        if ($completeOnly == 0) {
532
            return $this->privEaptypes;
533
        }
534
        foreach ($this->privEaptypes as $type) {
535
            if ($this->isEapTypeDefinitionComplete($type) === true) {
536
                $temparray[] = $type;
537
            }
538
        }
539
        return($temparray);
540
    }
541
542
    /**
543
     * Performs a sanity check for a given EAP type - did the admin submit enough information to create installers for him?
544
     * 
545
     * @param common\EAP $eaptype the EAP type
546
     * @return mixed TRUE if the EAP type is complete; an array of missing attributes if it's incomplete; FALSE if it's incomplete for other reasons
547
     */
548
    public function isEapTypeDefinitionComplete($eaptype)
549
    {
550
        if ($eaptype->needsServerCACert() && $eaptype->needsServerName()) {
551
            $missing = [];
552
            // silverbullet needs a support email address configured
553
            if ($eaptype->getIntegerRep() == common\EAP::INTEGER_SILVERBULLET && count($this->getAttributes("support:email")) == 0) {
554
                return ["support:email"];
555
            }
556
            $cnOption = $this->getAttributes("eap:server_name"); // cannot be set per device or eap type
557
            $caOption = $this->getAttributes("eap:ca_file"); // cannot be set per device or eap type
558
559
            if (count($caOption) > 0 && count($cnOption) > 0) {// see if we have at least one root CA cert
560
                foreach ($caOption as $oneCa) {
561
                    $x509 = new \core\common\X509();
562
                    $caParsed = $x509->processCertificate($oneCa['value']);
563
                    if ($caParsed['root'] == 1) {
564
                        return TRUE;
565
                    }
566
                }
567
                $missing[] = "eap:ca_file";
568
            }
569
            if (count($caOption) == 0) {
570
                $missing[] = "eap:ca_file";
571
            }
572
            if (count($cnOption) == 0) {
573
                $missing[] = "eap:server_name";
574
            }
575
            if (count($missing) == 0) {
576
                return TRUE;
577
            }
578
            return $missing;
579
        }
580
        return TRUE;
581
    }
582
583
    /**
584
     * list all devices marking their availabiblity and possible redirects
585
     *
586
     * @return array of device ids display names and their status
587
     */
588
    public function listDevices()
589
    {
590
        $returnarray = [];
591
        $redirect = $this->getAttributes("device-specific:redirect"); // this might return per-device ones or the general one
592
        // if it was a general one, we are done. Find out if there is one such
593
        // which has device = NULL
594
        $generalRedirect = NULL;
595
        foreach ($redirect as $index => $oneRedirect) {
596
            if ($oneRedirect["level"] == Options::LEVEL_PROFILE) {
597
                $generalRedirect = $index;
598
            }
599
        }
600
        if ($generalRedirect !== NULL) { // could be index 0
601
            return [['id' => '0', 'redirect' => $redirect[$generalRedirect]['value']]];
602
        }
603
        $preferredEap = $this->getEapMethodsinOrderOfPreference(1);
604
        $eAPOptions = [];
605
        if (count($this->getAttributes("media:openroaming")) == 1 && $this->getAttributes("media:openroaming")[0]['value'] == 'always-preagreed') {
606
            $orAlways = 1;
607
        } else {
608
            $orAlways = 0;
609
        }
610
        
611
        foreach (\devices\Devices::listDevices($this->identifier, $orAlways) as $deviceIndex => $deviceProperties) {
612
            $factory = new DeviceFactory($deviceIndex);
613
            $dev = $factory->device;
614
            // find the attribute pertaining to the specific device
615
            $group = '';
616
            $redirectUrl = 0;
617
            $redirects = [];
618
            foreach ($redirect as $index => $oneRedirect) {
619
                if ($oneRedirect["device"] == $deviceIndex) {
620
                    $redirects[] = $oneRedirect;
621
                }
622
            }
623
            if (count($redirects) > 0) {
624
                $redirectUrl = $this->languageInstance->getLocalisedValue($redirects);
625
            }
626
            $devStatus = self::AVAILABLE;
627
            $message = 0;
628
            if (isset($deviceProperties['options']) && isset($deviceProperties['options']['message']) && $deviceProperties['options']['message']) {
629
                $message = $deviceProperties['options']['message'];
630
            }
631
            if (isset($deviceProperties['group'])) {
632
                $group = $deviceProperties['group'];
633
            }
634
            $eapCustomtext = 0;
635
            $deviceCustomtext = 0;
636
            $geteduroam = 0;
637
            if ($redirectUrl === 0) {
638
                if (isset($deviceProperties['options']) && isset($deviceProperties['options']['redirect']) && $deviceProperties['options']['redirect']) {
639
                    $devStatus = self::HIDDEN;
640
                } else {
641
                    $dev->calculatePreferredEapType($preferredEap);
642
                    $eap = $dev->selectedEap;
643
                    if (count($eap) > 0) {
644
                        if (isset($eAPOptions["eap-specific:customtext"][serialize($eap)])) {
645
                            $eapCustomtext = $eAPOptions["eap-specific:customtext"][serialize($eap)];
646
                        } else {
647
                            // fetch customtexts from method-level attributes
648
                            $eapCustomtext = 0;
649
                            $customTextAttributes = [];
650
                            $attributeList = $this->getAttributes("eap-specific:customtext"); // eap-specific attributes always have the array index 'eapmethod' set
651
                            foreach ($attributeList as $oneAttribute) {
652
                                if ($oneAttribute["eapmethod"] == $eap) {
653
                                    $customTextAttributes[] = $oneAttribute;
654
                                }
655
                            }
656
                            if (count($customTextAttributes) > 0) {
657
                                $eapCustomtext = $this->languageInstance->getLocalisedValue($customTextAttributes);
658
                            }
659
                            $eAPOptions["eap-specific:customtext"][serialize($eap)] = $eapCustomtext;
660
                        }
661
                        // fetch customtexts for device
662
                        $customTextAttributes = [];
663
                        $attributeList = $this->getAttributes("device-specific:customtext");
664
                        foreach ($attributeList as $oneAttribute) {
665
                            if ($oneAttribute["device"] == $deviceIndex) { // device-specific attributes always have the array index "device" set
666
                                $customTextAttributes[] = $oneAttribute;
667
                            }
668
                        }
669
                        $deviceCustomtext = $this->languageInstance->getLocalisedValue($customTextAttributes);
670
                    } else {
671
                        $devStatus = self::UNAVAILABLE;
672
                    }
673
                    $geteduroamOpts = $this->getAttributes("device-specific:geteduroam");
674
                    foreach ($geteduroamOpts as $dev) {
675
                        if ($dev['device'] == $deviceIndex) {
676
                            $geteduroam = $dev['value'] == 'on' ? 1 : 0;
677
                        }
678
                    }
679
                }
680
            }
681
            $returnarray[] = ['id' => $deviceIndex, 'display' => $deviceProperties['display'], 'status' => $devStatus, 'redirect' => $redirectUrl, 'eap_customtext' => $eapCustomtext, 'device_customtext' => $deviceCustomtext, 'message' => $message, 'options' => $deviceProperties['options'], 'group' => $group, 'geteduroam' => $geteduroam];
682
        }
683
        return $returnarray;
684
    }
685
686
    /**
687
     * prepare profile attributes for device modules
688
     * Gets profile attributes taking into account the most specific level on which they may be defined
689
     * as well as the chosen language.
690
     * can be called with an optional $eap argument
691
     * 
692
     * @param array $eap if specified, retrieves all attributes except those not pertaining to the given EAP type
693
     * @return array list of attributes in collapsed style (index is the attrib name, value is an array of different values)
694
     */
695
    public function getCollapsedAttributes($eap = [])
696
    {
697
        $collapsedList = [];
698
        foreach ($this->getAttributes() as $attribute) {
699
            // filter out eap-level attributes not pertaining to EAP type $eap
700
            if (count($eap) > 0 && isset($attribute['eapmethod']) && $attribute['eapmethod'] != 0 && $attribute['eapmethod'] != $eap) {
701
                continue;
702
            }
703
            // create new array indexed by attribute name
704
            
705
            if (isset($attribute['device'])) {
706
                $collapsedList[$attribute['name']][$attribute['device']][] = $attribute['value'];
707
            } else {
708
                $collapsedList[$attribute['name']][] = $attribute['value'];
709
            } 
710
            // and keep all language-variant names in a separate sub-array
711
            if ($attribute['flag'] == "ML") {
712
                $collapsedList[$attribute['name']]['langs'][$attribute['lang']] = $attribute['value'];
713
            }
714
        }
715
        // once we have the final list, populate the respective "best-match"
716
        // language to choose for the ML attributes
717
718
        foreach ($collapsedList as $attribName => $valueArray) {
719
            if (isset($valueArray['langs'])) { // we have at least one language-dependent name in this attribute
720
                // for printed names on screen:
721
                // assign to exact match language, fallback to "default" language, fallback to English, fallback to whatever comes first in the list
722
                $collapsedList[$attribName][0] = $valueArray['langs'][$this->languageInstance->getLang()] ?? $valueArray['langs']['C'] ?? $valueArray['langs']['en'] ?? array_shift($valueArray['langs']);
723
                // for names usable in filesystems (closer to good old ASCII...)
724
                // prefer English, otherwise the "default" language, otherwise the same that we got above
725
                $collapsedList[$attribName][1] = $valueArray['langs']['en'] ?? $valueArray['langs']['C'] ?? $collapsedList[$attribName][0];
726
            }
727
        }
728
        return $collapsedList;
729
    }
730
731
    const READINESS_LEVEL_NOTREADY = 0;
732
    const READINESS_LEVEL_SUFFICIENTCONFIG = 1;
733
    const READINESS_LEVEL_SHOWTIME = 2;
734
    const CERT_STATUS_OK = 0;
735
    const CERT_STATUS_WARN = 1;
736
    const CERT_STATUS_ERROR = 2;
737
    
738
739
    /**
740
     * Does the profile contain enough information to generate installers with
741
     * it? Silverbullet will always return TRUE; RADIUS profiles need to do some
742
     * heavy lifting here.
743
     * 
744
     * @return int one of the constants above which tell if enough info is set to enable installers
745
     */
746
    public function readinessLevel()
747
    {
748
        $result = $this->databaseHandle->exec("SELECT sufficient_config, showtime FROM profile WHERE profile_id = ?", "i", $this->identifier);
749
        // SELECT queries always return a resource, not a boolean
750
        $configQuery = mysqli_fetch_row(/** @scrutinizer ignore-type */ $result);
751
        if ($configQuery[0] == "0") {
752
            return self::READINESS_LEVEL_NOTREADY;
753
        }
754
        // at least fully configured, if not showtime!
755
        if ($configQuery[1] == "0") {
756
            return self::READINESS_LEVEL_SUFFICIENTCONFIG;
757
        }
758
        return self::READINESS_LEVEL_SHOWTIME;
759
    }
760
761
    /**
762
     * Checks all profile certificates validity periods comparing to the pre-defined
763
     * thresholds and returns the most critical status.
764
     * 
765
     * @return int - one of constants defined in this profile
766
     */
767
    public function certificateStatus()
768
    {
769
        $query = "SELECT option_value AS cert FROM profile_option  WHERE option_name='eap:ca_file' AND profile_id = ?";        
770
        $result = $this->databaseHandle->exec($query, "i", $this->identifier);
771
        $rows = $result->fetch_all();
772
        $x509 = new \core\common\X509();
773
        $profileStatus = self::CERT_STATUS_OK;
774
        foreach ($rows as $row) {
775
            $encodedCert = $row[0];
776
            $tm = $x509->processCertificate(base64_decode($encodedCert))['full_details']['validTo_time_t']- time();
777
            if ($tm < \config\ConfAssistant::CERT_WARNINGS['expiry_critical']) {
778
                $certStatus = self::CERT_STATUS_ERROR;
779
            } elseif ($tm < \config\ConfAssistant::CERT_WARNINGS['expiry_warning']) {
780
                $certStatus = self::CERT_STATUS_WARN;
781
            } else {
782
                $certStatus = self::CERT_STATUS_OK;
783
            }
784
            $profileStatus = max($profileStatus, $certStatus);
785
        }
786
        return $profileStatus;
787
    }
788
789
    /**
790
     * Checks if the profile has enough information to have something to show to end users. This does not necessarily mean
791
     * that there's a fully configured EAP type - it is sufficient if a redirect has been set for at least one device.
792
     * 
793
     * @return boolean TRUE if enough information for showtime is set; FALSE if not
794
     */
795
    private function readyForShowtime()
796
    {
797
        $properConfig = FALSE;
798
        $attribs = $this->getCollapsedAttributes();
799
        // do we have enough to go live? Check if any of the configured EAP methods is completely configured ...
800
        if (sizeof($this->getEapMethodsinOrderOfPreference(1)) > 0) {
801
            $properConfig = TRUE;
802
        }
803
        // if not, it could still be that general redirect has been set
804
        if (!$properConfig) {
805
            if (isset($attribs['device-specific:redirect'])) {
806
                $properConfig = TRUE;
807
            }
808
            // just a per-device redirect? would be good enough... but this is not actually possible:
809
            // per-device redirects can only be set on the "fine-tuning" page, which is only accessible
810
            // if at least one EAP type is fully configured - which is caught above and makes readyForShowtime TRUE already
811
        }
812
        // do we know at least one SSID to configure, or work with wired? If not, it's not ready...
813
        if (!isset($attribs['media:SSID']) &&
814
                (!isset(\config\ConfAssistant::CONSORTIUM['ssid']) || count(\config\ConfAssistant::CONSORTIUM['ssid']) == 0) &&
815
                !isset($attribs['media:wired'])) {
816
            $properConfig = FALSE;
817
        }
818
        // institutions without a name are not really a corner case we should support
819
        if (!isset($attribs['general:instname'])) {
820
            $properConfig = FALSE;
821
        }
822
        return $properConfig;
823
    }
824
825
    /**
826
     * set the showtime property if prepShowTime says that there is enough info *and* the admin flagged the profile for showing
827
     * 
828
     * @return void
829
     */
830
    public function prepShowtime()
831
    {
832
        $properConfig = $this->readyForShowtime();
833
        $this->databaseHandle->exec("UPDATE profile SET sufficient_config = ".($properConfig ? "TRUE" : "FALSE")." WHERE profile_id = ".$this->identifier);
834
835
        $attribs = $this->getCollapsedAttributes();
836
        // if not enough info to go live, set FALSE
837
        // even if enough info is there, admin has the ultimate say: 
838
        //   if he doesn't want to go live, no further checks are needed, set FALSE as well
839
        if (!$properConfig || !isset($attribs['profile:production']) || (isset($attribs['profile:production']) && $attribs['profile:production'][0] != "on")) {
840
            $this->databaseHandle->exec("UPDATE profile SET showtime = FALSE WHERE profile_id = ?", "i", $this->identifier);
841
            return;
842
        }
843
        $this->databaseHandle->exec("UPDATE profile SET showtime = TRUE WHERE profile_id = ?", "i", $this->identifier);
844
    }
845
846
    /**
847
     * internal helper - some attributes are added by the constructor "ex officio"
848
     * without actual input from the admin. We can streamline their addition in
849
     * this function to avoid duplication.
850
     * 
851
     * @param array $internalAttributes - only names and value
852
     * @return array full attributes with all properties set
853
     */
854
    protected function addInternalAttributes($internalAttributes)
855
    {
856
        // internal attributes share many attribute properties, so condense the generation
857
        $retArray = [];
858
        foreach ($internalAttributes as $attName => $attValue) {
859
            $retArray[] = ["name" => $attName,
860
                "lang" => NULL,
861
                "value" => $attValue,
862
                "level" => Options::LEVEL_PROFILE,
863
                "row_id" => 0,
864
                "flag" => NULL,
865
            ];
866
        }
867
        return $retArray;
868
    }
869
870
    /**
871
     * Retrieves profile attributes stored in the database
872
     * 
873
     * @return array The attributes in one array
874
     */
875
    protected function addDatabaseAttributes()
876
    {
877
        $databaseAttributes = $this->retrieveOptionsFromDatabase("SELECT DISTINCT option_name, option_lang, option_value, row_id
878
                FROM $this->entityOptionTable
879
                WHERE $this->entityIdColumn = ?
880
                AND device_id IS NULL AND eap_method_id = 0
881
                ORDER BY option_name", "Profile");
882
        return $databaseAttributes;
883
    }
884
}
885