Test Setup Failed
Push — master ( 484f56...c5ec01 )
by Tomasz
12:57 queued 11s
created

SanityTests::testConfigConstants()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 14
c 0
b 0
f 0
dl 0
loc 21
rs 9.7998
cc 4
nc 6
nop 0
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
 * 
25
 * 
26
 * This is the definition of the CAT class implementing various configuration
27
 * tests. 
28
 * Each test is implemented as a priviate method which needs to be named "test_name_test".
29
 * The test returns the results by calling the testReturn method, this passing the return
30
 * code and the explanatory message. Multiple calls to testReturn are allowed.
31
 *
32
 * An individual test can be run by the "test" method which takes the test name as an argument
33
 * multiple tests should be run by the run_all_tests method which takes an array as an argument
34
 * see method descriptions for more information.
35
 * 
36
 * The results of the tests are passed within the $test_result array
37
 *
38
 * Some configuration of this class is required, see further down.
39
 * @author Stefan Winter <[email protected]>
40
 * @author Tomasz Wolniewicz <[email protected]>
41
 *
42
 * @license see LICENSE file in root directory
43
 *
44
 * @package Utilities
45
 */
46
47
namespace core;
48
49
use GeoIp2\Database\Reader;
50
use \Exception;
51
52
class SanityTests extends CAT
53
{
54
    /* in this section set current CAT requirements */
55
56
    /**
57
     * the minumum required php version 
58
     * 
59
     * @var string
60
     */
61
    private $needversionPHP = '7.2.0';
62
63
    /**
64
     * the minimum required simpleSAMLphp version
65
     * 
66
     * @var array
67
     */
68
    private $needversionSSP = ['major' => 1, 'minor' => 15];
69
70
    /**
71
     * all required NSIS modules
72
     * 
73
     * @var array<string>
74
     */
75
    private $NSISModules = [
76
        "nsArray.nsh",
77
        "FileFunc.nsh",
78
        "LogicLib.nsh",
79
        "WordFunc.nsh",
80
        "FileFunc.nsh",
81
        "x64.nsh",
82
    ];
83
84
    /**
85
     * set $profile_option_ct to the number of rows returned by 
86
     * "SELECT * FROM profile_option_dict" 
87
     * to compare actual vs. expected database structure
88
     * 
89
     * @var integer
90
     */
91
    private $profileOptionCount;
92
93
    /**
94
     * set $view_admin_ct to the number of rows returned by "desc view_admin" 
95
     *
96
     * @var integer
97
     */
98
    private $viewAdminCount = 8;
99
100
    /* end of config */
101
102
    /**
103
     * array holding the output of all tests that were executed
104
     * 
105
     * @var array
106
     */
107
    public $out;
108
109
    /**
110
     * temporary storage for the name of the test as it is being run
111
     * 
112
     * @var string
113
     */
114
    public $name;
115
    
116
    /**
117
     * variable used to signal that no more tests are to be performed
118
     * 
119
     * @var boolean
120
     */
121
    public $fatalError = false;
122
123
    /**
124
     * initialise the tests. Includes counting the number of expected rows in the profile_option_dict table.
125
     */
126
    public function __construct()
127
    {
128
        parent::__construct();
129
        $this->test_result = [];
130
        $this->test_result['global'] = 0;
131
        // parse the schema file to find out the number of expected rows...
132
        $schema = file(dirname(dirname(__FILE__)) . "/schema/schema.sql");
133
        $this->profileOptionCount = 0;
134
        $passedTheWindmill = FALSE;
135
        foreach ($schema as $schemaLine) {
136
            if (preg_match("/^INSERT INTO \`profile_option_dict\` VALUES/", $schemaLine)) {
137
                $passedTheWindmill = TRUE;
138
                continue;
139
            }
140
            if ($passedTheWindmill) {
141
                if (substr($schemaLine, 0, 1) == '(') { // a relevant line in schema
142
                    $this->profileOptionCount = $this->profileOptionCount + 1;
143
                } else { // anything else, quit parsing
144
                    break;
145
                }
146
            }
147
        }
148
    }
149
150
    /**
151
     * The single test wrapper
152
     * @param string $test the test name
153
     * @return void
154
     */
155
    public function runTest($test)
156
    {
157
        $this->out[$test] = [];
158
        $this->name = $test;
159
        $m_name = 'test' . $test;
160
        $this->test_result[$test] = 0;
161
        if (!method_exists($this, $m_name)) {
162
            $this->storeTestResult(\core\common\Entity::L_ERROR, "Configuration error, no test configured for <strong>$test</strong>.");
163
            return;
164
        }
165
        $this->$m_name();
166
    }
167
168
    /**
169
     * The multiple tests wrapper
170
     * @param array $Tests the tests array is a simple string array, where each 
171
     *                     entry is a test name. The test names can also be 
172
     *                     given in the format "test=>subtest", which defines a
173
     *                     conditional execution of the "subtest" if the "test"
174
     *                     was run earlier and returned a success.
175
     * @return void
176
     */
177
    public function runTests($Tests)
178
    {
179
        foreach ($Tests as $testName) {
180
            $matchArray = [];
181
            if (preg_match('/(.+)=>(.+)/', $testName, $matchArray)) {
182
                $tst = $matchArray[1];
183
                $subtst = $matchArray[2];
184
                if ($this->test_result[$tst] < \core\common\Entity::L_ERROR) {
185
                    $this->runTest($subtst);
186
                }
187
            } else {
188
                $this->runTest($testName);
189
            }
190
            if ($this->fatalError) {
191
                return;
192
            }
193
        }
194
    }
195
196
    /**
197
     * enumerates the tests which are defined
198
     * 
199
     * @return array
200
     */
201
    public function getTestNames()
202
    {
203
        $T = get_class_methods($this);
204
        $out = [];
205
        foreach ($T as $t) {
206
            if (preg_match('/^test(.*)$/', $t, $m)) {
207
                $out[] = $m[1];
208
            }
209
        }
210
        return $out;
211
    }
212
213
    /**
214
     * This array is used to return the test results.
215
     * As the 'global' entry it returns the maximum return value
216
     * from all tests.
217
     * Individual tests results are teturned as separate entires
218
     * indexed by test names; each value is an array passing "level" and "message"
219
     * from each of the tests.
220
     * $test_result is set by the testReturn method
221
     *
222
     * @var array $test_result
223
     */
224
    public $test_result;
225
226
    /**
227
     * stores the result of a given test in standardised format
228
     * 
229
     * @param int    $level   severity level of the result
230
     * @param string $message verbal description of the result
231
     * @return void
232
     */
233
    private function storeTestResult($level, $message)
234
    {
235
        $this->out[$this->name][] = ['level' => $level, 'message' => $message];
236
        $this->test_result[$this->name] = max($this->test_result[$this->name], $level);
237
        $this->test_result['global'] = max($this->test_result['global'], $level);
238
    }
239
240
    /**
241
     * finds out if a path name is configured as an absolute path or only implicit (e.g. is in $PATH)
242
     * @param string $pathToCheck the path to check
243
     * @return array
244
     */
245
    private function getExecPath($pathToCheck)
246
    {
247
        $the_path = "";
248
        $exec_is = "UNDEFINED";
249
250
        foreach ([\config\Master::PATHS, \config\ConfAssistant::PATHS, \config\Diagnostics::PATHS] as $config) {
251
            if (!empty($config[$pathToCheck])) {
252
                $matchArray = [];
253
                preg_match('/([^ ]+) ?/', $config[$pathToCheck], $matchArray);
254
                $exe = $matchArray[1];
255
                $the_path = exec("which " . $config[$pathToCheck]);
256
                if ($the_path == $exe) {
257
                    $exec_is = "EXPLICIT";
258
                } else {
259
                    $exec_is = "IMPLICIT";
260
                }
261
                return(['exec' => $the_path, 'exec_is' => $exec_is]);
262
            }
263
        }
264
        return(['exec' => $the_path, 'exec_is' => $exec_is]);
265
    }
266
267
    /**
268
     *  Test for php version
269
     * 
270
     * @return void
271
     */
272
    private function testPhp()
273
    {
274
        if (version_compare(phpversion(), $this->needversionPHP, '>=')) {
275
            $this->storeTestResult(\core\common\Entity::L_OK, "<strong>PHP</strong> is sufficiently recent. You are running " . phpversion() . ".");
276
        } else {
277
            $this->storeTestResult(\core\common\Entity::L_ERROR, "<strong>PHP</strong> is too old. We need at least $this->needversionPHP, but you only have " . phpversion() . ".");
278
        }
279
    }
280
    
281
    /**
282
     * Check if configuration constants from the template are set
283
     * in the correcponding config file
284
     * 
285
     * @param string $config file basename
286
     * @return array $failResults
287
     */
288
    private function runConstantsTest($config)
289
    {
290
        $templateConfig = file_get_contents(ROOT . "/config/$config-template.php");
291
        $newTemplateConfig = preg_replace("/class *$config/", "class $config" . "_template", $templateConfig);
292
        file_put_contents(ROOT . "/var/tmp/$config-template.php", $newTemplateConfig);
293
        include(ROOT . "/var/tmp/$config-template.php");
294
        unlink(ROOT . "/var/tmp/$config-template.php");
295
        $rft = new \ReflectionClass("\config\\$config" . "_template");
296
        $templateConstants = $rft->getConstants();
297
        $failResults = [];
298
        foreach ($templateConstants as $constant => $value) {
299
            try {
300
                $m = constant("\config\\$config::$constant");
0 ignored issues
show
Unused Code introduced by
The assignment to $m is dead and can be removed.
Loading history...
301
            } catch (Exception $e) {
302
                $failResults[] = "\config\\$config::$constant";
303
            }
304
        }
305
        return $failResults;
306
    }
307
308
    /**
309
     * Check if all required constants are set
310
     */
311
    private function testConfigConstants() {
312
        set_error_handler(function ($severity, $message, $file, $line) {
313
            throw new \ErrorException($message, $severity, $severity, $file, $line);
314
        });
315
        
316
        $failCount = 0;
317
        
318
        foreach (["Master", "ConfAssistant", "Diagnostics"] as $conf) {
319
            $failResults = $this->runConstantsTest($conf);
320
            $failCount = $failCount + count($failResults);
321
            if (count($failResults) > 0) {
322
            $this->storeTestResult(\core\common\Entity::L_ERROR, 
323
                    "<strong>The following constants are not set:</strong>" . implode(', ', $failResults));
324
            }
325
        }
326
        
327
        restore_error_handler();
328
        if ($failCount == 0) {
329
            $this->storeTestResult(\core\common\Entity::L_OK, "<strong>All config constants set</strong>");
330
        } else {
331
            $this->fatalError = true;
332
        }
333
    }
334
    /**
335
     * set for cat_base_url setting
336
     * 
337
     * @return void
338
     */
339
    private function testCatBaseUrl()
340
    {
341
        $rootUrl = substr(\config\Master::PATHS['cat_base_url'], -1) === '/' ? substr(\config\Master::PATHS['cat_base_url'], 0, -1) : \config\Master::PATHS['cat_base_url'];
342
        preg_match('/(^.*)\/admin\/112365365321.php/', $_SERVER['SCRIPT_NAME'], $m);
343
        if ($rootUrl === $m[1]) {
344
            $this->storeTestResult(\core\common\Entity::L_OK, "<strong>cat_base_url</strong> set correctly");
345
        } else {
346
            $rootFromScript = $m[1] === '' ? '/' : $m[1];
347
            $this->storeTestResult(\core\common\Entity::L_ERROR, "<strong>cat_base_url</strong> is set to <strong>" . \config\Master::PATHS['cat_base_url'] . "</strong> and should be <strong>$rootFromScript</strong>");
348
        }
349
    }
350
351
    /**
352
     * check whether the configured RADIUS hosts actually exist
353
     * 
354
     * @return void
355
     */
356
    private function testRADIUSProbes()
357
    {
358
        $probeReturns = [];
359
        foreach (\config\Diagnostics::RADIUSTESTS['UDP-hosts'] as $oneProbe) {
360
            $statusServer = new diag\RFC5997Tests($oneProbe['ip'], 1812, $oneProbe['secret']);
361
            if ($statusServer->statusServerCheck() !== diag\AbstractTest::RETVAL_OK) {
362
                $probeReturns[] = $oneProbe['display_name'];
363
            }
364
        }
365
        if (count($probeReturns) == 0) {
366
            $this->storeTestResult(common\Entity::L_OK, "All configured RADIUS/UDP probes are reachable.");
367
        } else {
368
            $this->storeTestResult(common\Entity::L_ERROR, "The following RADIUS probes are NOT reachable: " . implode(', ', $probeReturns));
369
        }
370
    }
371
372
    /**
373
     * test for simpleSAMLphp
374
     * 
375
     * @return void
376
     */
377
    private function testSsp()
378
    {
379
        if (!is_file(\config\Master::AUTHENTICATION['ssp-path-to-autoloader'])) {
380
            $this->storeTestResult(\core\common\Entity::L_ERROR, "<strong>simpleSAMLphp</strong> not found!");
381
        } else {
382
            include_once \config\Master::AUTHENTICATION['ssp-path-to-autoloader'];
383
            $SSPconfig = \SimpleSAML\Configuration::getInstance();
384
            $sspVersion = explode('.', $SSPconfig->getVersion());
385
            if ((int) $sspVersion[0] >= $this->needversionSSP['major'] && (int) $sspVersion[1] >= $this->needversionSSP['minor']) {
386
                $this->storeTestResult(\core\common\Entity::L_OK, "<strong>simpleSAMLphp</strong> is sufficently recent. You are running " . implode('.', $sspVersion));
387
            } else {
388
                $this->storeTestResult(\core\common\Entity::L_ERROR, "<strong>simpleSAMLphp</strong> is too old. We need at least " . implode('.', $this->needversionSSP));
389
            }
390
        }
391
    }
392
393
    /**
394
     * test for security setting
395
     * 
396
     * @return void
397
     */
398
    private function testSecurity()
399
    {
400
        if (in_array("I do not care about security!", \config\Master::SUPERADMINS)) {
401
            $this->storeTestResult(\core\common\Entity::L_WARN, "You do not care about security. This page should be made accessible to the CAT admin only! See config-master.php: 'SUPERADMINS'!");
402
        }
403
    }
404
405
    /**
406
     * test if zip is available
407
     * 
408
     * @return void
409
     */
410
    private function testZip()
411
    {
412
        if (exec("which zip") != "") {
413
            $this->storeTestResult(\core\common\Entity::L_OK, "<strong>zip</strong> binary found.");
414
        } else {
415
            $this->storeTestResult(\core\common\Entity::L_ERROR, "<strong>zip</strong> not found in your \$PATH!");
416
        }
417
    }
418
419
    /**
420
     * test if eapol_test is available and recent enough
421
     * 
422
     * @return void
423
     */
424
    private function testEapoltest()
425
    {
426
        exec(\config\Diagnostics::PATHS['eapol_test'], $out, $retval);
427
        if ($retval == 255) {
428
            $o = preg_grep('/-o<server cert/', $out);
429
            if (count($o) > 0) {
430
                $this->storeTestResult(\core\common\Entity::L_OK, "<strong>eapol_test</strong> script found.");
431
            } else {
432
                $this->storeTestResult(\core\common\Entity::L_ERROR, "<strong>eapol_test</strong> found, but is too old!");
433
            }
434
        } else {
435
            $this->storeTestResult(\core\common\Entity::L_ERROR, "<strong>eapol_test</strong> not found!");
436
        }
437
    }
438
439
    /**
440
     * test if logdir exists and is writable
441
     * 
442
     * @return void
443
     */
444
    private function testLogdir()
445
    {
446
        if (fopen(\config\Master::PATHS['logdir'] . "/debug.log", "a") == FALSE) {
447
            $this->storeTestResult(\core\common\Entity::L_WARN, "Log files in <strong>" . \config\Master::PATHS['logdir'] . "</strong> are not writable!");
448
        } else {
449
            $this->storeTestResult(\core\common\Entity::L_OK, "Log directory is writable.");
450
        }
451
    }
452
453
    /**
454
     * test for required PHP modules
455
     * 
456
     * @return void
457
     */
458
    private function testPhpModules()
459
    {
460
        if (function_exists('idn_to_ascii')) {
461
            $this->storeTestResult(\core\common\Entity::L_OK, "PHP can handle internationalisation.");
462
        } else {
463
            $this->storeTestResult(\core\common\Entity::L_ERROR, "PHP can <strong>NOT</strong> handle internationalisation (idn_to_ascii() from php7.0-intl).");
464
        }
465
466
        if (function_exists('gettext')) {
467
            $this->storeTestResult(\core\common\Entity::L_OK, "PHP extension <strong>GNU Gettext</strong> is installed.");
468
        } else {
469
            $this->storeTestResult(\core\common\Entity::L_ERROR, "PHP extension <strong>GNU Gettext</strong> not found!");
470
        }
471
472
        if (function_exists('openssl_sign')) {
473
            $this->storeTestResult(\core\common\Entity::L_OK, "PHP extension <strong>OpenSSL</strong> is installed.");
474
        } else {
475
            $this->storeTestResult(\core\common\Entity::L_ERROR, "PHP extension <strong>OpenSSL</strong> not found!");
476
        }
477
478
479
        // on CentOS and RHEL 8, look for Gmagick, else Imagick
480
        if (strpos(php_uname("r"), "el8") !== FALSE) {
481
            $classname = 'Gmagick';
482
        } else {
483
            $classname = 'Imagick';
484
        }
485
486
        if (class_exists('\\' . $classname)) {
487
            $this->storeTestResult(\core\common\Entity::L_OK, "PHP extension <strong>Imagick</strong> is installed.");
488
        } else {
489
            $this->storeTestResult(\core\common\Entity::L_ERROR, "PHP extension <strong>Imagick</strong> not found! Get it from your distribution or <a href='http://pecl.php.net/package/imagick'>here</a>.");
490
        }
491
492
        if (function_exists('ImageCreate')) {
493
            $this->storeTestResult(\core\common\Entity::L_OK, "PHP extension <strong>GD</strong> is installed.");
494
        } else {
495
            $this->storeTestResult(\core\common\Entity::L_ERROR, "PHP extension <strong>GD</strong> not found!</a>.");
496
        }
497
498
        if (function_exists('mysqli_connect')) {
499
            $this->storeTestResult(\core\common\Entity::L_OK, "PHP extension <strong>MySQL</strong> is installed.");
500
        } else {
501
            $this->storeTestResult(\core\common\Entity::L_ERROR, "PHP extension <strong>MySQL</strong> not found!");
502
        }
503
    }
504
505
    /**
506
     * test if GeoIP is installed correctly
507
     * 
508
     * @return void
509
     */
510
    private function testGeoip()
511
    {
512
        $host_4 = '145.0.2.50';
513
        $host_6 = '2001:610:188:444::50';
514
        switch (\config\Master::GEOIP['version']) {
515
            case 0:
516
                $this->storeTestResult(\core\common\Entity::L_REMARK, "As set in the config, no geolocation service will be used");
517
                break;
518
            case 1:
519
                if (!function_exists('geoip_record_by_name')) {
520
                    $this->storeTestResult(\core\common\Entity::L_ERROR, "PHP extension <strong>GeoIP</strong> (legacy) not found! Get it from your distribution or <a href='http://pecl.php.net/package/geoip'>here</a> or better install GeoIP2 from <a href='https://github.com/maxmind/GeoIP2-php'>here</a>.");
521
                    return;
522
                }
523
                $record = geoip_record_by_name($host_4);
524
                if ($record === FALSE) {
525
                    $this->storeTestResult(\core\common\Entity::L_ERROR, "PHP extension <strong>GeoIP</strong> (legacy) found but not working properly, perhaps you need to download the databases. See utils/GeoIP-update.sh in the CAT distribution and use it tu update the GeoIP database regularly.");
526
                    return;
527
                }
528
                if ($record['city'] != 'Utrecht') {
529
                    $this->storeTestResult(\core\common\Entity::L_ERROR, "PHP extension <strong>GeoIP</strong> (legacy) found but not working properly, perhaps you need to download the databases. See utils/GeoIP-update.sh in the CAT distribution and use it tu update the GeoIP database regularly.");
530
                    return;
531
                }
532
                $this->storeTestResult(\core\common\Entity::L_REMARK, "PHP extension <strong>GeoIP</strong> (legacy) is installed and working. See utils/GeoIP-update.sh in the CAT distribution and use it tu update the GeoIP database regularly. We stronly advise to replace the legacy GeoIP with GeoIP2 from <a href='https://github.com/maxmind/GeoIP2-php'>here</a>.");
533
                break;
534
            case 2:
535
                if (!is_file(\config\Master::GEOIP['geoip2-path-to-autoloader'])) {
536
                    $this->storeTestResult(\core\common\Entity::L_ERROR, "PHP extension <strong>GeoIP2</strong> not found! Get it from <a href='https://github.com/maxmind/GeoIP2-php'>here</a>.");
537
                    return;
538
                }
539
                if (!is_file(\config\Master::GEOIP['geoip2-path-to-db'])) {
540
                    $this->storeTestResult(\core\common\Entity::L_ERROR, "<strong>GeoIP2 database</strong> not found! See utils/GeoIP-update.sh in the CAT distribution and use it tu update the GeoIP database regularly.");
541
                    return;
542
                }
543
                include_once \config\Master::GEOIP['geoip2-path-to-autoloader'];
544
                $reader = new Reader(\config\Master::GEOIP['geoip2-path-to-db']);
545
                try {
546
                    $record = $reader->city($host_4);
547
                } catch (Exception $e) {
548
                    $this->storeTestResult(\core\common\Entity::L_ERROR, "PHP extension <strong>GeoIP2</strong> found but not working properly, perhaps you need to download the databases. See utils/GeoIP-update.sh in the CAT distribution and use it to update the GeoIP database regularly.");
549
                    return;
550
                }
551
                if ($record->city->name != 'Utrecht') {
552
                    $this->storeTestResult(\core\common\Entity::L_ERROR, "PHP extension <strong>GeoIP2</strong> found but not working properly, perhaps you need to download the databases. See utils/GeoIP-update.sh in the CAT distribution and use it to update the GeoIP database regularly.");
553
                    return;
554
                }
555
                try {
556
                    $record = $reader->city($host_6);
557
                } catch (Exception $e) {
558
                    $this->storeTestResult(\core\common\Entity::L_ERROR, "PHP extension <strong>GeoIP2</strong> found but not working properly with IPv6, perhaps you need to download the databases. See utils/GeoIP-update.sh in the CAT distribution and use it tu update the GeoIP database regularly.");
559
                    return;
560
                }
561
                if ($record->city->name != 'Utrecht') {
562
                    $this->storeTestResult(\core\common\Entity::L_ERROR, "PHP extension <strong>GeoIP2</strong> found but not working properly with IPv6, perhaps you need to download the databases. See utils/GeoIP-update.sh in the CAT distribution and use it tu update the GeoIP database regularly.");
563
                    return;
564
                }
565
                $this->storeTestResult(\core\common\Entity::L_OK, "PHP extension <strong>GeoIP2</strong> is installed and working. See utils/GeoIP-update.sh in the CAT distribution and use it tu update the GeoIP database regularly.");
566
                break;
567
            default:
568
                $this->storeTestResult(\core\common\Entity::L_ERROR, 'Check \config\Master::GEOIP[\'version\'], it must be set to either 1 or 2');
569
                break;
570
        }
571
    }
572
573
    /**
574
     * test if openssl is available
575
     * 
576
     * @return void
577
     */
578
    private function testOpenssl()
579
    {
580
        $A = $this->getExecPath('openssl');
581
        if ($A['exec'] != "") {
582
            $t = exec($A['exec'] . ' version');
583
            if ($A['exec_is'] == "EXPLICIT") {
584
                $this->storeTestResult(\core\common\Entity::L_OK, "<strong>$t</strong> was found and is configured explicitly in your config.");
585
            } else {
586
                $this->storeTestResult(\core\common\Entity::L_WARN, "<strong>$t</strong> was found, but is not configured with an absolute path in your config.");
587
            }
588
        } else {
589
            $this->storeTestResult(\core\common\Entity::L_ERROR, "<strong>openssl</strong> was not found on your system!");
590
        }
591
    }
592
593
    /**
594
     * test if makensis is available
595
     * 
596
     * @return void
597
     */
598
    private function testMakensis()
599
    {
600
        if (!is_numeric(\config\ConfAssistant::NSIS_VERSION)) {
601
            $this->storeTestResult(\core\common\Entity::L_ERROR, "NSIS_VERSION needs to be numeric!");
602
            return;
603
        }
604
        if (\config\ConfAssistant::NSIS_VERSION < 2) {
605
            $this->storeTestResult(\core\common\Entity::L_ERROR, "NSIS_VERSION needs to be at least 2!");
606
            return;
607
        }
608
        $A = $this->getExecPath('makensis');
609
        if ($A['exec'] != "") {
610
            $t = exec($A['exec'] . ' -VERSION');
611
            if ($A['exec_is'] == "EXPLICIT") {
612
                $this->storeTestResult(\core\common\Entity::L_OK, "<strong>makensis $t</strong> was found and is configured explicitly in your config.");
613
            } else {
614
                $this->storeTestResult(\core\common\Entity::L_WARN, "<strong>makensis $t</strong> was found, but is not configured with an absolute path in your config.");
615
            }
616
            $outputArray = [];
617
            exec($A['exec'] . ' -HELP', $outputArray);
618
            $t1 = count(preg_grep('/INPUTCHARSET/', $outputArray));
619
            if ($t1 == 1 && \config\ConfAssistant::NSIS_VERSION == 2) {
620
                $this->storeTestResult(\core\common\Entity::L_ERROR, "Declared NSIS_VERSION does not seem to match the file pointed to by PATHS['makensis']!");
621
            }
622
            if ($t1 == 0 && \config\ConfAssistant::NSIS_VERSION >= 3) {
623
                $this->storeTestResult(\core\common\Entity::L_ERROR, "Declared NSIS_VERSION does not seem to match the file pointed to by PATHS['makensis']!");
624
            }
625
        } else {
626
            $this->storeTestResult(\core\common\Entity::L_ERROR, "<strong>makensis</strong> was not found on your system!");
627
        }
628
    }
629
630
    /**
631
     * test if all required NSIS modules are available
632
     * 
633
     * @return void
634
     */
635
    private function testNSISmodules()
636
    {
637
        $tmp_dir = \core\common\Entity::createTemporaryDirectory('installer', 0)['dir'];
638
        if (!chdir($tmp_dir)) {
639
            $this->loggerInstance->debug(2, "Cannot chdir to $tmp_dir\n");
640
            $this->storeTestResult(\core\common\Entity::L_ERROR, "NSIS modules test - problem with temporary directory permissions, cannot continue");
641
            return;
642
        }
643
        $exe = 'tt.exe';
644
        $NSIS_Module_status = [];
645
        foreach ($this->NSISModules as $module) {
646
            unset($out);
647
            exec(\config\ConfAssistant::PATHS['makensis'] . " -V1 '-X!include $module' '-XOutFile $exe' '-XSection X' '-XSectionEnd'", $out, $retval);
648
            if ($retval > 0) {
649
                $NSIS_Module_status[$module] = 0;
650
            } else {
651
                $NSIS_Module_status[$module] = 1;
652
            }
653
        }
654
        if (is_file($exe)) {
655
            unlink($exe);
656
        }
657
        foreach ($NSIS_Module_status as $module => $status) {
658
            if ($status == 1) {
659
                $this->storeTestResult(\core\common\Entity::L_OK, "NSIS module <strong>$module</strong> was found.");
660
            } else {
661
                $this->storeTestResult(\core\common\Entity::L_ERROR, "NSIS module <strong>$module</strong> was not found or is not working correctly.");
662
            }
663
        }
664
    }
665
666
    /**
667
     * test access to dowloads directories
668
     * 
669
     * @return void
670
     */
671
    private function testDirectories()
672
    {
673
        $Dir1 = \core\common\Entity::createTemporaryDirectory('installer', 0);
674
        $dir1 = $Dir1['dir'];
675
        $base1 = $Dir1['base'];
676
        if ($dir1) {
677
            $this->storeTestResult(\core\common\Entity::L_OK, "Installer cache directory is writable.");
678
            \core\common\Entity::rrmdir($dir1);
679
        } else {
680
            $this->storeTestResult(\core\common\Entity::L_ERROR, "Installer cache directory $base1 does not exist or is not writable!");
681
            $this->fatalError = true;
682
        }
683
        $Dir2 = \core\common\Entity::createTemporaryDirectory('test', 0);
684
        $dir2 = $Dir2['dir'];
685
        $base2 = $Dir2['base'];
686
        if ($dir2) {
687
            $this->storeTestResult(\core\common\Entity::L_OK, "Test directory is writable.");
688
            \core\common\Entity::rrmdir($dir2);
689
        } else {
690
            $this->storeTestResult(\core\common\Entity::L_ERROR, "Test directory $base2 does not exist or is not writable!");
691
            $this->fatalError = true;
692
        }
693
        $Dir3 = \core\common\Entity::createTemporaryDirectory('logo', 0);
694
        $dir3 = $Dir3['dir'];
695
        $base3 = $Dir3['base'];
696
        if ($dir3) {
697
            $this->storeTestResult(\core\common\Entity::L_OK, "Logos cache directory is writable.");
698
            \core\common\Entity::rrmdir($dir3);
699
        } else {
700
            $this->storeTestResult(\core\common\Entity::L_ERROR, "Logos cache directory $base3 does not exist or is not writable!");
701
        }
702
    }
703
704
    /**
705
     * test if all required locales are enabled
706
     * 
707
     * @return void
708
     */
709
    private function testLocales()
710
    {
711
        $locales = shell_exec("locale -a");
712
        $allthere = "";
713
        foreach (\config\Master::LANGUAGES as $onelanguage) {
714
            if (preg_match("/" . $onelanguage['locale'] . "/", $locales) == 0) {
715
                $allthere .= $onelanguage['locale'] . " ";
716
            }
717
        }
718
        if ($allthere == "") {
719
            $this->storeTestResult(\core\common\Entity::L_OK, "All of your configured locales are available on your system.");
720
        } else {
721
            $this->storeTestResult(\core\common\Entity::L_WARN, "Some of your configured locales (<strong>$allthere</strong>) are not installed and will not be displayed correctly!");
722
        }
723
    }
724
725
    const DEFAULTS = [
726
        ["SETTING" => \config\Master::APPEARANCE['from-mail'],
727
            "DEFVALUE" => "[email protected]",
728
            "COMPLAINTSTRING" => "APPEARANCE/from-mail ",
729
            "REQUIRED" => FALSE,],
730
        ["SETTING" => \config\Master::APPEARANCE['support-contact']['url'],
731
            "DEFVALUE" => "[email protected]?body=Only%20English%20language%20please!",
732
            "COMPLAINTSTRING" => "APPEARANCE/support-contact/url ",
733
            "REQUIRED" => FALSE,],
734
        ["SETTING" => \config\Master::APPEARANCE['support-contact']['display'],
735
            "DEFVALUE" => "[email protected]",
736
            "COMPLAINTSTRING" => "APPEARANCE/support-contact/display ",
737
            "REQUIRED" => FALSE,],
738
        ["SETTING" => \config\Master::APPEARANCE['support-contact']['developer-mail'],
739
            "DEFVALUE" => "[email protected]",
740
            "COMPLAINTSTRING" => "APPEARANCE/support-contact/mail ",
741
            "REQUIRED" => FALSE,],
742
        ["SETTING" => \config\Master::APPEARANCE['abuse-mail'],
743
            "DEFVALUE" => "[email protected]",
744
            "COMPLAINTSTRING" => "APPEARANCE/abuse-mail ",
745
            "REQUIRED" => FALSE,],
746
        ["SETTING" => \config\Master::APPEARANCE['MOTD'],
747
            "DEFVALUE" => "Release Candidate. All bugs to be shot on sight!",
748
            "COMPLAINTSTRING" => "APPEARANCE/MOTD ",
749
            "REQUIRED" => FALSE,],
750
        ["SETTING" => \config\Master::APPEARANCE['webcert_CRLDP'],
751
            "DEFVALUE" => ['list', 'of', 'CRL', 'pointers'],
752
            "COMPLAINTSTRING" => "APPEARANCE/webcert_CRLDP ",
753
            "REQUIRED" => TRUE,],
754
        ["SETTING" => \config\Master::APPEARANCE['webcert_OCSP'],
755
            "DEFVALUE" => ['list', 'of', 'OCSP', 'pointers'],
756
            "COMPLAINTSTRING" => "APPEARANCE/webcert_OCSP ",
757
            "REQUIRED" => TRUE,],
758
        ["SETTING" => \config\Master::DB['INST']['host'],
759
            "DEFVALUE" => "db.host.example",
760
            "COMPLAINTSTRING" => "DB/INST ",
761
            "REQUIRED" => TRUE,],
762
        ["SETTING" => \config\Master::DB['INST']['host'],
763
            "DEFVALUE" => "db.host.example",
764
            "COMPLAINTSTRING" => "DB/USER ",
765
            "REQUIRED" => TRUE,],
766
        ["SETTING" => \config\Master::DB['EXTERNAL']['host'],
767
            "DEFVALUE" => "customerdb.otherhost.example",
768
            "COMPLAINTSTRING" => "DB/EXTERNAL ",
769
            "REQUIRED" => FALSE,],
770
    ];
771
772
    /**
773
     * test if defaults in the config have been replaced with some real values
774
     * 
775
     * @return void
776
     */
777
    private function testDefaults()
778
    {
779
        $defaultvalues = "";
780
        $missingvalues = "";
781
        // all the checks for equality with a shipped default value
782
        foreach (SanityTests::DEFAULTS as $oneCheckItem) {
783
            if ($oneCheckItem['REQUIRED'] && !$oneCheckItem['SETTING']) {
784
                $missingvalues .= $oneCheckItem["COMPLAINTSTRING"];
785
            } elseif ($oneCheckItem['SETTING'] == $oneCheckItem["DEFVALUE"]) {
786
                $defaultvalues .= $oneCheckItem["COMPLAINTSTRING"];
787
            }
788
        }
789
        // additional checks for defaults, which are not simple equality checks
790
        if (isset(\config\Diagnostics::RADIUSTESTS['UDP-hosts'][0]) && \config\Diagnostics::RADIUSTESTS['UDP-hosts'][0]['ip'] == "192.0.2.1") {
791
            $defaultvalues .= "RADIUSTESTS/UDP-hosts ";
792
        }
793
794
795
        if (isset(\config\Diagnostics::RADIUSTESTS['TLS-clientcerts'])) {
796
            foreach (\config\Diagnostics::RADIUSTESTS['TLS-clientcerts'] as $cadata) {
797
                foreach ($cadata['certificates'] as $cert_files) {
798
                    if (file_get_contents(ROOT . "/config/cli-certs/" . $cert_files['public']) === FALSE) {
799
                        $defaultvalues .= "CERTIFICATE/" . $cert_files['public'] . " ";
800
                    }
801
                    if (file_get_contents(ROOT . "/config/cli-certs/" . $cert_files['private']) === FALSE) {
802
                        $defaultvalues .= "CERTIFICATE/" . $cert_files['private'] . " ";
803
                    }
804
                }
805
            }
806
        }
807
808
        if ($defaultvalues != "") {
809
            $this->storeTestResult(\core\common\Entity::L_WARN, "Your configuration in config/config.php contains unchanged default values or links to inexistent files: <strong>$defaultvalues</strong>!");
810
        } else {
811
            $this->storeTestResult(\core\common\Entity::L_OK, "Your configuration does not contain any unchanged defaults, which is a good sign.");
812
        }
813
    }
814
815
    /**
816
     * test access to databases
817
     * 
818
     * @return void
819
     */
820
    private function testDatabases()
821
    {
822
        $databaseName1 = 'INST';
823
        try {
824
            $db1 = DBConnection::handle($databaseName1);
825
            $res1 = $db1->exec('SELECT * FROM profile_option_dict');
826
            if ($res1->num_rows == $this->profileOptionCount) {
827
                $this->storeTestResult(\core\common\Entity::L_OK, "The $databaseName1 database appears to be OK.");
828
            } else {
829
                $this->storeTestResult(\core\common\Entity::L_ERROR, "The $databaseName1 database is reacheable but probably not updated to this version of CAT.");
830
            }
831
        } catch (Exception $e) {
832
            $this->storeTestResult(\core\common\Entity::L_ERROR, "Connection to the  $databaseName1 database failed");
833
        }
834
835
        $databaseName2 = 'USER';
836
        try {
837
            $db2 = DBConnection::handle($databaseName2);
838
            if (\config\ConfAssistant::CONSORTIUM['name'] == "eduroam" && isset(\config\ConfAssistant::CONSORTIUM['deployment-voodoo']) && \config\ConfAssistant::CONSORTIUM['deployment-voodoo'] == "Operations Team") { // SW: APPROVED
839
                $res2 = $db2->exec('desc view_admin');
840
                if ($res2->num_rows == $this->viewAdminCount) {
841
                    $this->storeTestResult(\core\common\Entity::L_OK, "The $databaseName2 database appears to be OK.");
842
                } else {
843
                    $this->storeTestResult(\core\common\Entity::L_ERROR, "The $databaseName2 is reacheable but there is something wrong with the schema");
844
                }
845
            } else {
846
                $this->storeTestResult(\core\common\Entity::L_OK, "The $databaseName2 database appears to be OK.");
847
            }
848
        } catch (Exception $e) {
849
            $this->storeTestResult(\core\common\Entity::L_ERROR, "Connection to the  $databaseName2 database failed");
850
        }
851
852
        $databaseName3 = 'EXTERNAL';
853
        if (!empty(\config\Master::DB[$databaseName3])) {
854
            try {
855
                $db3 = DBConnection::handle($databaseName3);
856
                if (\config\ConfAssistant::CONSORTIUM['name'] == "eduroam" && isset(\config\ConfAssistant::CONSORTIUM['deployment-voodoo']) && \config\ConfAssistant::CONSORTIUM['deployment-voodoo'] == "Operations Team") { // SW: APPROVED
857
                    $res3 = $db3->exec('desc view_admin');
858
                    if ($res3->num_rows == $this->viewAdminCount) {
859
                        $this->storeTestResult(\core\common\Entity::L_OK, "The $databaseName3 database appears to be OK.");
860
                    } else {
861
                        $this->storeTestResult(\core\common\Entity::L_ERROR, "The $databaseName3 is reacheable but there is something wrong with the schema");
862
                    }
863
                } else {
864
                    $this->storeTestResult(\core\common\Entity::L_OK, "The $databaseName3 database appears to be OK.");
865
                }
866
            } catch (Exception $e) {
867
868
                $this->storeTestResult(\core\common\Entity::L_ERROR, "Connection to the  $databaseName3 database failed");
869
            }
870
        }
871
    }
872
873
    /**
874
     * test devices.php for the no_cache option
875
     * 
876
     * @return void
877
     */
878
    private function testDeviceCache()
879
    {
880
        if ((!empty(\devices\Devices::$Options['no_cache'])) && \devices\Devices::$Options['no_cache']) {
881
            $global_no_cache = 1;
882
        } else {
883
            $global_no_cache = 0;
884
        }
885
886
        if ($global_no_cache == 1) {
887
            $this->storeTestResult(\core\common\Entity::L_WARN, "Devices no_cache global option is set, this is not a good idea in a production setting\n");
888
        }
889
        $Devs = \devices\Devices::listDevices();
890
        $no_cache_dev = '';
891
        $no_cache_dev_count = 0;
892
        if ($global_no_cache) {
893
            foreach ($Devs as $dev => $D) {
894
                if (empty($D['options']['no_cache']) || $D['options']['no_cache'] != 0) {
895
                    $no_cache_dev .= $dev . " ";
896
                    $no_cache_dev_count++;
897
                }
898
            }
899
        } else {
900
            foreach ($Devs as $dev => $D) {
901
                if (!empty($D['options']['no_cache']) && $D['options']['no_cache'] != 0) {
902
                    $no_cache_dev .= $dev . " ";
903
                    $no_cache_dev_count++;
904
                }
905
            }
906
        }
907
908
909
        if ($no_cache_dev_count > 1) {
910
            $this->storeTestResult(\core\common\Entity::L_WARN, "The following devices will not be cached: $no_cache_dev");
911
        }
912
        if ($no_cache_dev_count == 1) {
913
            $this->storeTestResult(\core\common\Entity::L_WARN, "The following device will not be cached: $no_cache_dev");
914
        }
915
    }
916
917
    /**
918
     * test if mailer works
919
     * 
920
     * @return void
921
     */
922
    private function testMailer()
923
    {
924
        if (empty(\config\Master::APPEARANCE['abuse-mail']) || \config\Master::APPEARANCE['abuse-mail'] == "[email protected]") {
925
            $this->storeTestResult(\core\common\Entity::L_ERROR, "Your abuse-mail has not been set, cannot continue with mailer tests.");
926
            return;
927
        }
928
        $mail = new \PHPMailer\PHPMailer\PHPMailer();
929
        $mail->isSMTP();
930
        $mail->Port = 587;
931
        $mail->SMTPAuth = true;
932
        $mail->SMTPSecure = 'tls';
933
        $mail->Host = \config\Master::MAILSETTINGS['host'];
934
        $mail->Username = \config\Master::MAILSETTINGS['user'];
935
        $mail->Password = \config\Master::MAILSETTINGS['pass'];
936
        $mail->SMTPOptions = \config\Master::MAILSETTINGS['options'];
937
        $mail->WordWrap = 72;
938
        $mail->isHTML(FALSE);
939
        $mail->CharSet = 'UTF-8';
940
        $mail->From = \config\Master::APPEARANCE['from-mail'];
941
        $mail->FromName = \config\Master::APPEARANCE['productname'] . " Invitation System";
942
        $mail->addAddress(\config\Master::APPEARANCE['abuse-mail']);
943
        $mail->Subject = "testing CAT configuration mail";
944
        $mail->Body = "Testing CAT mailing\n";
945
        $sent = $mail->send();
946
        if ($sent) {
947
            $this->storeTestResult(\core\common\Entity::L_OK, "mailer settings appear to be working, check " . \config\Master::APPEARANCE['abuse-mail'] . " mailbox if the message was receiced.");
948
        } else {
949
            $this->storeTestResult(\core\common\Entity::L_ERROR, "mailer settings failed, check the Config::MAILSETTINGS");
950
        }
951
    }
952
953
    /**
954
     * TODO test if RADIUS connections work
955
     * 
956
     * @return void
957
     */
958
    private function testUDPhosts()
959
    {
960
//        if(empty)
961
    }
962
}