Passed
Push — release_2_1 ( a8ee7d...53e78a )
by Tomasz
09:23
created

AbstractProfile::openroamingRedinessTest()   F

Complexity

Conditions 22
Paths 152

Size

Total Lines 117
Code Lines 92

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 92
c 0
b 0
f 0
dl 0
loc 117
rs 3.7333
cc 22
nc 152
nop 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
    const OPENROAMING_ALL_GOOD = 24;
135
    const OPENROAMING_NO_REALM = 17; //n
136
    const OPENROAMING_BAD_SRV = 16; //n
137
    const OPENROAMING_BAD_NAPTR = 10; // w
138
    const OPENROAMING_SOME_BAD_CONNECTIONS = 8; //w
139
    const OPENROAMING_NO_DNSSEC = 8; //w
140
    const OPENROAMING_NO_NAPTR = 3; //e
141
    const OPENROAMING_BAD_NAPTR_RESOLVE = 2; //e
142
    const OPENROAMING_BAD_SRV_RESOLVE = 1; //e
143
    const OPENROAMING_BAD_CONNECTION = 0; //e
144
    
145
    
146
    
147
    
148
    
149
    /**
150
     *  generates a detailed log of which installer was downloaded
151
     * 
152
     * @param int    $idpIdentifier the IdP identifier
153
     * @param int    $profileId     the Profile identifier
154
     * @param string $deviceId      the Device identifier
155
     * @param string $area          the download area (user, silverbullet, admin)
156
     * @param string $lang          the language of the installer
157
     * @param int    $eapType       the EAP type of the installer
158
     * @return void
159
     * @throws Exception
160
     */
161
    protected function saveDownloadDetails($idpIdentifier, $profileId, $deviceId, $area, $lang, $eapType, $openRoaming)
162
    {
163
        if (\config\Master::PATHS['logdir']) {
164
            $file = fopen(\config\Master::PATHS['logdir']."/download_details.log", "a");
165
            if ($file === FALSE) {
166
                throw new Exception("Unable to open file for append: $file");
167
            }
168
            fprintf($file, "%-015s;%d;%d;%s;%s;%s;%d;%d\n", microtime(TRUE), $idpIdentifier, $profileId, $deviceId, $area, $lang, $eapType, $openRoaming);
169
            fclose($file);
170
        }
171
    }
172
173
    /**
174
     * checks if security-relevant parameters have changed
175
     * 
176
     * @param AbstractProfile $old old instantiation of a profile to compare against
177
     * @param AbstractProfile $new new instantiation of a profile 
178
     * @return array there are never any user-induced changes in SB
179
     */
180
    public static function significantChanges($old, $new)
181
    {
182
        $retval = [];
183
        // check if a CA was added
184
        $x509 = new common\X509();
185
        $baselineCA = [];
186
        $baselineCApublicKey = [];
187
        foreach ($old->getAttributes("eap:ca_file") as $oldCA) {
188
            $ca = $x509->processCertificate($oldCA['value']);
189
            $baselineCA[$ca['sha1']] = $ca['name'];
190
            $baselineCApublicKey[$ca['sha1']] = $ca['full_details']['public_key'];
191
        }
192
        // remove the new ones that are identical to the baseline
193
        foreach ($new->getAttributes("eap:ca_file") as $newCA) {
194
            $ca = $x509->processCertificate($newCA['value']);
195
            if (array_key_exists($ca['sha1'], $baselineCA) || $ca['root'] != 1) {
196
                // do nothing; we assume here that SHA1 doesn't clash
197
                continue;
198
            }
199
            // check if a CA with identical DN was added - alert NRO if so
200
            $foundSHA1 = array_search($ca['name'], $baselineCA);
201
            if ($foundSHA1 !== FALSE) {
202
                // but only if the public key does not match
203
                if ($baselineCApublicKey[$foundSHA1] === $ca['full_details']['public_key']) {
204
                    continue;
205
                }
206
                $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'];
207
            } else {
208
                $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";
209
            }
210
        }
211
        // check if a servername was added
212
        $baselineNames = [];
213
        foreach ($old->getAttributes("eap:server_name") as $oldName) {
214
            $baselineNames[] = $oldName['value'];
215
        }
216
        foreach ($new->getAttributes("eap:server_name") as $newName) {
217
            if (!in_array($newName['value'], $baselineNames)) {
218
                $retval[AbstractProfile::SERVERNAME_ADDED] .= "#New server name '".$newName['value']."' added";
219
            }
220
        }
221
        return $retval;
222
    }
223
224
    /**
225
     * Tests OpenRoaming aspects of the profile like DNS settings and server reachibility
226
     * 
227
     * @return array of arrays of the form [['level' => $level, 'explanation' => $explanation, 'reason' => $reason]];
228
     */
