Completed
Push — master ( 64741e...904a1b )
by Maurício
09:11
created

libraries/classes/Config/ServerConfigChecks.php (1 issue)

1
<?php
2
/* vim: set expandtab sw=4 ts=4 sts=4: */
3
/**
4
 * Server config checks management
5
 *
6
 * @package PhpMyAdmin
7
 */
8
declare(strict_types=1);
9
10
namespace PhpMyAdmin\Config;
11
12
use PhpMyAdmin\Config\ConfigFile;
13
use PhpMyAdmin\Config\Descriptions;
14
use PhpMyAdmin\Core;
15
use PhpMyAdmin\Sanitize;
16
use PhpMyAdmin\Setup\Index as SetupIndex;
17
use PhpMyAdmin\Url;
18
use PhpMyAdmin\Util;
19
20
/**
21
 * Performs various compatibility, security and consistency checks on current config
22
 *
23
 * Outputs results to message list, must be called between SetupIndex::messagesBegin()
24
 * and SetupIndex::messagesEnd()
25
 *
26
 * @package PhpMyAdmin
27
 */
28
class ServerConfigChecks
29
{
30
    /**
31
     * @var ConfigFile configurations being checked
32
     */
33
    protected $cfg;
34
35
    /**
36
     * Constructor.
37
     *
38
     * @param ConfigFile $cfg Configuration
39
     */
40
    public function __construct(ConfigFile $cfg)
41
    {
42
        $this->cfg = $cfg;
43
    }
44
45
    /**
46
     * Perform config checks
47
     *
48
     * @return void
49
     */
50
    public function performConfigChecks()
51
    {
52
        $blowfishSecret = $this->cfg->get('blowfish_secret');
53
        $blowfishSecretSet = false;
54
        $cookieAuthUsed = false;
55
56
        list($cookieAuthUsed, $blowfishSecret, $blowfishSecretSet)
57
            = $this->performConfigChecksServers(
58
                $cookieAuthUsed,
59
                $blowfishSecret,
60
                $blowfishSecretSet
61
            );
62
63
        $this->performConfigChecksCookieAuthUsed(
64
            $cookieAuthUsed,
65
            $blowfishSecretSet,
66
            $blowfishSecret
67
        );
68
69
        //
70
        // $cfg['AllowArbitraryServer']
71
        // should be disabled
72
        //
73
        if ($this->cfg->getValue('AllowArbitraryServer')) {
74
            $sAllowArbitraryServerWarn = sprintf(
75
                __(
76
                    'This %soption%s should be disabled as it allows attackers to '
77
                    . 'bruteforce login to any MySQL server. If you feel this is necessary, '
78
                    . 'use %srestrict login to MySQL server%s or %strusted proxies list%s. '
79
                    . 'However, IP-based protection with trusted proxies list may not be '
80
                    . 'reliable if your IP belongs to an ISP where thousands of users, '
81
                    . 'including you, are connected to.'
82
                ),
83
                '[a@' . Url::getCommon(['page' => 'form', 'formset' => 'Features']) . '#tab_Security]',
84
                '[/a]',
85
                '[a@' . Url::getCommon(['page' => 'form', 'formset' => 'Features']) . '#tab_Security]',
86
                '[/a]',
87
                '[a@' . Url::getCommon(['page' => 'form', 'formset' => 'Features']) . '#tab_Security]',
88
                '[/a]'
89
            );
90
            SetupIndex::messagesSet(
91
                'notice',
92
                'AllowArbitraryServer',
93
                Descriptions::get('AllowArbitraryServer'),
94
                Sanitize::sanitize($sAllowArbitraryServerWarn)
95
            );
96
        }
97
98
        $this->performConfigChecksLoginCookie();
99
100
        $sDirectoryNotice = __(
101
            'This value should be double checked to ensure that this directory is '
102
            . 'neither world accessible nor readable or writable by other users on '
103
            . 'your server.'
104
        );
105
106
        //
107
        // $cfg['SaveDir']
108
        // should not be world-accessible
109
        //
110
        if ($this->cfg->getValue('SaveDir') != '') {
111
            SetupIndex::messagesSet(
112
                'notice',
113
                'SaveDir',
114
                Descriptions::get('SaveDir'),
115
                Sanitize::sanitize($sDirectoryNotice)
116
            );
117
        }
118
119
        //
120
        // $cfg['TempDir']
121
        // should not be world-accessible
122
        //
123
        if ($this->cfg->getValue('TempDir') != '') {
124
            SetupIndex::messagesSet(
125
                'notice',
126
                'TempDir',
127
                Descriptions::get('TempDir'),
128
                Sanitize::sanitize($sDirectoryNotice)
129
            );
130
        }
131
132
        $this->performConfigChecksZips();
133
    }
134
135
    /**
136
     * Check config of servers
137
     *
138
     * @param boolean $cookieAuthUsed    Cookie auth is used
139
     * @param string  $blowfishSecret    Blowfish secret
140
     * @param boolean $blowfishSecretSet Blowfish secret set
141
     *
142
     * @return array
143
     */
144
    protected function performConfigChecksServers(
145
        $cookieAuthUsed,
146
        $blowfishSecret,
147
        $blowfishSecretSet
148
    ) {
149
        $serverCnt = $this->cfg->getServerCount();
150
        for ($i = 1; $i <= $serverCnt; $i++) {
151
            $cookieAuthServer
152
                = ($this->cfg->getValue("Servers/$i/auth_type") == 'cookie');
153
            $cookieAuthUsed |= $cookieAuthServer;
154
            $serverName = $this->performConfigChecksServersGetServerName(
155
                $this->cfg->getServerName($i),
156
                $i
157
            );
158
            $serverName = htmlspecialchars($serverName);
159
160
            list($blowfishSecret, $blowfishSecretSet)
161
                = $this->performConfigChecksServersSetBlowfishSecret(
162
                    $blowfishSecret,
163
                    $cookieAuthServer,
164
                    $blowfishSecretSet
165
                );
166
167
            //
168
            // $cfg['Servers'][$i]['ssl']
169
            // should be enabled if possible
170
            //
171
            if (!$this->cfg->getValue("Servers/$i/ssl")) {
172
                $title = Descriptions::get('Servers/1/ssl') . " ($serverName)";
173
                SetupIndex::messagesSet(
174
                    'notice',
175
                    "Servers/$i/ssl",
176
                    $title,
177
                    __(
178
                        'You should use SSL connections if your database server '
179
                        . 'supports it.'
180
                    )
181
                );
182
            }
183
            $sSecurityInfoMsg = Sanitize::sanitize(sprintf(
184
                __(
185
                    'If you feel this is necessary, use additional protection settings - '
186
                    . '%1$shost authentication%2$s settings and %3$strusted proxies list%4%s. '
187
                    . 'However, IP-based protection may not be reliable if your IP belongs '
188
                    . 'to an ISP where thousands of users, including you, are connected to.'
189
                ),
190
                '[a@' . Url::getCommon(['page' => 'servers', 'mode' => 'edit', 'id' => $i]) . '#tab_Server_config]',
191
                '[/a]',
192
                '[a@' . Url::getCommon(['page' => 'form', 'formset' => 'Features']) . '#tab_Security]',
193
                '[/a]'
194
            ));
195
196
            //
197
            // $cfg['Servers'][$i]['auth_type']
198
            // warn about full user credentials if 'auth_type' is 'config'
199
            //
200
            if ($this->cfg->getValue("Servers/$i/auth_type") == 'config'
201
                && $this->cfg->getValue("Servers/$i/user") != ''
202
                && $this->cfg->getValue("Servers/$i/password") != ''
203
            ) {
204
                $title = Descriptions::get('Servers/1/auth_type')
205
                    . " ($serverName)";
206
                SetupIndex::messagesSet(
207
                    'notice',
208
                    "Servers/$i/auth_type",
209
                    $title,
210
                    Sanitize::sanitize(sprintf(
211
                        __(
212
                            'You set the [kbd]config[/kbd] authentication type and included '
213
                            . 'username and password for auto-login, which is not a desirable '
214
                            . 'option for live hosts. Anyone who knows or guesses your phpMyAdmin '
215
                            . 'URL can directly access your phpMyAdmin panel. Set %1$sauthentication '
216
                            . 'type%2$s to [kbd]cookie[/kbd] or [kbd]http[/kbd].'
217
                        ),
218
                        '[a@' . Url::getCommon(['page' => 'servers', 'mode' => 'edit', 'id' => $i]) . '#tab_Server]',
219
                        '[/a]'
220
                    ))
221
                    . ' ' . $sSecurityInfoMsg
222
                );
223
            }
224
225
            //
226
            // $cfg['Servers'][$i]['AllowRoot']
227
            // $cfg['Servers'][$i]['AllowNoPassword']
228
            // serious security flaw
229
            //
230
            if ($this->cfg->getValue("Servers/$i/AllowRoot")
231
                && $this->cfg->getValue("Servers/$i/AllowNoPassword")
232
            ) {
233
                $title = Descriptions::get('Servers/1/AllowNoPassword')
234
                    . " ($serverName)";
235
                SetupIndex::messagesSet(
236
                    'notice',
237
                    "Servers/$i/AllowNoPassword",
238
                    $title,
239
                    __('You allow for connecting to the server without a password.')
240
                    . ' ' . $sSecurityInfoMsg
241
                );
242
            }
243
        }
244
        return [$cookieAuthUsed, $blowfishSecret, $blowfishSecretSet];
245
    }
246
247
    /**
248
     * Set blowfish secret
249
     *
250
     * @param string  $blowfishSecret    Blowfish secret
251
     * @param boolean $cookieAuthServer  Cookie auth is used
252
     * @param boolean $blowfishSecretSet Blowfish secret set
253
     *
254
     * @return array
255
     */
256
    protected function performConfigChecksServersSetBlowfishSecret(
257
        $blowfishSecret,
258
        $cookieAuthServer,
259
        $blowfishSecretSet
260
    ) {
261
        if ($cookieAuthServer && $blowfishSecret === null) {
0 ignored issues
show
The condition $blowfishSecret === null is always false.
Loading history...
262
            $blowfishSecretSet = true;
263
            $this->cfg->set('blowfish_secret', Util::generateRandom(32));
264
        }
265
        return [$blowfishSecret, $blowfishSecretSet];
266
    }
267
268
    /**
269
     * Define server name
270
     *
271
     * @param string $serverName Server name
272
     * @param int    $serverId   Server id
273
     *
274
     * @return string Server name
275
     */
276
    protected function performConfigChecksServersGetServerName(
277
        $serverName,
278
        $serverId
279
    ) {
280
        if ($serverName == 'localhost') {
281
            $serverName .= " [$serverId]";
282
            return $serverName;
283
        }
284
        return $serverName;
285
    }
286
287
    /**
288
     * Perform config checks for zip part.
289
     *
290
     * @return void
291
     */
292
    protected function performConfigChecksZips()
293
    {
294
        $this->performConfigChecksServerGZipdump();
295
        $this->performConfigChecksServerBZipdump();
296
        $this->performConfigChecksServersZipdump();
297
    }
298
299
    /**
300
     * Perform config checks for zip part.
301
     *
302
     * @return void
303
     */
304
    protected function performConfigChecksServersZipdump()
305
    {
306
        //
307
        // $cfg['ZipDump']
308
        // requires zip_open in import
309
        //
310
        if ($this->cfg->getValue('ZipDump') && !$this->functionExists('zip_open')) {
311
            SetupIndex::messagesSet(
312
                'error',
313
                'ZipDump_import',
314
                Descriptions::get('ZipDump'),
315
                Sanitize::sanitize(sprintf(
316
                    __(
317
                        '%sZip decompression%s requires functions (%s) which are unavailable '
318
                        . 'on this system.'
319
                    ),
320
                    '[a@' . Url::getCommon(['page' => 'form', 'formset' => 'Features']) . '#tab_Import_export]',
321
                    '[/a]',
322
                    'zip_open'
323
                ))
324
            );
325
        }
326
327
        //
328
        // $cfg['ZipDump']
329
        // requires gzcompress in export
330
        //
331
        if ($this->cfg->getValue('ZipDump') && !$this->functionExists('gzcompress')) {
332
            SetupIndex::messagesSet(
333
                'error',
334
                'ZipDump_export',
335
                Descriptions::get('ZipDump'),
336
                Sanitize::sanitize(sprintf(
337
                    __(
338
                        '%sZip compression%s requires functions (%s) which are unavailable on '
339
                        . 'this system.'
340
                    ),
341
                    '[a@' . Url::getCommon(['page' => 'form', 'formset' => 'Features']) . '#tab_Import_export]',
342
                    '[/a]',
343
                    'gzcompress'
344
                ))
345
            );
346
        }
347
    }
348
349
    /**
350
     * Check config of servers
351
     *
352
     * @param boolean $cookieAuthUsed    Cookie auth is used
353
     * @param boolean $blowfishSecretSet Blowfish secret set
354
     * @param string  $blowfishSecret    Blowfish secret
355
     *
356
     * @return array
357
     */
358
    protected function performConfigChecksCookieAuthUsed(
359
        $cookieAuthUsed,
360
        $blowfishSecretSet,
361
        $blowfishSecret
362
    ) {
363
        //
364
        // $cfg['blowfish_secret']
365
        // it's required for 'cookie' authentication
366
        //
367
        if ($cookieAuthUsed) {
368
            if ($blowfishSecretSet) {
369
                // 'cookie' auth used, blowfish_secret was generated
370
                SetupIndex::messagesSet(
371
                    'notice',
372
                    'blowfish_secret_created',
373
                    Descriptions::get('blowfish_secret'),
374
                    Sanitize::sanitize(__(
375
                        'You didn\'t have blowfish secret set and have enabled '
376
                        . '[kbd]cookie[/kbd] authentication, so a key was automatically '
377
                        . 'generated for you. It is used to encrypt cookies; you don\'t need to '
378
                        . 'remember it.'
379
                    ))
380
                );
381
            } else {
382
                $blowfishWarnings = [];
383
                // check length
384
                if (strlen($blowfishSecret) < 32) {
385
                    // too short key
386
                    $blowfishWarnings[] = __(
387
                        'Key is too short, it should have at least 32 characters.'
388
                    );
389
                }
390
                // check used characters
391
                $hasDigits = (bool)preg_match('/\d/', $blowfishSecret);
392
                $hasChars = (bool)preg_match('/\S/', $blowfishSecret);
393
                $hasNonword = (bool)preg_match('/\W/', $blowfishSecret);
394
                if (!$hasDigits || !$hasChars || !$hasNonword) {
395
                    $blowfishWarnings[] = Sanitize::sanitize(
396
                        __(
397
                            'Key should contain letters, numbers [em]and[/em] '
398
                            . 'special characters.'
399
                        )
400
                    );
401
                }
402
                if (!empty($blowfishWarnings)) {
403
                    SetupIndex::messagesSet(
404
                        'error',
405
                        'blowfish_warnings' . count($blowfishWarnings),
406
                        Descriptions::get('blowfish_secret'),
407
                        implode('<br />', $blowfishWarnings)
408
                    );
409
                }
410
            }
411
        }
412
    }
413
414
    /**
415
     * Check configuration for login cookie
416
     *
417
     * @return void
418
     */
419
    protected function performConfigChecksLoginCookie()
420
    {
421
        //
422
        // $cfg['LoginCookieValidity']
423
        // value greater than session.gc_maxlifetime will cause
424
        // random session invalidation after that time
425
        $loginCookieValidity = $this->cfg->getValue('LoginCookieValidity');
426
        if ($loginCookieValidity > ini_get('session.gc_maxlifetime')
427
        ) {
428
            SetupIndex::messagesSet(
429
                'error',
430
                'LoginCookieValidity',
431
                Descriptions::get('LoginCookieValidity'),
432
                Sanitize::sanitize(sprintf(
433
                    __(
434
                        '%1$sLogin cookie validity%2$s greater than %3$ssession.gc_maxlifetime%4$s may '
435
                        . 'cause random session invalidation (currently session.gc_maxlifetime '
436
                        . 'is %5$d).'
437
                    ),
438
                    '[a@' . Url::getCommon(['page' => 'form', 'formset' => 'Features']) . '#tab_Security]',
439
                    '[/a]',
440
                    '[a@' . Core::getPHPDocLink('session.configuration.php#ini.session.gc-maxlifetime') . ']',
441
                    '[/a]',
442
                    ini_get('session.gc_maxlifetime')
443
                ))
444
            );
445
        }
446
447
        //
448
        // $cfg['LoginCookieValidity']
449
        // should be at most 1800 (30 min)
450
        //
451
        if ($loginCookieValidity > 1800) {
452
            SetupIndex::messagesSet(
453
                'notice',
454
                'LoginCookieValidity',
455
                Descriptions::get('LoginCookieValidity'),
456
                Sanitize::sanitize(sprintf(
457
                    __(
458
                        '%sLogin cookie validity%s should be set to 1800 seconds (30 minutes) '
459
                        . 'at most. Values larger than 1800 may pose a security risk such as '
460
                        . 'impersonation.'
461
                    ),
462
                    '[a@' . Url::getCommon(['page' => 'form', 'formset' => 'Features']) . '#tab_Security]',
463
                    '[/a]'
464
                ))
465
            );
466
        }
467
468
        //
469
        // $cfg['LoginCookieValidity']
470
        // $cfg['LoginCookieStore']
471
        // LoginCookieValidity must be less or equal to LoginCookieStore
472
        //
473
        if (($this->cfg->getValue('LoginCookieStore') != 0)
474
            && ($loginCookieValidity > $this->cfg->getValue('LoginCookieStore'))
475
        ) {
476
            SetupIndex::messagesSet(
477
                'error',
478
                'LoginCookieValidity',
479
                Descriptions::get('LoginCookieValidity'),
480
                Sanitize::sanitize(sprintf(
481
                    __(
482
                        'If using [kbd]cookie[/kbd] authentication and %sLogin cookie store%s '
483
                        . 'is not 0, %sLogin cookie validity%s must be set to a value less or '
484
                        . 'equal to it.'
485
                    ),
486
                    '[a@' . Url::getCommon(['page' => 'form', 'formset' => 'Features']) . '#tab_Security]',
487
                    '[/a]',
488
                    '[a@' . Url::getCommon(['page' => 'form', 'formset' => 'Features']) . '#tab_Security]',
489
                    '[/a]'
490
                ))
491
            );
492
        }
493
    }
494
495
    /**
496
     * Check GZipDump configuration
497
     *
498
     * @return void
499
     */
500
    protected function performConfigChecksServerBZipdump()
501
    {
502
        //
503
        // $cfg['BZipDump']
504
        // requires bzip2 functions
505
        //
506
        if ($this->cfg->getValue('BZipDump')
507
            && (!$this->functionExists('bzopen') || !$this->functionExists('bzcompress'))
508
        ) {
509
            $functions = $this->functionExists('bzopen')
510
                ? '' :
511
                'bzopen';
512
            $functions .= $this->functionExists('bzcompress')
513
                ? ''
514
                : ($functions ? ', ' : '') . 'bzcompress';
515
            SetupIndex::messagesSet(
516
                'error',
517
                'BZipDump',
518
                Descriptions::get('BZipDump'),
519
                Sanitize::sanitize(
520
                    sprintf(
521
                        __(
522
                            '%1$sBzip2 compression and decompression%2$s requires functions (%3$s) which '
523
                             . 'are unavailable on this system.'
524
                        ),
525
                        '[a@' . Url::getCommon(['page' => 'form', 'formset' => 'Features']) . '#tab_Import_export]',
526
                        '[/a]',
527
                        $functions
528
                    )
529
                )
530
            );
531
        }
532
    }
533
534
    /**
535
     * Check GZipDump configuration
536
     *
537
     * @return void
538
     */
539
    protected function performConfigChecksServerGZipdump()
540
    {
541
        //
542
        // $cfg['GZipDump']
543
        // requires zlib functions
544
        //
545
        if ($this->cfg->getValue('GZipDump')
546
            && (!$this->functionExists('gzopen') || !$this->functionExists('gzencode'))
547
        ) {
548
            SetupIndex::messagesSet(
549
                'error',
550
                'GZipDump',
551
                Descriptions::get('GZipDump'),
552
                Sanitize::sanitize(sprintf(
553
                    __(
554
                        '%1$sGZip compression and decompression%2$s requires functions (%3$s) which '
555
                        . 'are unavailable on this system.'
556
                    ),
557
                    '[a@' . Url::getCommon(['page' => 'form', 'formset' => 'Features']) . '#tab_Import_export]',
558
                    '[/a]',
559
                    'gzencode'
560
                ))
561
            );
562
        }
563
    }
564
565
    /**
566
     * Wrapper around function_exists to allow mock in test
567
     *
568
     * @param string $name Function name
569
     *
570
     * @return boolean
571
     */
572
    protected function functionExists($name)
573
    {
574
        return function_exists($name);
575
    }
576
}
577