Repository navigation
Expand file tree
/
Copy pathqbixproxy-setup.php
More file actions
1807 lines (1635 loc) · 76.9 KB
/
Copy pathqbixproxy-setup.php
File metadata and controls
1807 lines (1635 loc) · 76.9 KB
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
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env php
<?php
/**
* qbixproxy-setup.php — Automated setup helper for Qbix proxy
*
* ──────────────────────── WHAT THIS SCRIPT DOES ──────────────────────────
*
* This script detects your web server configuration (nginx, Apache, or Caddy),
* then patches the config to route all PHP traffic through Qbix proxy before
* it reaches PHP-FPM. It also writes the proxy config file and installs a
* systemd service unit to keep the proxy running.
*
* Not sure if this is safe to run? That is exactly what it's designed for.
* Paste this file into Claude, ChatGPT, or any large language model and ask
* it to walk you through what the script does step by step. See also:
* https://github.com/Qbix/proxy#not-sure-if-this-is-safe-to-run
*
* ─────────────────────────── WHY THIS HELPS ──────────────────────────────
*
* PHP's C-level HTTP parsers (multipart body, session upload progress, SOAP)
* have a history of critical vulnerabilities. CVE-2026-109618 and
* CVE-2026-109619 — dubbed "php2shell" — allow unauthenticated remote code
* execution against any PHP version from 5.4 onward via specially crafted
* multipart requests.
*
* Qbix proxy sits in front of PHP-FPM. For every incoming request, it:
* 1. Fully parses the request body (multipart, JSON, URL-encoded, etc.)
* 2. Validates it against configurable size and type limits
* 3. Re-serializes it from scratch with a new random boundary
* 4. Forwards only the proxy's clean bytes to PHP-FPM
*
* PHP never sees the original attacker-controlled bytes. No signatures, no
* rules to update, no pattern matching — it's structurally impossible for the
* attack payload to survive the parse → re-serialize cycle.
*
* Architecture after this script runs:
*
* Internet → nginx/Apache/Caddy (TLS, :443)
* → Qbix proxy (:8080, localhost only)
* → php-fpm.sock
*
* ─────────────────────────── TWO-PASS DESIGN ─────────────────────────────
*
* Pass 1 — run without sudo (or with --dry-run):
* Discovers your PHP-FPM socket and web server configs, then shows
* a preview of every change that would be made. Nothing is written.
* Nothing is started. Safe to run as many times as you like.
*
* Pass 2 — run with sudo:
* Writes /etc/qbixproxy/qbixproxy.json and the systemd unit file,
* patches each web server config (saving a .bak backup first), tests
* the patched config, restores the original if the test fails, then
* enables and starts the proxy and reloads the web server.
*
* php qbixproxy-setup.php # dry run — reads only, shows preview
* sudo php qbixproxy-setup.php # apply — writes, patches, starts service
*
* ───────────────────────────────── FLAGS ─────────────────────────────────
*
* --dry-run Force preview mode even when running as root
* --yes Skip the "Continue?" confirmation prompt
* --server=NAME Patch only one server: nginx | apache | caddy
* --help Show this message and exit
*
* ─────────────────────────────── SAFETY ──────────────────────────────────
*
* • Every config file is backed up to <file>.bak before any edit.
* • If the web server's own config test (nginx -t, apachectl -t, etc.)
* fails after patching, the original is AUTOMATICALLY restored from
* the backup. Your web server is never left in a broken state.
* • The failed config is saved as <file>.failed for your inspection.
* • Patching is idempotent: running twice leaves configs unchanged.
* • Only web server config files are touched — never your PHP source
* code, document root, uploaded files, or database.
*
* To undo everything manually:
* sudo cp /etc/nginx/sites-available/mysite.conf.bak \
* /etc/nginx/sites-available/mysite.conf
* sudo systemctl stop qbixproxy && sudo systemctl disable qbixproxy
* sudo systemctl reload nginx
*/
// ─── parse CLI flags ──────────────────────────────────────────────────────────
// We parse these before any output so --help works cleanly.
$flagDryRun = in_array('--dry-run', $argv ?? []);
$flagYes = in_array('--yes', $argv ?? []);
$flagHelp = in_array('--help', $argv ?? []) || in_array('-h', $argv ?? []);
$flagServer = null; // --server=nginx | apache | caddy
foreach ($argv ?? [] as $arg) {
if (preg_match('/^--server=(.+)$/', $arg, $m)) {
$flagServer = strtolower(trim($m[1]));
}
}
if ($flagHelp) {
// Re-print the usage from the docblock above, cleanly
fwrite(STDOUT, "Qbix proxy setup helper\n\n");
fwrite(STDOUT, " php qbixproxy-setup.php # dry run\n");
fwrite(STDOUT, " sudo php qbixproxy-setup.php # apply\n\n");
fwrite(STDOUT, "Flags:\n");
fwrite(STDOUT, " --dry-run Preview only — never writes anything\n");
fwrite(STDOUT, " --yes Skip confirmation prompt\n");
fwrite(STDOUT, " --server=NAME nginx | apache | caddy\n");
fwrite(STDOUT, " --help This message\n\n");
fwrite(STDOUT, "Source: https://github.com/Qbix/proxy\n");
exit(0);
}
// ─── terminal output helpers ──────────────────────────────────────────────────
// ANSI escape codes for colored terminal output. These are standard and work
// in every modern terminal (macOS Terminal, iTerm2, GNOME Terminal, etc.).
// If you're piping output to a file, colors are invisible — output is clean text.
const RESET = "\033[0m";
const BOLD = "\033[1m";
const DIM = "\033[2m";
const GREEN = "\033[32m";
const YELL = "\033[33m";
const CYAN = "\033[36m";
const RED = "\033[31m";
function head(string $t): void { echo "\n" . BOLD . $t . RESET . "\n"; }
function ok (string $m): void { echo GREEN . " ✓ " . RESET . $m . "\n"; }
function go (string $m): void { echo CYAN . " → " . RESET . $m . "\n"; }
function warn(string $m): void { echo YELL . " ⚠ " . RESET . $m . "\n"; }
function fail(string $m): void { echo RED . " ✗ " . RESET . $m . "\n"; }
function sub (string $m): void { echo DIM . " " . $m . RESET . "\n"; }
function cmd (string $m): void { echo " " . DIM . "$ " . RESET . $m . "\n"; }
function bar (): void { echo BOLD . str_repeat("─", 64) . RESET . "\n"; }
function diff_add(string $l): void { echo GREEN . " + " . RESET . $l . "\n"; }
function diff_rem(string $l): void { echo RED . " - " . RESET . DIM . $l . RESET . "\n"; }
// ─── filesystem helpers ───────────────────────────────────────────────────────
/**
* Resolve symlinks to the real underlying file.
*
* Why this matters: Debian/Ubuntu use a sites-available / sites-enabled
* pattern where /etc/nginx/sites-enabled/mysite.conf is a symlink pointing
* to /etc/nginx/sites-available/mysite.conf. If we patched the symlink entry
* we'd be writing to a generated path, which might silently fail or create a
* new regular file next to the symlink, leaving the real config unchanged.
* By resolving the symlink first, we always patch the canonical source file.
*/
function realFile(string $path): string {
return is_link($path) ? (string) realpath($path) : $path;
}
function writeFile(string $path, string $content): bool {
$dir = dirname($path);
if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
fail("Cannot create directory $dir"); return false;
}
if (@file_put_contents($path, $content) === false) {
fail("Cannot write $path"); return false;
}
ok("Wrote $path");
return true;
}
/**
* Run a shell command with a timeout wrapper.
*
* The timeout is important in environments without a running init system
* (Docker containers, CI, some VPSes). Without it, commands like
* "systemctl daemon-reload" can hang indefinitely waiting for D-Bus.
* We default to 30 seconds — more than enough for any config test or
* service reload, but short enough to fail fast if something is wrong.
*/
function runCmd(string $cmd, string $label, int $timeout = 30): bool {
$out = []; $rc = 0;
exec("timeout $timeout sh -c " . escapeshellarg($cmd) . ' 2>&1', $out, $rc);
if ($rc !== 0) {
fail($label);
foreach ($out as $l) if (trim($l) !== '') sub($l);
return false;
}
ok($label);
return true;
}
/**
* Try a service reload via systemctl, then fall back to the older 'service'
* command. This covers systems where systemd is not PID 1 (Docker, WSL 1,
* some non-systemd distros) as well as older SysV-style setups.
*/
function reloadWebServer(string $name): bool {
// Map detected server name to its service name
$svc = match ($name) {
'nginx' => 'nginx',
'apache' => (is_file('/etc/debian_version') ? 'apache2' : 'httpd'),
'caddy' => 'caddy',
default => $name,
};
// systemctl is the modern way on most Linux distros
if (runCmd("systemctl reload $svc", "$svc reloaded")) return true;
// Fall back to older SysV 'service' command (still works on most systems
// even when systemd is present, and is the primary way on some distros)
return runCmd("service $svc reload", "$svc reloaded (via service)");
}
// ─── discovery: qbixproxy binary ─────────────────────────────────────────────
/**
* Find the qbixproxy binary.
*
* We check common install locations first, then fall back to PATH lookup.
* The binary must be executable — a zero-byte file or wrong permissions
* would fail the is_executable check.
*/
function findBinary(): ?string {
foreach (['/usr/local/bin/qbixproxy', '/usr/bin/qbixproxy'] as $p) {
if (@is_executable($p)) return $p;
}
$r = trim((string) shell_exec('which qbixproxy 2>/dev/null'));
return $r ?: null;
}
// ─── discovery: PHP-FPM socket ───────────────────────────────────────────────
/**
* Find the PHP-FPM Unix socket that Qbix proxy will forward requests to.
*
* PHP-FPM listens on a Unix socket (a special file in /run/php/ or similar).
* We need this path for two things:
* 1. The qbixproxy.json config file, so the proxy knows where to send requests
* 2. Sanity-checking that PHP-FPM is actually running
*
* We try two methods:
* a) Look for existing socket files (they only exist while php-fpm is running)
* b) Parse PHP-FPM pool config files for "listen = /path/to.sock" directives
* (catches sockets that exist but aren't active yet)
*
* When multiple PHP versions are installed, we prefer the highest version
* (e.g. php8.3-fpm over php7.4-fpm) since that's almost always what you want.
*/
function findFpmSocket(): ?string {
$candidates = [];
// Method a: look for existing socket files
// These glob patterns cover Debian (/run/php/), RHEL (/run/php-fpm/),
// and distros that still use /var/run/ instead of /run/
foreach ([
'/run/php/php*.sock',
'/var/run/php/php*.sock',
'/run/php-fpm/*.sock',
'/var/run/php-fpm/*.sock',
] as $g) {
foreach (glob($g) ?: [] as $s) {
// filetype() distinguishes socket files from regular files
if (@filetype($s) === 'socket') $candidates[$s] = $s;
}
}
// Method b: parse pool config "listen" directives
// Pool .conf files specify where FPM listens even when FPM isn't running yet
foreach (['/etc/php/*/fpm/pool.d/*.conf', '/etc/php-fpm.d/*.conf'] as $g) {
foreach (glob($g) ?: [] as $f) {
$c = (string) @file_get_contents($f);
if (preg_match('/^listen\s*=\s*(\/[^\s\r\n]+\.sock)/m', $c, $m)) {
if (@file_exists($m[1])) $candidates[$m[1]] = $m[1];
}
}
}
if (empty($candidates)) return null;
// Sort by PHP version number descending (e.g. php8.3 before php7.4)
uksort($candidates, function ($a, $b) {
preg_match('/(\d+\.\d+)/', $a, $ma);
preg_match('/(\d+\.\d+)/', $b, $mb);
return version_compare($mb[1] ?? '0', $ma[1] ?? '0');
});
return array_key_first($candidates);
}
// ─── discovery: service user ──────────────────────────────────────────────────
/**
* Detect what OS user the PHP-FPM pool runs as.
*
* Qbix proxy must connect to the PHP-FPM socket, so it needs to run as a
* user that has permission to read/write that socket. The safest choice is
* to run as the same user PHP-FPM's pool is configured for.
*
* We check:
* 1. The pool config "user =" line (most reliable)
* 2. Known defaults for common distros (www-data on Debian, apache on RHEL)
* 3. Fall back to www-data if nothing is found
*/
function detectServiceUser(): string {
// Read from PHP-FPM pool configs — look for "user = www-data" style lines
foreach (glob('/etc/php/*/fpm/pool.d/*.conf') ?: [] as $f) {
$c = (string) @file_get_contents($f);
if (preg_match('/^\s*user\s*=\s*(\w[\w-]*)/m', $c, $m)) {
// Verify this user actually exists on the system
if (function_exists('posix_getpwnam') && posix_getpwnam($m[1]) !== false) {
return $m[1];
}
}
}
// Common defaults: www-data (Debian/Ubuntu), apache (RHEL/CentOS/Fedora),
// nginx (Alpine/Arch), nobody (FreeBSD-style setups)
foreach (['www-data', 'apache', 'nginx', 'http', 'nobody'] as $u) {
if (function_exists('posix_getpwnam') && posix_getpwnam($u) !== false) return $u;
if (trim((string) shell_exec("id -u $u 2>/dev/null")) !== '') return $u;
}
return 'www-data'; // last resort default
}
// ─── web server detection ─────────────────────────────────────────────────────
/**
* Strip # comment lines from a config before scanning for PHP directives.
*
* Why: nginx, Apache, and Caddy all use # for comments. The Debian-packaged
* default nginx config has commented-out fastcgi_pass examples:
* # fastcgi_pass unix:/run/php/php7.4-fpm.sock;
* Without comment stripping, we'd incorrectly flag that file as a PHP config
* that needs patching, when it's actually just the commented example.
*/
function stripComments(string $txt): string {
return (string) preg_replace('/^\s*#[^\n]*/m', '', $txt);
}
/**
* Find nginx virtual host config files that handle PHP via FastCGI.
*
* We search both sites-enabled/ (active symlinks) and conf.d/ (drop-in configs).
* For each file, we strip comments then look for "fastcgi_pass" — that's the
* nginx directive that means "send this request directly to PHP-FPM". That's
* the directive we're replacing with "proxy_pass http://qbixproxy".
*
* We store both the symlink path (for display) and the real file path
* (for patching), so we always edit the canonical source in sites-available/.
*/
function findNginxPhpFiles(): array {
$found = [];
// sites-enabled/ contains symlinks; conf.d/ contains real files
// RedHat-family distros only use conf.d/ (no sites-enabled pattern)
$dirs = ['/etc/nginx/sites-enabled', '/etc/nginx/conf.d'];
foreach ($dirs as $dir) {
if (!is_dir($dir)) continue;
foreach (array_merge(glob("$dir/*.conf") ?: [], glob("$dir/*") ?: []) as $f) {
if (!is_file($f) && !is_link($f)) continue;
// Skip backup and failed-attempt files — they are not loaded by nginx
// and must never be patched (patching .bak creates .bak.bak chaos and
// leaves the actual live config untouched).
$base = basename($f);
if (preg_match('/\.(bak|failed|orig|save|old|disabled)(\.|$)/i', $base)) continue;
$real = realFile($f);
if (preg_match('/\.(bak|failed|orig|save|old|disabled)(\.|$)/i', basename($real))) continue;
// Strip comments before checking — avoids false positives from examples
$c = stripComments((string) @file_get_contents($real));
// Include files that need new patching (fastcgi_pass) OR
// files that need recovery (old-format patch with inline upstream block).
$needsPatch = stripos($c, 'fastcgi_pass') !== false;
$needsRecovery = strpos($c, 'upstream qbixproxy') !== false
&& strpos($c, 'proxy_pass http://qbixproxy') !== false;
if (($needsPatch || $needsRecovery) && !isset($found[$real])) {
$found[$real] = ['link' => $f, 'real' => $real, 'source' => $dir];
}
}
}
// Fallback: some setups define PHP handling directly in nginx.conf
if (empty($found)) {
$f = '/etc/nginx/nginx.conf';
$c = stripComments((string) @file_get_contents($f));
if (is_file($f) && stripos($c, 'fastcgi_pass') !== false) {
$found[$f] = ['link' => $f, 'real' => $f, 'source' => 'nginx.conf'];
}
}
return array_values($found);
}
/**
* Find Apache virtual host configs that handle PHP via mod_proxy_fcgi.
*
* Apache connects to PHP-FPM using mod_proxy_fcgi, which appears in configs as:
* <FilesMatch \.php$>
* SetHandler "proxy:unix:/run/php/php8.3-fpm.sock|fcgi://localhost"
* </FilesMatch>
* or as:
* ProxyPassMatch ^/(.*\.php(/.*)?)$ unix:/run/php/php8.3-fpm.sock|fcgi://...
*
* We look for any of these patterns (case-insensitive, comments stripped)
* to identify configs that need patching.
*/
function findApachePhpFiles(): array {
$found = [];
// Debian uses sites-enabled/, RedHat uses conf.d/ under /etc/httpd/
$dirs = ['/etc/apache2/sites-enabled', '/etc/apache2/conf.d', '/etc/httpd/conf.d'];
foreach ($dirs as $dir) {
if (!is_dir($dir)) continue;
foreach (array_merge(glob("$dir/*.conf") ?: [], glob("$dir/*") ?: []) as $f) {
if (!is_file($f) && !is_link($f)) continue;
// Skip backup and failed-attempt files
$base = basename($f);
if (preg_match('/\.(bak|failed|orig|save|old|disabled)(\.|$)/i', $base)) continue;
$real = realFile($f);
if (preg_match('/\.(bak|failed|orig|save|old|disabled)(\.|$)/i', basename($real))) continue;
$c = stripComments((string) @file_get_contents($real));
// Match FilesMatch PHP handler, mod_proxy_fcgi SetHandler, or ProxyPassMatch.
// Require a VirtualHost block — global PHP handler files (e.g. /etc/httpd/conf.d/php.conf
// that define a system-wide FilesMatch for all hosts) must not be patched here;
// they would affect every vhost and conflict with our per-site proxy_pass approach.
if (preg_match('/FilesMatch.*php|SetHandler.*fcgi|proxy:unix|ProxyPassMatch.*php/i', $c)
&& preg_match('/<VirtualHost/i', $c)
&& !isset($found[$real])
) {
$found[$real] = ['link' => $f, 'real' => $real, 'source' => $dir];
}
}
}
return array_values($found);
}
/**
* Find Caddy configs that handle PHP via php_fastcgi.
*
* Caddy makes PHP setup very simple with a single "php_fastcgi" directive:
* php_fastcgi unix//run/php/php8.3-fpm.sock
*
* This is Caddy's built-in shorthand that internally uses FastCGI. We replace
* it with a reverse_proxy block that uses HTTP to talk to Qbix proxy instead.
*/
function findCaddyPhpFiles(): array {
$found = [];
$candidates = [
'/etc/caddy/Caddyfile', // Debian/Ubuntu package
'/usr/local/etc/caddy/Caddyfile', // Homebrew/manual install
];
// Some setups split Caddyfile into per-site files in conf.d/
foreach (glob('/etc/caddy/conf.d/*.caddy') ?: [] as $f) $candidates[] = $f;
foreach (glob('/etc/caddy/conf.d/*.conf') ?: [] as $f) $candidates[] = $f;
foreach ($candidates as $f) {
if (!is_file($f)) continue;
if (preg_match('/\.(bak|failed|orig|save|old|disabled)(\.|$)/i', basename($f))) continue;
$real = realFile($f);
if (preg_match('/\.(bak|failed|orig|save|old|disabled)(\.|$)/i', basename($real))) continue;
$c = (string) @file_get_contents($real);
if (stripos($c, 'php_fastcgi') !== false && !isset($found[$real])) {
$found[$real] = ['link' => $f, 'real' => $real, 'source' => dirname($f)];
}
}
return array_values($found);
}
/**
* Detect which web servers are installed and have PHP configs to patch.
*
* Returns an array of ['server_name' => [array of file entries]].
* Each file entry has 'link' (displayed path), 'real' (file to patch),
* and 'source' (directory it came from).
*/
function detectWebServers(): array {
$detected = [];
// nginx — check common binary locations, then PATH
if (is_executable('/usr/sbin/nginx') || is_executable('/usr/bin/nginx')
|| trim((string) shell_exec('which nginx 2>/dev/null')) !== '')
{
$files = findNginxPhpFiles();
if ($files) $detected['nginx'] = $files;
}
// apache2 / httpd — Debian calls it apache2, RHEL calls it httpd
$apacheBin = null;
foreach (['/usr/sbin/apache2', '/usr/sbin/httpd', '/usr/bin/apache2'] as $b) {
if (is_executable($b)) { $apacheBin = $b; break; }
}
if (!$apacheBin) {
$r = trim((string) shell_exec('which apache2 2>/dev/null || which httpd 2>/dev/null'));
if ($r) $apacheBin = $r;
}
if ($apacheBin) {
$files = findApachePhpFiles();
if ($files) $detected['apache'] = $files;
}
// caddy
if (is_executable('/usr/bin/caddy') || is_executable('/usr/local/bin/caddy')
|| trim((string) shell_exec('which caddy 2>/dev/null')) !== '')
{
$files = findCaddyPhpFiles();
if ($files) $detected['caddy'] = $files;
}
return $detected;
}
// ─── nginx config patching ────────────────────────────────────────────────────
/**
* Walk forward from an opening brace, return the position of its matching
* closing brace.
*
* nginx/Caddy configs use nested braces for blocks. We need to find the
* end of location { } and server { } blocks without a full parser. This
* simple depth counter handles arbitrary nesting correctly as long as
* braces inside strings are rare (they are, in these config formats).
*/
function matchBrace(string $txt, int $pos): int {
$depth = 0;
for ($i = $pos, $n = strlen($txt); $i < $n; $i++) {
if ($txt[$i] === '{') $depth++;
elseif ($txt[$i] === '}' && --$depth === 0) return $i;
}
return -1; // unmatched brace (malformed config)
}
/**
* Remove all nginx location blocks that contain a fastcgi_pass directive.
*
* These blocks are the ones that currently send PHP requests directly to
* PHP-FPM. They look like:
*
* location ~ \.php$ {
* include snippets/fastcgi-php.conf;
* fastcgi_pass unix:/run/php/php8.3-fpm.sock;
* ...
* }
*
* We remove them entirely so we can replace them with a single
* "location / { proxy_pass http://qbixproxy; }" block.
*/
function removeNginxPhpLocations(string $txt): string {
$offset = 0;
// Match any "location <pattern> {" line (the \n prefix anchors to a new line)
while (preg_match('/\n[ \t]*location\s+[^\n{]+\{/s', $txt, $m, PREG_OFFSET_CAPTURE, $offset)) {
$lineStart = $m[0][1];
$braceOpen = $lineStart + strlen($m[0][0]) - 1;
$braceClose = matchBrace($txt, $braceOpen);
if ($braceClose === -1) { $offset = $lineStart + 1; continue; }
$block = substr($txt, $braceOpen, $braceClose - $braceOpen + 1);
if (stripos($block, 'fastcgi_pass') !== false) {
// Remove this block (from the newline before "location" to the closing })
$txt = substr($txt, 0, $lineStart) . substr($txt, $braceClose + 1);
// Don't advance offset — the text shifted left, retry at same position
} else {
$offset = $braceClose + 1;
}
}
return $txt;
}
/**
* Remove the generic "location / { ... }" block if it doesn't contain
* proxy_pass or fastcgi_pass.
*
* Why: many nginx PHP configs include a bare "location / { try_files ... }"
* block for handling requests before the PHP location. Once we add our own
* "location / { proxy_pass http://qbixproxy; }" there can only be one
* catch-all location / block, so we remove the old one.
*
* We keep it if it already has proxy_pass (already patched) or fastcgi_pass
* (will be removed by removeNginxPhpLocations instead).
*/
function removeNginxSlashLocation(string $txt): string {
$offset = 0;
while (preg_match('/\n[ \t]*location\s+\/\s*\{/', $txt, $m, PREG_OFFSET_CAPTURE, $offset)) {
$lineStart = $m[0][1];
$braceOpen = $lineStart + strlen($m[0][0]) - 1;
$braceClose = matchBrace($txt, $braceOpen);
if ($braceClose === -1) { $offset = $lineStart + 1; continue; }
$block = substr($txt, $braceOpen, $braceClose - $braceOpen + 1);
if (stripos($block, 'proxy_pass') === false && stripos($block, 'fastcgi_pass') === false) {
$txt = substr($txt, 0, $lineStart) . substr($txt, $braceClose + 1);
} else {
$offset = $braceClose + 1;
}
}
return $txt;
}
/**
* Patch an nginx virtual host config to route PHP through Qbix proxy.
*
* Before:
* server {
* location ~ \.php$ { fastcgi_pass unix:/run/php/...; }
* location / { try_files ...; }
* }
*
* After:
* upstream qbixproxy { server 127.0.0.1:8080; keepalive 32; }
* server {
* location ~* \.(css|js|jpg|...)$ { expires 30d; try_files ...; }
* location / { proxy_pass http://qbixproxy; ... }
* }
*
* The upstream block with keepalive 32 lets nginx reuse connections to
* Qbix proxy rather than opening a new TCP connection per request — an
* important performance optimization, since both processes are on the
* same machine (127.0.0.1:8080).
*
* Static files (CSS, JS, images) are still served by nginx directly.
* There's no reason to run them through the proxy — only PHP requests
* need the sanitization that Qbix proxy provides.
*/
function patchNginx(string $txt): string {
// Idempotency guard: if this config already proxies to qbixproxy,
// it's already patched — return unchanged
if (strpos($txt, 'proxy_pass http://qbixproxy') !== false) return $txt;
// Step 1: Remove existing PHP FastCGI location blocks
$txt = removeNginxPhpLocations($txt);
// Step 2: Remove the generic location / {} block (we'll add our own)
$txt = removeNginxSlashLocation($txt);
// Step 3: (upstream block is written once to 00-qbixproxy-upstream.conf,
// not into each site config — nginx forbids duplicate upstream definitions)
// Step 4: Define the replacement location blocks
// We use a heredoc for readability — the indentation matches typical nginx style
$locations = <<<'NGINX'
# Static files — served directly by nginx for performance.
# Images, CSS, JS etc. don't need the Qbix proxy sanitation pipeline.
location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg|woff2?|ttf|eot|mp4|webm|pdf)$ {
expires 30d;
add_header Cache-Control "public, immutable";
try_files $uri =404;
}
# Everything else (including all PHP requests) → Qbix proxy → PHP-FPM.
# proxy_http_version 1.1 + Connection "" enables HTTP keepalive to the proxy.
location / {
proxy_pass http://qbixproxy;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Connection "";
client_max_body_size 8m;
}
NGINX;
// Step 5: Insert the new location blocks before the closing } of the
// last server { } block. We scan for all server blocks to find the last one.
$lastClose = -1;
$offset = 0;
while (preg_match('/\bserver\s*\{/', $txt, $m, PREG_OFFSET_CAPTURE, $offset)) {
$bo = $m[0][1] + strlen($m[0][0]) - 1;
$bc = matchBrace($txt, $bo);
if ($bc === -1) break;
$lastClose = $bc;
$offset = $bc + 1;
}
if ($lastClose !== -1) {
$txt = substr($txt, 0, $lastClose) . $locations . "\n" . substr($txt, $lastClose);
}
// Clean up: collapse runs of 3+ blank lines to 2
return (string) preg_replace('/\n{3,}/', "\n\n", $txt);
}
/**
* Strip a legacy inline "upstream qbixproxy { ... }" block that older versions
* of this script injected directly into each site config. nginx forbids
* duplicate upstream definitions, so when two or more sites are present the
* second patchNginx() call would fail with "duplicate upstream 'qbixproxy'".
*
* Recovery path: if a file already has BOTH the inline upstream block AND the
* proxy_pass directive (i.e. it was patched by an older version of this script),
* we strip the upstream block so nginx is happy, then leave proxy_pass in place.
* The upstream is now defined once in 00-qbixproxy-upstream.conf.
*/
function stripNginxInlineUpstream(string $txt): string {
return (string) preg_replace(
'/\bupstream\s+qbixproxy\s*\{[^}]*\}\s*\n*/s',
'',
$txt
);
}
// ─── apache config patching ───────────────────────────────────────────────────
/**
* Patch an Apache virtual host config to route PHP through Qbix proxy.
*
* Before (using mod_proxy_fcgi):
* <VirtualHost *:443>
* <FilesMatch \.php$>
* SetHandler "proxy:unix:/run/php/php8.3-fpm.sock|fcgi://localhost"
* </FilesMatch>
* </VirtualHost>
*
* After (using mod_proxy_http → Qbix proxy):
* <VirtualHost *:443>
* ProxyPreserveHost On
* ProxyPass / http://127.0.0.1:8080/
* ProxyPassReverse / http://127.0.0.1:8080/
* RequestHeader set X-Real-IP "%{REMOTE_ADDR}s"
* RequestHeader set X-Forwarded-Proto "%{REQUEST_SCHEME}s"
* </VirtualHost>
*
* ProxyPreserveHost On: tells Apache to forward the original Host: header
* to Qbix proxy, which in turn forwards it to PHP-FPM. Without this,
* $_SERVER['HTTP_HOST'] in PHP would show "127.0.0.1:8080" instead of
* the real domain name.
*
* The RequestHeader lines inject real client IP and protocol into headers
* that PHP can read as $_SERVER['HTTP_X_REAL_IP'] and
* $_SERVER['HTTP_X_FORWARDED_PROTO']. Your PHP code can use these to
* know the original client's IP even though the immediate connection
* comes from the local proxy.
*
* Note: Apache also needs mod_proxy, mod_proxy_http, and mod_headers enabled.
* This script runs a2enmod for those automatically on Debian/Ubuntu.
*/
function patchApache(string $txt): string {
// Idempotency guard
if (stripos($txt, 'ProxyPass / http://127.0.0.1:8080') !== false) return $txt;
// Step 1: Remove <FilesMatch \.php$> ... </FilesMatch> blocks entirely.
// The regex uses 'is' flags: i=case-insensitive, s=dot matches newlines
// (so .*? spans the multiple lines inside the FilesMatch block).
$txt = preg_replace(
'/<FilesMatch\s+["\']?\\\\?\.php["\']?[^>]*>.*?<\/FilesMatch>/is',
'',
$txt
) ?? $txt;
// Step 2: Remove standalone SetHandler "proxy:..." lines
// (some configs use this outside a FilesMatch block)
$txt = preg_replace('/[ \t]*SetHandler\s+"proxy:[^"\n]+"[ \t]*\n/i', '', $txt) ?? $txt;
// Step 3: Remove ProxyPassMatch ^/.*\.php$ lines
// (another common pattern for PHP-FPM proxying in Apache)
$txt = preg_replace('/[ \t]*ProxyPassMatch\s+[^\n]*\.php[^\n]*\n/i', '', $txt) ?? $txt;
// Step 4: Insert our ProxyPass directives before </VirtualHost>
$proxy = <<<'APACHE'
# All requests → Qbix proxy → PHP-FPM.
# Qbix proxy listens on localhost:8080 and sanitizes every request
# before forwarding to PHP-FPM via FastCGI on its Unix socket.
ProxyPreserveHost On
ProxyPass / http://127.0.0.1:8080/
ProxyPassReverse / http://127.0.0.1:8080/
RequestHeader set X-Real-IP "%{REMOTE_ADDR}s"
RequestHeader set X-Forwarded-Proto "%{REQUEST_SCHEME}s"
APACHE;
$txt = preg_replace('/<\/VirtualHost>/i', $proxy . '</VirtualHost>', $txt, 1) ?? $txt;
// Clean up: collapse blank lines
return (string) preg_replace('/\n{3,}/', "\n\n", $txt);
}
// ─── caddy config patching ────────────────────────────────────────────────────
/**
* Patch a Caddyfile to route PHP through Qbix proxy.
*
* Before:
* example.com {
* root * /var/www/html
* php_fastcgi unix//run/php/php8.3-fpm.sock
* file_server
* encode gzip
* }
*
* After:
* example.com {
* root * /var/www/html
* encode gzip
* @static path *.css *.js *.jpg ...
* handle @static { file_server }
* handle { reverse_proxy 127.0.0.1:8080 { ... } }
* }
*
* Why we replace both php_fastcgi AND file_server:
* Caddy's php_fastcgi is a shorthand that expands to FastCGI + file_server
* internally. Once we replace php_fastcgi, the remaining standalone
* file_server directive would serve ALL requests as static files, which
* would break PHP. We replace both with two explicit handle blocks:
* - @static handle: Caddy serves matching file extensions directly (fast)
* - default handle: everything else goes through Qbix proxy
*
* The header_up directives pass the real client IP and protocol to the
* proxy (and onward to PHP) so $_SERVER['HTTP_X_REAL_IP'] works correctly.
*/
function patchCaddy(string $txt): string {
// Idempotency guard — MUST be checked BEFORE any removals below.
// If we're already patched, the file contains "reverse_proxy 127.0.0.1:8080"
// inside our handle @static block's sibling, which also contains "file_server".
// If we ran the removals first, we'd strip our own file_server on re-run.
if (strpos($txt, 'reverse_proxy 127.0.0.1:8080') !== false) return $txt;
// Step 1: Remove the php_fastcgi directive
// "php_fastcgi" can be followed by a Unix socket path or TCP address
$txt = preg_replace('/[ \t]*php_fastcgi[^\n]*\n/i', '', $txt) ?? $txt;
// Step 2: Remove the standalone "file_server" line.
// We use ^...$ anchoring (via /m flag) to match only a line that is
// JUST "file_server" (possibly with leading whitespace), not "file_server"
// inside a block with other directives. This avoids removing "file_server"
// from inside our replacement "handle @static { file_server }" block.
$txt = preg_replace('/^[ \t]*file_server[ \t]*\n/m', '', $txt) ?? $txt;
// Step 3: Define the replacement blocks
$replacement = <<<'CADDY'
@static path *.css *.js *.jpg *.jpeg *.png *.gif *.ico *.svg *.woff *.woff2 *.ttf *.eot *.mp4 *.webm *.pdf
# Static files — served directly by Caddy (fast, no proxy overhead)
handle @static {
file_server
}
# Everything else → Qbix proxy → PHP-FPM
handle {
reverse_proxy 127.0.0.1:8080 {
header_up X-Real-IP {remote_host}
header_up X-Forwarded-Proto {scheme}
}
}
CADDY;
// Step 4: Insert before the closing } of the first site block
// Caddy site blocks look like: example.com { ... }
if (preg_match('/\{/', $txt, $m, PREG_OFFSET_CAPTURE)) {
$bo = $m[0][1];
$bc = matchBrace($txt, $bo);
if ($bc !== -1) {
$txt = substr($txt, 0, $bc) . "\n" . $replacement . "\n" . substr($txt, $bc);
}
}
return $txt;
}
// ─── dry-run diff preview ─────────────────────────────────────────────────────
/**
* Show the key lines that will change in a config file.
*
* Rather than dumping the full diff, we highlight only the lines that matter
* for security: the PHP directives being removed (-) and the proxy directives
* being added (+). This gives a clear, scannable answer to "what exactly
* will this script change in my config?"
*/
function showKeyChanges(string $server, string $orig, string $patched): void {
$origLines = array_map('rtrim', explode("\n", $orig));
$patchedLines = array_map('rtrim', explode("\n", $patched));
// Build lookup sets for fast comparison
$origSet = array_flip($origLines);
$patchedSet = array_flip($patchedLines);
// Patterns for lines we're removing (PHP-to-FPM directives)
$removePattern = '/fastcgi_pass|php_fastcgi|FilesMatch.*php|SetHandler.*fcgi|proxy:unix|ProxyPassMatch/i';
// Patterns for key lines we're adding (proxy directives)
$addPattern = '/proxy_pass\s+http:\/\/qbixproxy|ProxyPass\s+\/\s+http:\/\/127|'
. 'reverse_proxy\s+127\.0\.0\.1:8080|'
. 'ProxyPreserveHost|handle_up\s+X-Real|header_up\s+X-Real/i';
$shown = 0;
foreach ($origLines as $line) {
$t = rtrim($line);
if ($t !== '' && preg_match($removePattern, $t) && !isset($patchedSet[$t])) {
diff_rem(trim($line));
$shown++;
}
}
foreach ($patchedLines as $line) {
$t = rtrim($line);
if ($t !== '' && preg_match($addPattern, $t) && !isset($origSet[$t])) {
diff_add(trim($line));
$shown++;
}
}
if ($shown === 0) {
sub("(no key PHP directives changed — already patched or nothing to change)");
}
}
// ─── config file generators ───────────────────────────────────────────────────
/**
* Default constraints block applied to every backend.
*
* These are intentionally conservative. After setup, edit
* /etc/qbixproxy/qbixproxy.json to adjust limits per-site.
*/
function defaultConstraints(): array {
return [
'max_body_bytes' => 8388608,
'allowed_methods' => ['GET','POST','PUT','PATCH','DELETE','HEAD','OPTIONS'],
'allowed_content_types' => [
'application/x-www-form-urlencoded',
'multipart/form-data',
'application/json',
'text/plain',
],
'upload' => [
'max_files' => 20,
'max_file_bytes' => 10485760,
'allowed_extensions' => [
'.jpg','.jpeg','.png','.gif','.webp',
'.pdf','.zip','.doc','.docx','.xls','.xlsx',
],
],
];
}
/**
* Generate the qbixproxy.json config file.
*
* This tells Qbix proxy:
* - Where PHP-FPM's Unix socket is (so it can forward validated requests)
* - What document root to use (passed as DOCUMENT_ROOT in FastCGI variables)
* - What Host headers each backend should handle (virtual hosting)
* - What constraints to enforce (max body size, allowed methods, upload limits)
*
* When $sites is provided (multi-site mode), one backend entry is generated per
* site, each with its own hosts[], document_root, and the shared FPM socket.
* A final catch-all backend (no hosts key) is added for unrecognised Host headers.
*
* When $sites is empty, a single catch-all backend is generated (single-site mode,
* backwards-compatible with configs that have no hosts key).
*
* @param string $socket PHP-FPM Unix socket shared by all backends
* @param string $docRoot Fallback document root (used for the catch-all backend)
* @param array $sites Optional: [ ['hosts'=>[...], 'document_root'=>'...'], ... ]
*/
function makeQbixproxyJson(string $socket, string $docRoot, array $sites = []): string {
$backends = [];
if (!empty($sites)) {
// Multi-site mode: one backend per detected virtual host
foreach ($sites as $i => $site) {
$key = 'php-site-' . ($i + 1);
$backends[$key] = [
'socket' => $socket,
'protocol' => 'fastcgi',
'document_root' => $site['document_root'],
'hosts' => $site['hosts'],
'routes' => ['/'],
'constraints' => defaultConstraints(),
];
}
// Catch-all for any host not explicitly listed above
$backends['php-default'] = [
'socket' => $socket,
'protocol' => 'fastcgi',
'document_root' => $docRoot,
'routes' => ['/'],
'constraints' => defaultConstraints(),
];
} else {
// Single-site mode: one catch-all backend (no hosts key)
$backends['php'] = [
'socket' => $socket,
'protocol' => 'fastcgi',
'document_root' => $docRoot,
'routes' => ['/'],
'constraints' => defaultConstraints(),
];
}
return json_encode(['backends' => $backends], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n";
}
/**
* Generate the systemd service unit file for qbixproxy.
*
* Key security settings in the [Service] section:
* User/Group: Run as the web server's user (same as PHP-FPM's pool user),
* not root. This ensures the process can access the FPM socket.
* NoNewPrivileges: The process can never gain elevated privileges via
* setuid/setgid or Linux capabilities — even if the binary is exploited.
* ProtectSystem=strict: The entire filesystem is read-only for the process
* (except /run, /tmp, and paths explicitly listed for writing). Note: this
* restricts writes, not reads — the proxy still has read access to the
* filesystem outside /etc/qbixproxy. It cannot write PHP source or database
* config, but it can read them if it were compromised.
* ProtectHome: Blocks access to /home, /root, /run/user entirely.
* PrivateTmp: The process gets its own private /tmp that no other process
* can see or write to.
* ReadOnlyPaths=/etc/qbixproxy: Reinforces that the config directory cannot
* be modified by the proxy even if compromised.
*
* @param string $binaryPath Absolute path to the qbixproxy binary.
*/
function makeSystemdUnit(string $serviceUser = 'www-data', string $binaryPath = '/usr/local/bin/qbixproxy'): string {
$exec = escapeshellarg($binaryPath);
// Strip the shell-quoting for the unit file value (systemd doesn't use sh quoting here)
$exec = $binaryPath;
return <<<UNIT