229
    public function openroamingRedinessTest() {
230
        // do OpenRoaming initial diagnostic checks
231
        // numbers correspond to RFC7585Tests::OVERALL_LEVEL
232
        $results = [];
233
        $resultLevel = $this::OVERALL_OPENROAMING_LEVEL_GOOD; // assume all is well, degrade if we have concrete findings to suggest otherwise
234
        $tag = "aaa+auth:radius.tls.tcp";
235
        // do we know the realm at all? Notice if not.
236
        if (!isset($this->getAttributes("internal:realm")[0]['value'])) {
237
            $explanation = _("The profile information does not include the realm, so no DNS checks for OpenRoaming can be executed.");
238
            $level = $this::OVERALL_OPENROAMING_LEVEL_NOTE;
239
            $reason = $this::OPENROAMING_NO_REALM;
240
            $results[] = ['level' => $level, 'explanation' => $explanation, 'reason' => $reason];
241
            $resultLevel = min([$resultLevel, $level]);
242
        } else {
243
            $dnsChecks = new \core\diag\RFC7585Tests($this->getAttributes("internal:realm")[0]['value'], $tag);
244
            $relevantNaptrRecords = $dnsChecks->relevantNAPTR();
245
            if ($relevantNaptrRecords <= 0) {
246
                $explanation = _("There is no relevant DNS NAPTR record ($tag) for this realm. OpenRoaming will not work.");
247
                $reason = $this::OPENROAMING_NO_NAPTR;
248
                $level = $this::OVERALL_OPENROAMING_LEVEL_ERROR;
249
                $results[] = ['level' => $level, 'explanation' => $explanation, 'reason' => $reason];
250
                $resultLevel = min([$resultLevel, $level]);
251
            } else {
252
                $recordCompliance = $dnsChecks->relevantNAPTRcompliance();
253
                if ($recordCompliance != \core\diag\AbstractTest::RETVAL_OK) {
254
                    $explanation = _("The DNS NAPTR record ($tag) for this realm is not syntax conform. OpenRoaming will likely not work.");
255
                    $reason = $this::OPENROAMING_BAD_NAPTR;
256
                    $level = $this::OVERALL_OPENROAMING_LEVEL_WARN;
257
                    $results[] = ['level' => $level, 'explanation' => $explanation, 'reason' => $reason];
258
                    $resultLevel = min([$resultLevel, $level]);
259
                }
260
                // check if target is the expected one, if set by NRO
261
                foreach ($this->fedAttributes as $attr) {
262
                    if ($attr['name'] === 'fed:openroaming_customtarget') {
263
                        $customText = $attr['value'];
264
                    } else {
265
                        $customText = '';
266
                    }
267
                }
268
                if ($customText !== '') {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $customText seems to be defined by a foreach iteration on line 261. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
269
                    foreach ($dnsChecks->NAPTR_records as $orpointer) {
270
                        if ($orpointer["replacement"] != $customText) {
271
                            $explanation = _("The SRV target of an OpenRoaming NAPTR record is unexpected.");
272
                            $reason = $this::OPENROAMING_BAD_SRV;
273
                            $level = $this::OVERALL_OPENROAMING_LEVEL_NOTE;
274
                            $results[] = ['level' => $level, 'explanation' => $explanation, 'reason' => $reason];
275
                            $resultLevel = min([$resultLevel, $level]);
276
                        }
277
                    }
278
                }
279
                $srvResolution = $dnsChecks->relevantNAPTRsrvResolution();
280
                $hostnameResolution = $dnsChecks->relevantNAPTRhostnameResolution();
281
282
                if ($srvResolution <= 0) {
283
                    $explanation = _("The DNS SRV target for NAPTR $tag does not resolve. OpenRoaming will not work.");
284
                    $level = $this::OVERALL_OPENROAMING_LEVEL_ERROR;
285
                    $reason = $this::OPENROAMING_BAD_NAPTR_RESOLVE;
286
                    $results[] = ['level' => $level, 'explanation' => $explanation, 'reason' => $reason];
287
                    $resultLevel = min([$resultLevel, $this::OVERALL_OPENROAMING_LEVEL_ERROR]);
288
                } elseif ($hostnameResolution <= 0) {
289
                    $explanation = _("The DNS hostnames in the SRV records do not resolve to actual host IPs. OpenRoaming will not work.");
290
                    $level = $this::OVERALL_OPENROAMING_LEVEL_ERROR;
291
                    $reason = $this::OPENROAMING_BAD_SRV_RESOLVE;
292
                    $results[] = ['level' => $level, 'explanation' => $explanation, 'reason' => $reason];
293
                    $resultLevel = min([$resultLevel, $level]);
294
                }
295
                // connect to all IPs we found and see if they are really an OpenRoaming server
296
                $allHostsOkay = TRUE;
297
                $oneHostOkay = FALSE;
298
                $testCandidates = [];
299
                foreach ($dnsChecks->NAPTR_hostname_records as $oneServer) {
300
                    $testCandidates[$oneServer['hostname']][] = ($oneServer['family'] == "IPv4" ? $oneServer['IP'] : "[".$oneServer['IP']."]").":".$oneServer['port'];
301
                }
302
                foreach ($testCandidates as $oneHost => $listOfIPs) {
303
                    $connectionTests = new \core\diag\RFC6614Tests(array_values($listOfIPs), $oneHost, "openroaming");
304
                    // for now (no OpenRoaming client certs available) only run server-side tests
305
                    foreach ($listOfIPs as $oneIP) {
306
                        $connectionResult = $connectionTests->cApathCheck($oneIP);
307
                        if ($connectionResult != \core\diag\AbstractTest::RETVAL_OK || ( isset($connectionTests->TLS_CA_checks_result['cert_oddity']) && count($connectionTests->TLS_CA_checks_result['cert_oddity']) > 0)) {
308
                            $allHostsOkay = FALSE;
309
                        } else {
310
                            $oneHostOkay = TRUE;
311
                        }
312
                    }
313
                }
314
                if (!$allHostsOkay) {
315
                    if (!$oneHostOkay) {
316
                        $explanation = _("When connecting to the discovered OpenRoaming endpoints, they all had errors. OpenRoaming will likely not work.");
317
                        $level = $this::OVERALL_OPENROAMING_LEVEL_ERROR;
318
                        $reason = $this::OPENROAMING_BAD_CONNECTION;
319
                        $results[] = ['level' => $level, 'explanation' => $explanation, 'reason' => $reason];
320
                        $resultLevel = min([$resultLevel, $level]);
321
                    } else {
322
                        $explanation = _("When connecting to the discovered OpenRoaming endpoints, only a subset of endpoints had no errors.");
323
                        $level = $this::OVERALL_OPENROAMING_LEVEL_WARN;
324
                        $reason = $this::OPENROAMING_SOME_BAD_CONNECTIONS;
325
                        $results[] = ['level' => $level, 'explanation' => $explanation, 'reason' => $reason];
326
                        $resultLevel = min([$resultLevel, $level]);
327
                    }
328
                }
329
            }
330
        }
331
        if (!$dnsChecks->allResponsesSecure) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $dnsChecks does not seem to be defined for all execution paths leading up to this point.
Loading history...
332
            $explanation = _("At least one DNS response was NOT secured using DNSSEC. OpenRoaming ANPs may refuse to connect to the endpoint.");
333
            $level = $this::OVERALL_OPENROAMING_LEVEL_WARN;
334
            $reason = $this::OPENROAMING_NO_DNSSEC;
335
            $results[] = ['level' => $level, 'explanation' => $explanation, 'reason' => $reason];
336
            $resultLevel = min([$resultLevel, $level]);
337
        }
