-
Notifications
You must be signed in to change notification settings - Fork 0
/
snggen
executable file
·820 lines (706 loc) · 28.9 KB
/
snggen
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
#!/usr/bin/env php
<?php
//
// SNGGen Tool - Generate Snuffleupagus configuration files from templates
// This tool is part of the Suhosin-NG Tools Suite - https://github.com/sektioneins/sng-tools
//
// Copyright 2021, SektionEins GmbH
//
// The SNGGen Tool is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The SNGGen Tool is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser Public License for more details.
//
// You should have received a copy of the GNU Lesser Public License
// along with the SNGGen Tool. If not, see <https://www.gnu.org/licenses/>.
//
class SNGGen {
public const version = '0.1';
public const sng_url = 'https://github.com/sektioneins/sng-tools';
public const sep = "\n############################# ### # ---------\n";
public const answers_yncx = [
['text' => '[y] Yes, enable this feature.', 'answer' => 'y'],
['text' => '[n] No. Disable this feature, please.', 'answer' => 'n'],
['text' => '[c] Comment out. Include feature in configuration, but leave it commented out for now.', 'answer' => 'c'],
['text' => '[x] Exclude. Do not include this feature at all.', 'answer' => 'x']
];
public static $templates = [];
public $cfg = [
'o' => '--', // output file
'force' => false, // force output file override
];
public $answers = [];
public $width = 100;
public function __construct() {}
public static function gen_yncx_template($line_desc, $enable_str, $disable_str) {
return function($answer, $tmpl) use ($line_desc, $enable_str, $disable_str) {
if ($answer === 'x') { return; }
SNGGen::print_tmpl_start($tmpl, $answer, $line_desc);
switch ($answer) {
case 'c':
echo '#', str_replace("\n", "\n#", $enable_str), "\n";
break;
case 'y':
echo $enable_str, "\n";
break;
case 'n':
echo $disable_str, "\n";
}
};
}
public static function get_tmpl_answer_text($tmpl, $answer) {
foreach ($tmpl['answers'] as $a) {
if ($a['answer'] == $answer) { return $a['text']; }
}
return false;
}
public static function default_read_validator($in, $tmpl) {
$valid = array_column($tmpl['answers'], 'answer');
return in_array($in, $valid);
}
public static function read_multichoice($tmpl) {
$validator = self::class . '::default_read_validator';
if (array_key_exists('validator', $tmpl)) {
$validator = $tmpl['validator'];
}
// $valid = array_column($tmpl['answers'], 'answer');
$default = $tmpl['default'];
$in = '';
do {
echo "Answer [default=$default]: ";
$in = fgets(STDIN);
if ($in === false) {
return false;
}
$in = strtolower(trim($in));
if ($in == '') {
$in = $default;
}
// echo "in=$in\n";
} while (!$validator($in, $tmpl));
return $in;
}
public function do_qa() {
foreach (self::$templates as $tmpl_name => $tmpl) {
if (array_key_exists('text', $tmpl)) {
echo wordwrap($tmpl['text'], $this->width) . "\n\n";
}
if (!array_key_exists('question', $tmpl)) { continue; }
echo "\n|==========[ ", $tmpl_name, " ]==========>\n\n";
echo wordwrap($tmpl['question'], $this->width) . "\n\n";
if (!array_key_exists('answers', $tmpl)) { continue; }
foreach ($tmpl['answers'] as $a) {
echo wordwrap($a['text'], $this->width) . "\n";
}
echo "\n";
if (array_key_exists($tmpl_name, $this->answers)) {
$tmpl['default'] = $this->answers[$tmpl_name];
}
$answer = self::read_multichoice($tmpl);
if ($answer === false) { return false; }
$this->answers[$tmpl_name] = $answer;
echo "Ok. Storing answer `" . self::get_tmpl_answer_text($tmpl, $answer) . "`\n";
}
}
public function gen_rules() {
ob_start();
foreach (self::$templates as $tmpl_name => $tmpl) {
if (!array_key_exists('template', $tmpl)) { continue; }
$this->process_template($tmpl_name, $tmpl);
}
$rules = ob_get_contents();
ob_end_clean();
if ($this->cfg['o'] === '--') {
echo $rules;
return;
}
if (file_exists($this->cfg['o']) && !$this->cfg['force']) {
error_exit("Output file '{$this->cfg['o']}' exists. Use -f to override.");
}
$fh = fopen($this->cfg['o'], 'w');
if ($fh === false) {
error_exit("Unable to write file '{$this->cfg['o']}'");
}
chmod($this->cfg['o'], 0600);
fwrite($fh, $rules);
fclose($fh);
print_stderr("Output written to '{$this->cfg['o']}' with file permission 0600 (only read-write for current user).");
}
public function process_template($tmpl_name, $tmpl) {
$answer = null;
if (array_key_exists($tmpl_name, $this->answers)) {
$answer = $this->answers[$tmpl_name];
} else if (isset($tmpl['default'])) {
$answer = $tmpl['default'];
}
$tmpl['name'] = $tmpl_name;
switch (gettype($tmpl['template'])) {
case 'string':
eval($tmpl['template']);
break;
case 'object':
$tmpl['template']($answer, $tmpl);
break;
}
}
public static function print_tmpl_start($tmpl, $answer, $title) {
echo self::sep, "## | --", $tmpl['name'], "=$answer\n", '## ', $title, "\n";
}
}
// --------------------------------- ------ -
function print_stderr($msg) {
fwrite(STDERR, $msg . "\n");
}
function error_exit($msg) {
print_stderr("ERROR: " . $msg);
exit(1);
}
function show_help() {
global $argv;
echo "SNGGen version " . SNGGen::version . "\n";
echo "Usage: ", $argv[0], " [actions/options]\n";
echo <<<'EOT'
actions:
--qa start interactive Q&A session
--gen generate Snuffleupagus rules file
options for --qa and --gen:
EOT;
foreach (SNGGen::$templates as $tmpl_name => $tmpl) {
if (!array_key_exists('template', $tmpl) || !array_key_exists('question', $tmpl)) { continue; }
echo ' --', $tmpl_name, ' | default: ', $tmpl['default'], "\n";
}
echo <<<EOT
examples:
Generate default configuration and print to STDOUT:
{$argv[0]} --gen
Complete a questionnaire and write configuration file to 'prod.rules':
{$argv[0]} --qa -o prod.rules
EOT;
}
function run() {
$sng = new SNGGen();
$longopts = ['help', 'qa', 'gen', 'force'];
foreach (SNGGen::$templates as $key => $tmpl) {
if (array_key_exists('question', $tmpl)) {
$longopts[] = $key . ":";
}
}
$opts = getopt('vo:fh', $longopts);
if ($opts === false) {
show_help();
exit(1);
}
$action = 'help';
foreach ($opts as $key => $value) {
if (array_key_exists($key, SNGGen::$templates)) {
$tmpl = SNGGen::$templates[$key];
$validator = 'SNGGen::default_read_validator';
if (array_key_exists('validator', $tmpl)) {
$validator = $tmpl['validator'];
}
$value = strtolower(trim($value));
if ($validator($value, $tmpl)) {
$sng->answers[$key] = $value;
} else {
error_exit("invalid or incorrect argument '$value' for option '--$key'");
}
continue;
}
switch ($key) {
case 'v':
echo "SNGGen version " . SNGGen::version . "\n";
exit(0);
case 'qa':
case 'h':
case 'help':
case 'gen':
$action = $key;
break;
case 'o':
$sng->cfg[$key] = $value;
break;
case 'f':
case 'force':
$sng->cfg['force'] = true;
break;
default:
error_exit("unknown option '$key'");
}
}
switch ($action) {
case 'qa':
if ($sng->do_qa() === false) {
print_stderr("\n--[ Goodbye. ]--\n");
exit(1);
}
$sng->gen_rules();
break;
case 'gen':
$sng->gen_rules();
break;
default:
show_help();
}
}
// --------------------------------- ------ -
// DEFINE TEMPLATES
SNGGen::$templates['qa_greeting'] = [
'text' => <<<'EOT'
Hi.
This is a short questionnaire, just to get to know your system better.
EOT
];
SNGGen::$templates['head_comment'] = [
'template' => <<<'EOT'
?>
## This Snuffleupagus rules file was automatically generated by the
## Suhosin-NG Tools Suite - <?php echo SNGGen::sng_url; ?>
## SNGGen Tool - version <?php echo SNGGen::version; ?>.
## - See https://suhosin.org/ for more information.
##
## Timestamp: <?php echo date('c'); ?>
##
<?php echo SNGGen::sep; ?>
## Let's start by enabling INI protection by default:
sp.ini_protection.enable();
EOT
];
SNGGen::$templates['display_errors'] = [
'question' => <<<'EOT'
Is this a configuration for a production system, or for a development setup?
For production systems it is usually best to disable error output and similar information disclosure.
EOT,
'answers' => [
['text' => '[p]: production system', 'answer' => 'p'],
['text' => '[d]: development system', 'answer' => 'd']
],
'default' => 'p',
'template' => function($answer, $tmpl) {
SNGGen::print_tmpl_start($tmpl, $answer, 'Disable error output?');
switch ($answer) {
case 'p': echo <<<'EOT'
## FOR PRODUCTION SYSTEMS: disable error messages and version numbers
sp.ini.key("display_errors").set("0").ro();
sp.ini.key("display_startup_errors").set("0").ro();
sp.ini.key("expose_php").set("0").ro();
EOT;
break;
case 'd': echo <<<'EOT'
## FOR DEVELOPMENT/TESTING: allow enabling error messages and version numbers
sp.ini.key("display_errors").rw();
sp.ini.key("display_startup_errors").rw();
sp.ini.key("expose_php").rw();
EOT;
break;
}
}
];
SNGGen::$templates['log_media'] = [
'question' => <<<'EOT'
Should logging be done via PHP or via Syslog?
EOT,
'answers' => [
['text' => '[p] PHP', 'answer' => 'p'],
['text' => '[s] Syslog', 'answer' => 's']
],
'default' => 'p',
'template' => function($answer, $tmpl) {
SNGGen::print_tmpl_start($tmpl, $answer, 'Logging output can be one of "php", "syslog"');
echo ($answer === 'p' ? '' : '#') . 'sp.log_media("php")' . "\n";
echo ($answer === 's' ? '' : '#') . 'sp.log_media("syslog")' . "\n";
}
];
SNGGen::$templates['secret_key'] = [
'question' => <<<'EOT'
Session and cookie encryption needs a secret key.
Would you like me to generate a new secret key for you?
(This is usually a good idea, even if you are not yet planning to use any of the encryption features.)
EOT,
'answers' => [
['text' => '[y] Yes.', 'answer' => 'y'],
['text' => '[n] No.', 'answer' => 'n']
],
'default' => 'y',
'template' => function($answer, $tmpl) {
if ($answer === 'n') { return; }
SNGGen::print_tmpl_start($tmpl, $answer, 'Secret key for session/cookie encryption');
echo "sp.global.secret_key(\"" . bin2hex(random_bytes(16)) . "\"); ## this key should be unique to your installation.\n";
}
];
SNGGen::$templates['harden_random'] = [
'question' => <<<'EOT'
Would you like to use better random numbers for rand() and mt_rand()?
This feature basically replaces rand() and mt_rand() with get_random_int(), thereby eliminating the need for random seeds.
Bad or predictable random seeds have been the source of many vulnerabilities in regard to supposedly unpredictable tokens, e.g. predictable passwords or predictable CSRF tokens.
Unless you actually need predictable pseudorandom numbers, it is highly recommended to enable this feature.
EOT,
'answers' => SNGGen::answers_yncx,
'default' => 'y',
'template' => SNGGen::gen_yncx_template('Harden random numbers?', 'sp.harden_random.enable();', 'sp.harden_random.disable();')
];
SNGGen::$templates['xxe_protection'] = [
'question' => <<<'EOT'
Would you like to disable XML External Entity (XXE) support? (probably yes)
EOT,
'answers' => SNGGen::answers_yncx,
'default' => 'y',
'template' => SNGGen::gen_yncx_template('Disable XML External Entity (XXE)?', 'sp.xxe_protection.enable();', 'sp.xxe_protection.disable();')
];
SNGGen::$templates['include_traversal'] = [
'question' => <<<'EOT'
Would you like to disable path traversal for require()/include()-style functions?
This feature will detect a number of `../` via regular expression and disable a matching include/require call.
Answers can be combined, e.g. '2c' will generate a rule for `../../`, but commented out.
EOT,
'answers' => [
['text' => '[1..100] Detect one or more `../`', 'answer' => '3'],
['text' => '[c] Comment out. Include feature in configuration, but leave it commented out for now.', 'answer' => 'c'],
['text' => '[s] Detect `../../../`, but put it in simulation mode', 'answer' => 's'],
['text' => '[x] Exclude. Do not include this feature at all.', 'answer' => 'x']
],
'default' => '3c',
'validator' => function($in, $tmpl) {
return (preg_match('/^(?:(\d+)([sc]*)|x)$/', $in, $m) && $m[1] >= 1);
},
'template' => function($answer, $tmpl) {
if ($answer === 'x') { return; }
if (!preg_match('/^(?:(\d+)([sc]*)|x)$/', $answer, $m)) { return; }
SNGGen::print_tmpl_start($tmpl, $answer, 'Prevent include/require path traversal');
$cc = strstr($m[2], 'c') === false ? '' : '#';
$sim = strstr($m[2], 's') === false ? '' : '.simulation()';
echo $cc, 'sp.disable_function.function_r("^(require|include)(_once)?$").value_r("' . str_repeat('\\.\\./+', (int)$m[1]) . '").' . $sim . 'drop();', "\n";
}
];
SNGGen::$templates['wrappers_whitelist'] = [
'question' => <<<'EOT'
PHP is able to open URLs when opening files via fopen() or include(). If supported by your PHP configuration, the following URL wrappers are allowed by default:
file:// — Accessing local filesystem
http:// — Accessing HTTP(s) URLs
ftp:// — Accessing FTP(s) URLs
php:// — Accessing various I/O streams
zlib:// — Compression Streams
data:// — Data (RFC 2397)
glob:// — Find pathnames matching pattern
phar:// — PHP Archive
ssh2:// — Secure Shell 2
rar:// — RAR
ogg:// — Audio streams
expect:// — Process Interaction Streams
The list may be incomplete.
Depending on your configuration setting of allow_url_fopen and allow_url_include, the list may be restricted to local resources.
Please provide a comma separated list of allowed wrappers.
EOT,
'answers' => [
['text' => '[comma separated list] of URL wrappers', 'answer' => ','],
['text' => '[c] Comment out. Include feature in configuration, but leave it commented out for now.', 'answer' => 'c'],
['text' => '[x] Exclude. Do not include this feature at all.', 'answer' => 'x']
],
'default' => 'file,php,phar',
'validator' => function($in, $tmpl) {
return preg_match('/^[a-z0-9]+(,[a-z0-9]+)*$/', $in);
},
'template' => function($answer, $tmpl) {
if ($answer === 'x') { return; }
SNGGen::print_tmpl_start($tmpl, $answer, 'Restrict URL wrappers');
if ($answer === 'c') {
echo '#sp.wrappers_whitelist.list("file,php,phar");', "\n";
return;
}
echo 'sp.wrappers_whitelist.list("' . $answer . '");', "\n";
}
];
SNGGen::$templates['allow_url'] = [
'question' => <<<'EOT'
The INI setting allow_url_fopen and allow_url_include make PHP support remote file inclusions, which can become a critical vulnerability when user input is part of the URL to be loaded. These settings can be forced to a disabled state.
Disable remote URL inclusions?
EOT,
'answers' => SNGGen::answers_yncx,
'default' => 'y',
'template' => SNGGen::gen_yncx_template('Prevent remote access via fopen/include', <<<'EOT'
sp.ini.key("allow_url_fopen").set("0").ro();
sp.ini.key("allow_url_include").set("0").ro();
EOT, <<<'EOT'
## allow_url_* protection is not enabled
EOT)
];
SNGGen::$templates['readonly_exec'] = [
'question' => <<<'EOT'
PHP files with write access can be prevented from being executed.
EOT,
'answers' => SNGGen::answers_yncx,
'default' => 'c',
'template' => SNGGen::gen_yncx_template('Disable execution of writable PHP files?', 'sp.readonly_exec.enable();', 'sp.readonly_exec.disable();')
];
SNGGen::$templates['disable_symlink'] = [
'question' => <<<'EOT'
Creating symbolic links with filenames generated from user input can become a serious vulnerability, e.g.
* Generated links may override existing links or files.
* Links can circumvent other protection features such as 'open_basedir'.
* Links can provide access to files outside the document root.
On the other hand, your application may need to create symbolic links in order to work correctly.
Should I disable the `symlink()` function entirely?
EOT,
'answers' => SNGGen::answers_yncx,
'default' => 'c',
'template' => SNGGen::gen_yncx_template('Disable the symlink() function?', 'sp.disable_function.function("symlink").drop();', '# not disabled.')
];
SNGGen::$templates['disable_eval'] = [
'question' => <<<'EOT'
The infamous eval() construct has been the source of endless vulnerabilities and code obfuscation in PHP for decades. There are legitimate use cases for eval(), but most applications can be written perfectly fine with other language constructs.
Would you like to block all calls to `eval()`?
EOT,
'answers' => SNGGen::answers_yncx,
'default' => 'n',
'template' => SNGGen::gen_yncx_template('Disable the eval() language construct?', 'sp.disable_function.function("symlink").drop();', <<<'EOT'
## eval() is not disabled.
## please consider restricting access to eval() using an eval_blacklist or better yet, an eval_whitelist, like so:
#sp.eval_blacklist.list("system,exec,shell_exec,passthru");
#sp.eval_whitelist.list("sin,cos,tan");
EOT)
];
SNGGen::$templates['protect_mail'] = [
'question' => <<<'EOT'
Newline injection into SMTP or email headers can lead to spam emails as well as information disclosure or related vulnerabilities. PHP's mail() function should not be able to accept the newline character (LF or CRLF) as input to any argument. But just in case it does not, would you like to activate a standard mail() protection filter?
EOT,
'answers' => SNGGen::answers_yncx,
'default' => 'y',
'template' => SNGGen::gen_yncx_template('mail() protection', <<<'EOT'
sp.disable_function.function("mail").param("to").value_r("\\n").alias("newline in mail() To:").drop();
sp.disable_function.function("mail").param("subject").value_r("\\n").alias("newline in mail() Subject:").drop();
sp.disable_function.function("mail").param("additional_headers").param_type("STRING").drop();
sp.disable_function.function("mail").param("additional_headers").param_type("NULL").allow();
sp.disable_function.function("mail").param("additional_headers").key_r("^(to|b?cc)$").drop();
EOT, <<<'EOT'
## mail() protection is not enabled
EOT)
];
SNGGen::$templates['mysql_bailout'] = [
'question' => <<<'EOT'
(experimental feature)
If any Mysql (Mysqli or Mysqlnd) query fails in production, this may indicate an attack. This feature tries to prevent further damage by stopping the request if any SQL query fails. Of course, by then it may already be too late, but in combination with other protection mechanisms such as fail2ban, this may prevent further attacks.
Enable Mysqli bailout protection?
EOT,
'answers' => SNGGen::answers_yncx,
'default' => 'c',
'template' => SNGGen::gen_yncx_template('Mysqli bailout protection', <<<'EOT'
@condition extension_loaded("mysqli");
sp.disable_function.function("mysqli_query").ret("FALSE").drop();
sp.disable_function.function("mysqli::query").ret("FALSE").drop();
sp.disable_function.function("mysqli_real_query").ret("FALSE").drop();
sp.disable_function.function("mysqli::real_query").ret("FALSE").drop();
sp.disable_function.function("mysqli_prepare").ret("FALSE").drop();
sp.disable_function.function("mysqli::prepare").ret("FALSE").drop();
sp.disable_function.function("mysqli_stmt_execute").ret("FALSE").drop();
sp.disable_function.function("mysqli_stmt::execute").ret("FALSE").drop();
sp.disable_function.function("mysqli_execute").ret("FALSE").
@condition extension_loaded("mysqlnd");
sp.ini.key("mysqlnd.collect_memory_statistics").set("0").ro();
sp.ini.key("mysqlnd.collect_statistics").set("1").ro();
sp.ini.key("mysqlnd.debug").set("").ro();
sp.ini.key("mysqlnd.log_mask").set("0").ro();
sp.ini.key("mysqlnd.mempool_default_size").set("16000").ro();
sp.ini.key("mysqlnd.net_cmd_buffer_size").set("4096").ro();
sp.ini.key("mysqlnd.net_read_buffer_size").set("32768").ro();
sp.ini.key("mysqlnd.net_read_timeout").set("86400").ro();
sp.ini.key("mysqlnd.sha256_server_public_key").set("").ro();
sp.ini.key("mysqlnd.trace_alloc").set("").ro();
@condition extension_loaded("mysqlnd") && PHP_VERSION_ID < 80100;
sp.ini.key("mysqlnd.fetch_data_copy").set("0").ro();
@end_condition;
EOT, <<<'EOT'
## Mysql bailout protection is not enabled
EOT)
];
SNGGen::$templates['pdo_bailout'] = [
'question' => <<<'EOT'
(experimental feature)
If any PDO query fails in production, this may indicate an attack. This feature tries to prevent further damage by stopping the request if any SQL query fails. Of course, by then it may already be too late, but in combination with other protection mechanisms such as fail2ban, this may prevent further attacks.
Enable PDO bailout protection?
EOT,
'answers' => SNGGen::answers_yncx,
'default' => 'c',
'template' => SNGGen::gen_yncx_template('Mysqli bailout protection', <<<'EOT'
sp.disable_function.function("PDO::query").ret("FALSE").drop();
sp.disable_function.function("PDO::prepare").ret("FALSE").drop();
sp.disable_function.function("PDO::exec").ret("FALSE").drop();
sp.disable_function.function("PDOStatement::execute").ret("FALSE").drop();
EOT, <<<'EOT'
## PDO bailout protection is not enabled
EOT)
];
SNGGen::$templates['upload_validation'] = [
'question' => <<<'EOT'
File upload scenarios come with a lot of attack surface and are notoriously difficult to protect. This feature provides a way to execute a script for each uploaded file in order to pre-validate user input before the actual PHP processing starts.
If you want to enable this feature, please provide the full path of your validation script.
Example: /opt/scripts/validator.sh
EOT,
'answers' => [
['text' => '[path] script to be executed', 'answer' => ''],
['text' => '[c] Comment out. Include feature in configuration, but leave it commented out for now.', 'answer' => 'c'],
['text' => '[x] Exclude. Do not include this feature at all.', 'answer' => 'x'],
],
'default' => 'c',
'validator' => function($in, $tmpl) {
return preg_match('#^(/.*|c|x)$#', $in);
},
'template' => function($answer, $tmpl) {
if ($answer === 'x') { return; }
SNGGen::print_tmpl_start($tmpl, $answer, 'Upload validation script');
if ($answer === 'c') {
echo '#sp.upload_validation.script("/var/www/is_valid_php.py").enable();', "\n";
return;
}
echo 'sp.upload_validation.script("', $answer, '").enable();', "\n";
}
];
SNGGen::$templates['ini_misc'] = [
'question' => <<<'EOT'
PHP's INI settings can make a huge difference when hardening PHP. This feature enables a set of rules to make some INI setting read-only or check or limit their value.
Prevent unwanted runtime INI changes made by ini_set() or other functions or by .htaccess?
EOT,
'answers' => SNGGen::answers_yncx,
'default' => 'y',
'template' => SNGGen::gen_yncx_template('Advanced INI protection', <<<'EOT'
## do not log read-only violations
## -> this setting allows PHP to prevent changes in most cases without even triggering the SP check
sp.ini_protection.policy_silent_ro();
## error logging options should not be set during runtime -> read-only.
sp.ini.key("error_log").ro();
sp.ini.key("error_reporting").ro();
sp.ini.key("log_errors").ro();
@condition PHP_VERSION_ID < 80000;
sp.ini.key("log_errors_max_len").set("2048").ro();
@end_condition;
sp.ini.key("ignore_repeated_errors").ro();
sp.ini.key("ignore_repeated_source").ro();
sp.ini.key("syslog.filter").ro();
## disable assert. assert() in PHP can evaluate arbitrary code just like eval()
sp.ini.key("assert.active").set("0").ro();
sp.ini.key("assert.bail").ro();
sp.ini.key("assert.callback").ro();
sp.ini.key("assert.exception").ro();
sp.ini.key("assert.warning").ro();
## enforce color codes. prevents potential XSS
sp.ini.key("highlight.comment").regexp("^#[0-9a-fA-F]{6}$");
sp.ini.key("highlight.default").regexp("^#[0-9a-fA-F]{6}$");
sp.ini.key("highlight.html").regexp("^#[0-9a-fA-F]{6}$");
sp.ini.key("highlight.keyword").regexp("^#[0-9a-fA-F]{6}$");
sp.ini.key("highlight.string").regexp("^#[0-9a-fA-F]{6}$");
## prevent code execution from auto-included files
sp.ini.key("auto_append_file").ro();
sp.ini.key("auto_prepend_file").ro();
## make rarely used features read-only. you can always set the value in php.ini
sp.ini.key("arg_separator.input").ro();
sp.ini.key("arg_separator.output").ro();
sp.ini.key("auto_detect_line_endings").ro();
sp.ini.key("auto_globals_jit").ro();
sp.ini.key("browscap").ro();
sp.ini.key("default_charset").ro();
sp.ini.key("register_argc_argv").ro();
sp.ini.key("report_memleaks").ro();
sp.ini.key("report_zend_debug").ro();
sp.ini.key("request_order").ro();
sp.ini.key("url_rewriter.hosts").ro();
sp.ini.key("url_rewriter.tags").ro();
sp.ini.key("variables_order").ro();
sp.ini.key("from").ro();
sp.ini.key("short_open_tag").ro();
sp.ini.key("unserialize_callback_func").ro();
sp.ini.key("zend.detect_unicode").ro();
sp.ini.key("zend.enable_gc").ro();
sp.ini.key("zend.exception_ignore_args").ro();
sp.ini.key("zend.exception_string_param_max_len").ro();
sp.ini.key("zend.multibyte").ro();
sp.ini.key("zend.script_encoding").ro();
## setting a default mime type other than text/html can be a way to prevent XSS, so this will be set to read-write by default
sp.ini.key("default_mimetype").rw();
## allow reasonable socket timeouts
sp.ini.key("default_socket_timeout").min("1").max("300").rw();
## disable dynamic loading of PHP extensions in an apache/mod_php environment as it is a security risk.
sp.ini.key("enable_dl").set("0").ro();
## links to manual pages in error pages should not be set during runtime.
sp.ini.key("docref_ext").ro();
sp.ini.key("docref_root").ro();
sp.ini.key("html_errors").set("0").ro();
## preventing $_POST and $_FILES to be populated can be a security feature, so read-write is ok.
sp.ini.key("enable_post_data_reading").rw();
## disable error append/prepend which may lead to log forging.
sp.ini.key("error_append_string").ro();
sp.ini.key("error_prepend_string").set("").ro();
## restrict limit settings to prevent Denial-of-Service
sp.ini.key("max_execution_time").min("30").max("600").rw();
sp.ini.key("max_file_uploads").min("0").max("25").rw();
sp.ini.key("max_input_nesting_level").min("16").max("64").rw();
sp.ini.key("max_input_time").set("-1").ro();
sp.ini.key("max_input_vars").min("0").max("1024").rw();
sp.ini.key("memory_limit").min("4M").max("256M").rw();
sp.ini.key("post_max_size").max("256M").rw();
sp.ini.key("upload_max_filesize").max("256M").rw();
sp.ini.key("precision").max("14").rw();
sp.ini.key("unserialize_max_depth").min("128").max("4096").rw();
sp.ini.key("serialize_precision").ro();
## some applications rely on these filters for security
## even though they should implement proper input validation for each input field separately.
@condition extension_loaded("filter");
sp.ini.key("filter.default").rw();
sp.ini.key("filter.default_flags").rw();
@end_condition;
## scripts will not be terminated after a client has aborted their connection.
## this feature may be needed for some time consuming server-side calculation
sp.ini.key("ignore_user_abort").rw();
## flushing may be needed
sp.ini.key("implicit_flush").rw();
## this feature may be required for some frameworks to work properly,
## but setting the include path to a fixed value is always more secure.
sp.ini.key("include_path").ro();
## input/output and encoding options
sp.ini.key("input_encoding").ro();
sp.ini.key("internal_encoding").ro();
sp.ini.key("output_encoding").ro();
#sp.ini.key("output_buffering").min("0").max("4096").rw();
sp.ini.key("output_handler").ro();
## open basedir is a security feature similar to chroot.
## why should it be allowed to disable this feature during runtime?
sp.ini.key("open_basedir").ro();
## pcre options
@condition extension_loaded("pcre");
sp.ini.key("pcre.backtrack_limit").min("1000").max("1000000").rw();
sp.ini.key("pcre.jit").rw();
sp.ini.key("pcre.recursion_limit").min("1000").max("100000").ro();
@end_condition;
## phar options
@condition extension_loaded("phar");
sp.ini.key("phar.cache_list").ro();
sp.ini.key("phar.readonly").ro();
sp.ini.key("phar.require_hash").ro();
@end_condition;
## allow setting the user agent
sp.ini.key("user_agent").rw();
## allow setting the xmlrpc fault code
sp.ini.key("xmlrpc_error_number").rw();
EOT, <<<'EOT'
## Advanced INI protection is not enabled
EOT)
];
SNGGen::$templates['qa_final'] = [
'text' => <<<'EOT'
Done. That's it. Finished. End of work. Emh... not quite.
There is much more to discover about Snuffleupagus features and its configuration.
Please have a look at the official documentation: https://snuffleupagus.readthedocs.io/config.html
Next steps:
* Configure how cookie encryption is pinned to a specific TLS session using
sp.global.cookie_env_var("SSL_SESSION_ID");
* Configure some cookies to encrypt using sp.cookie.name("my_cookie_name").encrypt();
* Please check back every once in a while for new versions of the snggen tool.
Have a nice day.
EOT
];
// --------------------------------- ------ -
if (php_sapi_name() == "cli" && $argv && $argv[0] && realpath($argv[0]) === __FILE__) {
run();
}