338
        if ($resultLevel == $this::OVERALL_OPENROAMING_LEVEL_GOOD) {
339
            $explanation = _("Initial diagnostics regarding the DNS part of OpenRoaming (including DNSSEC) were successful.");
340
            $level = $this::OVERALL_OPENROAMING_LEVEL_GOOD;
341
            $reason = $this::OPENROAMING_ALL_GOOD;
342
            $results = [['level' => $level, 'explanation' => $explanation, 'reason' => $reason]];
343
        }               
344
        $this->setOpenRoamingReadinessInfo($resultLevel);
345
        return $results;
346
    }
347
    
348
    /**
349
     * Takes note of the OpenRoaming participation and conformance level
350
     * 
351
     * @param int $level the readiness level, as determined by RFC7585Tests
352
     * @return void
353
     */
354
    public function setOpenRoamingReadinessInfo(int $level)
355
    {
356
            $this->databaseHandle->exec("UPDATE profile SET openroaming = ? WHERE profile_id = ?", "ii", $level, $this->identifier);
357
    }
358
359
    /**
360
     * each profile has supported EAP methods, so get this from DB, Silver Bullet has one
361
     * static EAP method.
362
     * 
363
     * @return array list of supported EAP methods
364
     */
365
    protected function fetchEAPMethods()
366
    {
367
        $eapMethod = $this->databaseHandle->exec("SELECT eap_method_id 
368
                                                        FROM supported_eap supp 
369
                                                        WHERE supp.profile_id = $this->identifier 
370
                                                        ORDER by preference");
371
        $eapTypeArray = [];
372
        // SELECTs never return a boolean, it's always a resource
373
        while ($eapQuery = (mysqli_fetch_object(/** @scrutinizer ignore-type */ $eapMethod))) {
374
            $eaptype = new common\EAP($eapQuery->eap_method_id);
375
            $eapTypeArray[] = $eaptype;
376
        }
377
        $this->loggerInstance->debug(4, "This profile supports the following EAP types:\n"./** @scrutinizer ignore-type */ print_r($eapTypeArray, true));
378
        return $eapTypeArray;
379
    }
380
381
    /**
382
     * Class constructor for existing profiles (use IdP::newProfile() to actually create one). Retrieves all attributes and 
383
     * supported EAP types from the DB and stores them in the priv_ arrays.
384
     * 
385
     * sub-classes need to set the property $realm, $name themselves!
386
     * 
387
     * @param int $profileIdRaw identifier of the profile in the DB
388
     * @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.
389
     * @throws Exception
390
     */
391
    public function __construct($profileIdRaw, $idpObject = NULL)
392
    {
393
        $this->databaseType = "INST";
394
        parent::__construct(); // we now have access to our INST database handle and logging
395
        $handle = DBConnection::handle("FRONTEND");
396
        if ($handle instanceof DBConnection) {
397
            $this->frontendHandle = $handle;
398
        } else {
399
            throw new Exception("This database type is never an array!");
400
        }
401
        $profile = $this->databaseHandle->exec("SELECT inst_id FROM profile WHERE profile_id = ?", "i", $profileIdRaw);
402
        // SELECT always yields a resource, never a boolean
403
        if ($profile->num_rows == 0) {
404
            $this->loggerInstance->debug(2, "Profile $profileIdRaw not found in database!\n");
405
            throw new Exception("Profile $profileIdRaw not found in database!");
406
        }
407
        $this->identifier = $profileIdRaw;
408
        $profileQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $profile);
409
        if (!($idpObject instanceof IdP)) {
410
            $this->institution = $profileQuery->inst_id;
411
            $idp = new IdP($this->institution);
412
        } else {
413
            $idp = $idpObject;
414
            $this->institution = $idp->identifier;
415
        }
416
417
        $this->instName = $idp->name;
418
        $this->idpNumberOfProfiles = $idp->profileCount();
419
        $this->idpAttributes = $idp->getAttributes();
420
        $fedObject = new Federation($idp->federation);
421
        $this->fedAttributes = $fedObject->getAttributes();
422
        $this->loggerInstance->debug(4, "--- END Constructing new AbstractProfile object ... ---\n");
423
    }
424
425
    /**
426
     * find a profile, given its realm
427
     * 
428
     * @param string $realm the realm for which we are trying to find a profile
429
     * @return int|false the profile identifier, if any
430
     */
431
    public static function profileFromRealm($realm)
432
    {
433
        // static, need to create our own handle
434
        $handle = DBConnection::handle("INST");
435
        $execQuery = $handle->exec("SELECT profile_id FROM profile WHERE realm LIKE '%@$realm'");
436
        // a SELECT query always yields a resource, not a boolean
437
        if ($profileIdQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $execQuery)) {
438
            return $profileIdQuery->profile_id;
439
        }
440
        return FALSE;
441
    }
442
443
    /**
444
     * Constructs the outer ID which should be used during realm tests. Obviously
445
     * can only do something useful if the realm is known to the system.
446
     * 
447
     * @return string the outer ID to use for realm check operations
448
     * @throws Exception
449
     */
450
    public function getRealmCheckOuterUsername()
451
    {
452
        $realm = $this->getAttributes("internal:realm")[0]['value'] ?? FALSE;
453
        if ($realm == FALSE) { // we can't really return anything useful here
454
            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.");
455
        }
456
        if (count($this->getAttributes("internal:checkuser_outer")) > 0) {
457
            // we are supposed to use a specific outer username for checks, 
458
            // which is different from the outer username we put into installers
459
            return $this->getAttributes("internal:checkuser_value")[0]['value']."@".$realm;
460
        }
461
        if (count($this->getAttributes("internal:use_anon_outer")) > 0) {
462
            // no special check username, but there is an anon outer ID for
463
            // installers - so let's use that one
464
            return $this->getAttributes("internal:anon_local_value")[0]['value']."@".$realm;
465
        }
466
        // okay, no guidance on outer IDs at all - but we need *something* to
467
        // test with for the RealmChecks. So:
468
        return "@".$realm;
469
    }
470
471
    /**
472
     * update the last_changed timestamp for this profile
473
     * 
474
     * @return void
475
     */
476
    public function updateFreshness()
477
    {
478
        $this->databaseHandle->exec("UPDATE profile SET last_change = CURRENT_TIMESTAMP WHERE profile_id = $this->identifier");
479
    }
480
481
    /**
482
     * gets the last-modified timestamp (useful for caching "dirty" check)
483
     * 
484
     * @return string the date in string form, as returned by SQL
485
     */
486
    public function getFreshness()
487
    {
488
        $execLastChange = $this->databaseHandle->exec("SELECT last_change FROM profile WHERE profile_id = $this->identifier");
489
        // SELECT always returns a resource, never a boolean
490
        if ($freshnessQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $execLastChange)) {
491
            return $freshnessQuery->last_change;
492
        }
493
    }
494
    /**
495
     * tests if the configurator needs to be regenerated
496
     * returns the configurator path or NULL if regeneration is required
497
     */
498
    /**
499
     * This function tests if the configurator needs to be regenerated 
500
     * (properties of the Profile may have changed since the last configurator 
501
     * generation).
502
     * SilverBullet will always return NULL here because all installers are new!
503
     * 
504
     * @param string $device device ID to check
505
     * @return mixed a string with the path to the configurator download, or NULL if it needs to be regenerated
506
     */
507
508
    /**
509
     * This function tests if the configurator needs to be regenerated (properties of the Profile may have changed since the last configurator generation).
510
     * 
511
     * @param string $device device ID to check
512
     * @return mixed a string with the path to the configurator download, or NULL if it needs to be regenerated
513
     */
514
    public function testCache($device, $openRoaming)
515
    {
516
        $returnValue = ['cache' => NULL, 'mime' => NULL];
517
        $lang = $this->languageInstance->getLang();
518
        $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);
519
        // SELECT queries always return a resource, not a boolean
520
        if ($result && $cache = mysqli_fetch_object(/** @scrutinizer ignore-type */ $result)) {
521
            $execUpdate = $this->databaseHandle->exec("SELECT UNIX_TIMESTAMP(last_change) AS last_change FROM profile WHERE profile_id = $this->identifier");
522
            // SELECT queries always return a resource, not a boolean
523
            if ($lastChange = mysqli_fetch_object(/** @scrutinizer ignore-type */ $execUpdate)->last_change) {
524
                if ($lastChange < $cache->tm) {
525
                    $this->loggerInstance->debug(4, "Installer cached:$cache->download_path\n");
526
                    $returnValue = ['cache' => $cache->download_path, 'mime' => $cache->mime];
527
                }
528
            }
529
        }
530
        return $returnValue;
531
    }
532
533
    /**
534
     * Updates database with new installer location. Actually does stuff when
535
     * caching is possible; is a noop if not
536
     * 
537
     * @param string $device         the device identifier string
538
     * @param string $path           the path where the new installer can be found
539
     * @param string $mime           the mime type of the new installer
540
     * @param int    $integerEapType the inter-representation of the EAP type that is configured in this installer
541
     * @return void
542
     */
543
    abstract public function updateCache($device, $path, $mime, $integerEapType, $openRoaming);
544
545
    /** Toggle anonymous outer ID support.
546
     *
547
     * @param boolean $shallwe TRUE to enable outer identities (needs valid $realm), FALSE to disable
548
     * @return void
549
     */
550
    abstract public function setAnonymousIDSupport($shallwe);
551
552
    /**
553
     * Log a new download for our stats
554
     * 
555
     * @param string $device the device id string
556
     * @param string $area   either admin or user
557
     * @return boolean TRUE if incrementing worked, FALSE if not
558
     */
559
    public function incrementDownloadStats($device, $area, $openRoaming)
560
    {
561
        if ($area == "admin" || $area == "user" || $area == "silverbullet") {
562
            $lang = $this->languageInstance->getLang();
563
            $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);
564
            // get eap_type from the downloads table
565
            $eapTypeQuery = $this->frontendHandle->exec("SELECT eap_type FROM downloads WHERE profile_id = ? AND device_id = ? AND lang = ?", "iss", $this->identifier, $device, $lang);
566
            // SELECT queries always return a resource, not a boolean
567
            if (!$eapTypeQuery || !$eapO = mysqli_fetch_object(/** @scrutinizer ignore-type */ $eapTypeQuery)) {
568
                $this->loggerInstance->debug(2, "Error getting EAP_type from the database\n");
569
            } else {
570
                if ($eapO->eap_type == NULL) {
571
                    $this->loggerInstance->debug(2, "EAP_type not set in the database\n");
572
                } else {
573
                    $this->saveDownloadDetails($this->institution, $this->identifier, $device, $area, $this->languageInstance->getLang(), $eapO->eap_type, $openRoaming);
574
                }
575
            }
576
            return TRUE;
577
        }
578
        return FALSE;
579
    }
580
581
    /**
582
     * Retrieve current download stats from database, either for one specific device or for all devices
583
     * 
584
     * @param string $device the device id string
585
     * @return mixed user downloads of this profile; if device is given, returns the counter as int, otherwise an array with devicename => counter
586
     */
587
    public function getUserDownloadStats($device = NULL)
588
    {
589
        $columnName = "downloads_user";
590
        if ($this instanceof \core\ProfileSilverbullet) {
591
            $columnName = "downloads_silverbullet";
592
        }
593
        $returnarray = [];
594
        $numbers = $this->frontendHandle->exec("SELECT device_id, SUM($columnName) AS downloads_user FROM downloads WHERE profile_id = ? GROUP BY device_id", "i", $this->identifier);
595
        // SELECT queries always return a resource, not a boolean
596
        while ($statsQuery = mysqli_fetch_object(/** @scrutinizer ignore-type */ $numbers)) {
597
            $returnarray[$statsQuery->device_id] = $statsQuery->downloads_user;
598
        }
599
        if ($device !== NULL) {
600
            if (isset($returnarray[$device])) {
601
                return $returnarray[$device];
602
            }
603
            return 0;
604
        }
605
        // we should pretty-print the device names
606
        $finalarray = [];
607
        $devlist = \devices\Devices::listDevices($this->identifier);
608
        foreach ($returnarray as $devId => $count) {
609
            if (isset($devlist[$devId])) {
610
                $finalarray[$devlist[$devId]['display']] = $count;
611
            }
612
        }
613
        return $finalarray;
614
    }
615
616
    /**
617
     * Deletes the profile from database and uninstantiates itself.
618
     * Works fine also for Silver Bullet; the first query will simply do nothing
619
     * because there are no stored options
620
     * 
621
     * @return void
622
     */
623
    public function destroy()
624
    {
625
        $this->databaseHandle->exec("DELETE FROM profile_option WHERE profile_id = $this->identifier");
626
        $this->databaseHandle->exec("DELETE FROM supported_eap WHERE profile_id = $this->identifier");
627
        $this->databaseHandle->exec("DELETE FROM profile WHERE profile_id = $this->identifier");
628
    }
629
630
    /**
631
     * Specifies the realm of this profile.
632
     * 
633
     * Forcefully type-hinting $realm parameter to string - Scrutinizer seems to
634
     * think that it can alternatively be an array<integer,?> which looks like a
635
     * false positive. If there really is an issue, let PHP complain about it at
636
     * runtime.
637
     * 
638
     * @param string $realm the realm (potentially with the local@ part that should be used for anonymous identities)
639
     * @return void
640
     */
641
    public function setRealm(string $realm)
642
    {
643
        $this->databaseHandle->exec("UPDATE profile SET realm = ? WHERE profile_id = ?", "si", $realm, $this->identifier);
644
        $this->realm = $realm;
645
    }
646
647
    /**
648
     * register new supported EAP method for this profile
649
     *
650
     * @param \core\common\EAP $type       The EAP Type, as defined in class EAP
651
     * @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.
652
     * @return void
653
     */
654
    public function addSupportedEapMethod(\core\common\EAP $type, $preference)
655
    {
656
        $eapInt = $type->getIntegerRep();
657
        $this->databaseHandle->exec("INSERT INTO supported_eap (profile_id, eap_method_id, preference) VALUES (?, ?, ?)", "iii", $this->identifier, $eapInt, $preference);
658
        $this->updateFreshness();
659
    }
660
661
    /**
662
     * Produces an array of EAP methods supported by this profile, ordered by preference
663
     * 
664
     * @param int $completeOnly if set and non-zero limits the output to methods with complete information
665
     * @return array list of EAP methods, (in object representation)
666
     */
667
    public function getEapMethodsinOrderOfPreference($completeOnly = 0)
668
    {
669
        $temparray = [];
670
671
        if ($completeOnly == 0) {
672
            return $this->privEaptypes;
673
        }
674
        foreach ($this->privEaptypes as $type) {
675
            if ($this->isEapTypeDefinitionComplete($type) === true) {
676
                $temparray[] = $type;
677
            }
678
        }
679
        return($temparray);
680
    }
681
682
    /**
683
     * Performs a sanity check for a given EAP type - did the admin submit enough information to create installers for him?
684
     * 
685
     * @param common\EAP $eaptype the EAP type
686
     * @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
687
     */
688
    public function isEapTypeDefinitionComplete($eaptype)
689
    {
690
        if ($eaptype->needsServerCACert() && $eaptype->needsServerName()) {
691
            $missing = [];
692
            // silverbullet needs a support email address configured
693
            if ($eaptype->getIntegerRep() == common\EAP::INTEGER_SILVERBULLET && count($this->getAttributes("support:email")) == 0) {
694
                return ["support:email"];
695
            }
696
            $cnOption = $this->getAttributes("eap:server_name"); // cannot be set per device or eap type
697
            $caOption = $this->getAttributes("eap:ca_file"); // cannot be set per device or eap type
698
699
            if (count($caOption) > 0 && count($cnOption) > 0) {// see if we have at least one root CA cert
700
                foreach ($caOption as $oneCa) {
701
                    $x509 = new \core\common\X509();
702
                    $caParsed = $x509->processCertificate($oneCa['value']);
703
                    if ($caParsed['root'] == 1) {
704
                        return TRUE;
705
                    }
706
                }
707
                $missing[] = "eap:ca_file";
708
            }
709
            if (count($caOption) == 0) {
710
                $missing[] = "eap:ca_file";
711
            }
712
            if (count($cnOption) == 0) {
713
                $missing[] = "eap:server_name";
714
            }
715
            if (count($missing) == 0) {
716
                return TRUE;
717
            }
718
            return $missing;
719
        }
720
        return TRUE;
721
    }
722
723
    /**
724
     * list all devices marking their availabiblity and possible redirects
725
     *
726
     * @return array of device ids display names and their status
727
     */
728
    public function listDevices()
729
    {
730
        $returnarray = [];
731
        $redirect = $this->getAttributes("device-specific:redirect"); // this might return per-device ones or the general one
732
        // if it was a general one, we are done. Find out if there is one such
733
        // which has device = NULL
734
        $generalRedirect = NULL;
735
        foreach ($redirect as $index => $oneRedirect) {
736
            if ($oneRedirect["level"] == Options::LEVEL_PROFILE) {
737
                $generalRedirect = $index;
738
            }
739
        }
740
        if ($generalRedirect !== NULL) { // could be index 0
741
            return [['id' => '0', 'redirect' => $redirect[$generalRedirect]['value']]];
742
        }
743
        $preferredEap = $this->getEapMethodsinOrderOfPreference(1);
744
        $eAPOptions = [];
745
        if (count($this->getAttributes("media:openroaming")) == 1 && $this->getAttributes("media:openroaming")[0]['value'] == 'always-preagreed') {
746
            $orAlways = 1;
747
        } else {
748
            $orAlways = 0;
749
        }
750
        
751
        foreach (\devices\Devices::listDevices($this->identifier, $orAlways) as $deviceIndex => $deviceProperties) {
752
            $factory = new DeviceFactory($deviceIndex);
753
            $dev = $factory->device;
754
            // find the attribute pertaining to the specific device
755
            $group = '';
756
            $redirectUrl = 0;
757
            $redirects = [];
758
            foreach ($redirect as $index => $oneRedirect) {
759
                if ($oneRedirect["device"] == $deviceIndex) {
760
                    $redirects[] = $oneRedirect;
761
                }
762
            }
763
            if (count($redirects) > 0) {
764
                $redirectUrl = $this->languageInstance->getLocalisedValue($redirects);
765
            }
766
            $devStatus = self::AVAILABLE;
767
            $message = 0;
768
            if (isset($deviceProperties['options']) && isset($deviceProperties['options']['message']) && $deviceProperties['options']['message']) {
769
                $message = $deviceProperties['options']['message'];
770
            }
771
            if (isset($deviceProperties['group'])) {
772
                $group = $deviceProperties['group'];
773
            }
774
            $eapCustomtext = 0;
775
            $deviceCustomtext = 0;
776
            $geteduroam = 0;
777
            if ($redirectUrl === 0) {
778
                if (isset($deviceProperties['options']) && isset($deviceProperties['options']['redirect']) && $deviceProperties['options']['redirect']) {
779
                    $devStatus = self::HIDDEN;
780
                } else {
781
                    $dev->calculatePreferredEapType($preferredEap);
782
                    $eap = $dev->selectedEap;
783
                    if (count($eap) > 0) {
784
                        if (isset($eAPOptions["eap-specific:customtext"][serialize($eap)])) {
785
                            $eapCustomtext = $eAPOptions["eap-specific:customtext"][serialize($eap)];
786
                        } else {
787
                            // fetch customtexts from method-level attributes
788
                            $eapCustomtext = 0;
789
                            $customTextAttributes = [];
790
                            $attributeList = $this->getAttributes("eap-specific:customtext"); // eap-specific attributes always have the array index 'eapmethod' set
791
                            foreach ($attributeList as $oneAttribute) {
792
                                if ($oneAttribute["eapmethod"] == $eap) {
793
                                    $customTextAttributes[] = $oneAttribute;
794
                                }
795
                            }
796
                            if (count($customTextAttributes) > 0) {
797
                                $eapCustomtext = $this->languageInstance->getLocalisedValue($customTextAttributes);
798
                            }
799
                            $eAPOptions["eap-specific:customtext"][serialize($eap)] = $eapCustomtext;
800
                        }
801
                        // fetch customtexts for device
802
                        $customTextAttributes = [];
803
                        $attributeList = $this->getAttributes("device-specific:customtext");
804
                        foreach ($attributeList as $oneAttribute) {
805
                            if ($oneAttribute["device"] == $deviceIndex) { // device-specific attributes always have the array index "device" set
806
                                $customTextAttributes[] = $oneAttribute;
807
                            }
808
                        }
809
                        $deviceCustomtext = $this->languageInstance->getLocalisedValue($customTextAttributes);
810
                    } else {
811
                        $devStatus = self::UNAVAILABLE;
812
                    }
813
                    $geteduroamOpts = $this->getAttributes("device-specific:geteduroam");
814
                    foreach ($geteduroamOpts as $dev) {
815
                        if ($dev['device'] == $deviceIndex) {
816
                            $geteduroam = $dev['value'] == 'on' ? 1 : 0;
817
                        }
818
                    }
819
                }
820
            }
821
            $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];
822
        }
823
        return $returnarray;
824
    }
825
826
    /**
827
     * prepare profile attributes for device modules
828
     * Gets profile attributes taking into account the most specific level on which they may be defined
829
     * as well as the chosen language.
830
     * can be called with an optional $eap argument
831
     * 
832
     * @param array $eap if specified, retrieves all attributes except those not pertaining to the given EAP type
833
     * @return array list of attributes in collapsed style (index is the attrib name, value is an array of different values)
834
     */
835
    public function getCollapsedAttributes($eap = [])
836
    {
837
        $collapsedList = [];
838
        foreach ($this->getAttributes() as $attribute) {
839
            // filter out eap-level attributes not pertaining to EAP type $eap
840
            if (count($eap) > 0 && isset($attribute['eapmethod']) && $attribute['eapmethod'] != 0 && $attribute['eapmethod'] != $eap) {
841
                continue;
842
            }
843
            // create new array indexed by attribute name
844
            
845
            if (isset($attribute['device'])) {
846
                $collapsedList[$attribute['name']][$attribute['device']][] = $attribute['value'];
847
            } else {
848
                $collapsedList[$attribute['name']][] = $attribute['value'];
849
            } 
850
            // and keep all language-variant names in a separate sub-array
851
            if ($attribute['flag'] == "ML") {
852
                $collapsedList[$attribute['name']]['langs'][$attribute['lang']] = $attribute['value'];
853
            }
854
        }
855
        // once we have the final list, populate the respective "best-match"
856
        // language to choose for the ML attributes
857
858
        foreach ($collapsedList as $attribName => $valueArray) {
859
            if (isset($valueArray['langs'])) { // we have at least one language-dependent name in this attribute
860
                // for printed names on screen:
861
                // assign to exact match language, fallback to "default" language, fallback to English, fallback to whatever comes first in the list
862
                $collapsedList[$attribName][0] = $valueArray['langs'][$this->languageInstance->getLang()] ?? $valueArray['langs']['C'] ?? $valueArray['langs']['en'] ?? array_shift($valueArray['langs']);
863
                // for names usable in filesystems (closer to good old ASCII...)
864
                // prefer English, otherwise the "default" language, otherwise the same that we got above
865
                $collapsedList[$attribName][1] = $valueArray['langs']['en'] ?? $valueArray['langs']['C'] ?? $collapsedList[$attribName][0];
866
            }
867
        }
868
        return $collapsedList;
869
    }
870
871
    const READINESS_LEVEL_NOTREADY = 0;
872
    const READINESS_LEVEL_SUFFICIENTCONFIG = 1;
873
    const READINESS_LEVEL_SHOWTIME = 2;
874
    const CERT_STATUS_OK = 0;
875
    const CERT_STATUS_WARN = 1;
876
    const CERT_STATUS_ERROR = 2;
877
    
878
879
    /**
880
     * Does the profile contain enough information to generate installers with
881
     * it? Silverbullet will always return TRUE; RADIUS profiles need to do some
882
     * heavy lifting here.
883
     * 
884
     * @return int one of the constants above which tell if enough info is set to enable installers
885
     */
886
    public function readinessLevel()
887
    {
888
        $result = $this->databaseHandle->exec("SELECT sufficient_config, showtime FROM profile WHERE profile_id = ?", "i", $this->identifier);
889
        // SELECT queries always return a resource, not a boolean
890
        $configQuery = mysqli_fetch_row(/** @scrutinizer ignore-type */ $result);
891
        if ($configQuery[0] == "0") {
892
            return self::READINESS_LEVEL_NOTREADY;
893
        }
894
        // at least fully configured, if not showtime!
895
        if ($configQuery[1] == "0") {
896
            return self::READINESS_LEVEL_SUFFICIENTCONFIG;
897
        }
898
        return self::READINESS_LEVEL_SHOWTIME;
899
    }
900
901
    /**
902
     * Checks all profile certificates validity periods comparing to the pre-defined
903
     * thresholds and returns the most critical status.
904
     * 
905
     * @return int - one of constants defined in this profile
906
     */
907
    public function certificateStatus()
908
    {
909
        $query = "SELECT option_value AS cert FROM profile_option  WHERE option_name='eap:ca_file' AND profile_id = ?";        
910
        $result = $this->databaseHandle->exec($query, "i", $this->identifier);
911
        $rows = $result->fetch_all();
912
        $x509 = new \core\common\X509();
913
        $profileStatus = self::CERT_STATUS_OK;
914
        foreach ($rows as $row) {
915
            $encodedCert = $row[0];
916
            $tm = $x509->processCertificate(base64_decode($encodedCert))['full_details']['validTo_time_t']- time();
917
            if ($tm < \config\ConfAssistant::CERT_WARNINGS['expiry_critical']) {
918
                $certStatus = self::CERT_STATUS_ERROR;
919
            } elseif ($tm < \config\ConfAssistant::CERT_WARNINGS['expiry_warning']) {
920
                $certStatus = self::CERT_STATUS_WARN;
921
            } else {
922
                $certStatus = self::CERT_STATUS_OK;
923
            }
924
            $profileStatus = max($profileStatus, $certStatus);
925
        }
926
        return $profileStatus;
927
    }
928
929
    /**
930
     * Checks if the profile has enough information to have something to show to end users. This does not necessarily mean
931
     * that there's a fully configured EAP type - it is sufficient if a redirect has been set for at least one device.
932
     * 
933
     * @return boolean TRUE if enough information for showtime is set; FALSE if not
934
     */
935
    private function readyForShowtime()
936
    {
937
        $properConfig = FALSE;
938
        $attribs = $this->getCollapsedAttributes();
939
        // do we have enough to go live? Check if any of the configured EAP methods is completely configured ...
940
        if (sizeof($this->getEapMethodsinOrderOfPreference(1)) > 0) {
941
            $properConfig = TRUE;
942
        }
943
        // if not, it could still be that general redirect has been set
944
        if (!$properConfig) {
945
            if (isset($attribs['device-specific:redirect'])) {
946
                $properConfig = TRUE;
947
            }
948
            // just a per-device redirect? would be good enough... but this is not actually possible:
949
            // per-device redirects can only be set on the "fine-tuning" page, which is only accessible
950
            // if at least one EAP type is fully configured - which is caught above and makes readyForShowtime TRUE already
951
        }
952
        // do we know at least one SSID to configure, or work with wired? If not, it's not ready...
953
        if (!isset($attribs['media:SSID']) &&
954
                (!isset(\config\ConfAssistant::CONSORTIUM['ssid']) || count(\config\ConfAssistant::CONSORTIUM['ssid']) == 0) &&
955
                !isset($attribs['media:wired'])) {
956
            $properConfig = FALSE;
957
        }
958
        // institutions without a name are not really a corner case we should support
959
        if (!isset($attribs['general:instname'])) {
960
            $properConfig = FALSE;
961
        }
962
        return $properConfig;
963
    }
964
965
    /**
966
     * set the showtime property if prepShowTime says that there is enough info *and* the admin flagged the profile for showing
967
     * 
968
     * @return void
969
     */
970
    public function prepShowtime()
971
    {
972
        $properConfig = $this->readyForShowtime();
973
        $this->databaseHandle->exec("UPDATE profile SET sufficient_config = ".($properConfig ? "TRUE" : "FALSE")." WHERE profile_id = ".$this->identifier);
974
975
        $attribs = $this->getCollapsedAttributes();
976
        // if not enough info to go live, set FALSE
977
        // even if enough info is there, admin has the ultimate say: 
978
        //   if he doesn't want to go live, no further checks are needed, set FALSE as well
979
        if (!$properConfig || !isset($attribs['profile:production']) || (isset($attribs['profile:production']) && $attribs['profile:production'][0] != "on")) {
980
            $this->databaseHandle->exec("UPDATE profile SET showtime = FALSE WHERE profile_id = ?", "i", $this->identifier);
981
            return;
982
        }
983
        $this->databaseHandle->exec("UPDATE profile SET showtime = TRUE WHERE profile_id = ?", "i", $this->identifier);
984
    }
985
986
    /**
987
     * internal helper - some attributes are added by the constructor "ex officio"
988
     * without actual input from the admin. We can streamline their addition in
989
     * this function to avoid duplication.
990
     * 
991
     * @param array $internalAttributes - only names and value
992
     * @return array full attributes with all properties set
993
     */
994
    protected function addInternalAttributes($internalAttributes)
995
    {
996
        // internal attributes share many attribute properties, so condense the generation
997
        $retArray = [];
998
        foreach ($internalAttributes as $attName => $attValue) {
999
            $retArray[] = ["name" => $attName,
1000
                "lang" => NULL,
1001
                "value" => $attValue,
1002
                "level" => Options::LEVEL_PROFILE,
1003
                "row_id" => 0,
1004
                "flag" => NULL,
1005
            ];
1006
        }
1007
        return $retArray;
1008
    }
1009
1010
    /**
1011
     * Retrieves profile attributes stored in the database
1012
     * 
1013
     * @return array The attributes in one array
1014
     */
1015
    protected function addDatabaseAttributes()
1016
    {
1017
        $databaseAttributes = $this->retrieveOptionsFromDatabase("SELECT DISTINCT option_name, option_lang, option_value, row_id
1018
                FROM $this->entityOptionTable
1019
                WHERE $this->entityIdColumn = ?
1020
                AND device_id IS NULL AND eap_method_id = 0
1021
                ORDER BY option_name", "Profile");
1022
        return $databaseAttributes;
1023
    }
1024
}
1025