-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathindex.php
More file actions
7547 lines (7030 loc) · 305 KB
/
index.php
File metadata and controls
7547 lines (7030 loc) · 305 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
<?php
/**
* PHProxy v1.2.0
*
* Single-file web HTTP/HTTPS proxy in PHP. Drop into any PHP 8.1+ web root
* and open it — no dependencies, no build step, no `vendor/`, no `files/`
* directory. Works under any filename (rename to proxy.php if you like).
*
* @version v1.2.0
* @author Miglen Evlogiev (revive), PhoenixPeca, Biojet1, Quix0r, dacendo
* @copyright 2002-2007 A.A. (whitefyre); 2015-2019 contributors; 2025-2026 revive
* @license GNU GPL v3
* @repo https://github.com/PHProxy/phproxy
*/
/* PRODUCTIVE: */ error_reporting(0);
// DEVELOP: error_reporting(E_ALL); ini_set('display_errors', '1');
// --- ASSET DISPATCHER --------------------------------------------------
// Serves the proxy's own CSS via ?asset=<name>. Keeps the script
// self-contained — no files/ directory needed.
if (isset($_GET['asset'])) {
header('Cache-Control: public, max-age=3600');
switch ((string) $_GET['asset']) {
case 'index.css': header('Content-Type: text/css; charset=utf-8'); echo phproxy_index_css(); exit;
case 'panel.css': header('Content-Type: text/css; charset=utf-8'); echo phproxy_panel_css(); exit;
case 'netcheck.js': header('Content-Type: application/javascript; charset=utf-8'); echo phproxy_netcheck_js(); exit;
}
http_response_code(404);
exit;
}
// --- JSON API DISPATCHER (?api=fetch) -----------------------------------
// POST with a JSON body — proxy makes the HTTP request and returns either
// JSON (default) or the raw upstream response.
//
// Body schema:
// {
// "url": "https://example.com/" (required),
// "method": "GET" | "POST" | ... (default: GET),
// "headers": { "Name": "value", ... },
// "cookies": { "name": "value", ... },
// "body": "string",
// "timeout": 30,
// "follow_redirects": false,
// "max_redirects": 5,
// "verify_ssl": true,
// "return": "json" | "raw" (default: json)
// }
// Helper used by the new network-check APIs (dns / portcheck / cert).
$phproxy_api_validate_host = function (string $host): bool {
if ($host === '' || strlen($host) > 253) return false;
if (!preg_match('/^[a-zA-Z0-9._:-]+$/', $host)) return false;
$block = '#^127\.|192\.168\.|10\.|172\.(1[6-9]|2[0-9]|3[01])\.|^localhost$|^::1$|^0+\.0+\.0+\.0+$#i';
if (preg_match($block, $host)) return false;
return true;
};
// --- DNS LOOKUP API (?api=dns&host=example.com&type=A) -----------------
if (isset($_GET['api']) && $_GET['api'] === 'dns') {
header('Content-Type: application/json; charset=utf-8');
$host = (string) ($_GET['host'] ?? '');
$type = strtoupper((string) ($_GET['type'] ?? 'A'));
if (!$phproxy_api_validate_host($host)) {
http_response_code(400);
echo json_encode(['ok' => false, 'error' => 'Invalid or blacklisted host']);
exit;
}
$types = [
'A' => DNS_A, 'AAAA' => DNS_AAAA, 'MX' => DNS_MX,
'TXT' => DNS_TXT, 'NS' => DNS_NS, 'SOA' => DNS_SOA,
'CAA' => DNS_CAA, 'CNAME' => DNS_CNAME,'PTR' => DNS_PTR,
'SRV' => DNS_SRV, 'ANY' => DNS_ANY,
];
if (!isset($types[$type])) {
http_response_code(400);
echo json_encode(['ok' => false, 'error' => 'Unknown record type', 'supported' => array_keys($types)]);
exit;
}
$started = microtime(true);
$records = @dns_get_record($host, $types[$type]);
$ms = (int) ((microtime(true) - $started) * 1000);
if ($records === false) {
echo json_encode(['ok' => false, 'host' => $host, 'type' => $type, 'error' => 'Lookup failed', 'duration_ms' => $ms]);
exit;
}
echo json_encode(['ok' => true, 'host' => $host, 'type' => $type, 'records' => $records, 'duration_ms' => $ms], JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
exit;
}
// --- PORT CHECK API (?api=portcheck&host=example.com&port=443) ---------
// `port` accepts a single port (443), an inclusive range (80-443) or a
// comma-separated mix (22,80,443,8000-8010). Hard cap is 128 ports per
// request; default per-port timeout is 1.0s, override with ?timeout=…
// (clamped 0.1–5.0). Response always carries a `results` array.
if (isset($_GET['api']) && $_GET['api'] === 'portcheck') {
header('Content-Type: application/json; charset=utf-8');
$host = (string) ($_GET['host'] ?? '');
$port_spec = (string) ($_GET['port'] ?? '');
$timeout = (float) ($_GET['timeout'] ?? 1.0);
if ($timeout < 0.1) $timeout = 0.1;
if ($timeout > 5.0) $timeout = 5.0;
if (!$phproxy_api_validate_host($host)) {
http_response_code(400);
echo json_encode(['ok' => false, 'error' => 'Invalid or blacklisted host']);
exit;
}
$ports = phproxy_parse_port_spec($port_spec);
if ($ports === false) {
http_response_code(400);
echo json_encode(['ok' => false, 'error' => 'Invalid port spec. Examples: 443, 80-443, 22,80,443,8000-8010', 'received' => $port_spec]);
exit;
}
if (count($ports) > 128) {
http_response_code(400);
echo json_encode(['ok' => false, 'error' => 'Too many ports requested (max 128)', 'requested' => count($ports)]);
exit;
}
// Streaming mode: emit NDJSON — one event per line, flushed immediately,
// so the UI can show partial progress as each port comes back. Triggered
// by ?stream=1. Default remains the batched JSON envelope so existing
// CLI consumers don't break.
$stream = !empty($_GET['stream']);
if ($stream) {
while (ob_get_level() > 0) @ob_end_clean();
@ob_implicit_flush(true);
header('Content-Type: application/x-ndjson; charset=utf-8');
header('X-Accel-Buffering: no'); // nginx hint
header('Cache-Control: no-cache, no-store');
$emit = function (array $obj): void {
echo json_encode($obj, JSON_UNESCAPED_SLASHES), "\n";
@flush();
};
$emit([
'event' => 'start',
'host' => $host,
'port_spec' => $port_spec,
'count' => count($ports),
'ports' => $ports,
'timeout_s' => $timeout,
]);
$scan_started = microtime(true);
$open = $closed = 0;
foreach ($ports as $p) {
if (connection_aborted()) break;
$t0 = microtime(true);
$sock = @stream_socket_client("tcp://$host:$p", $errno, $errstr, $timeout);
$ms = (int) ((microtime(true) - $t0) * 1000);
if ($sock === false) {
$closed++;
$emit(['event' => 'result', 'port' => $p, 'reachable' => false, 'error' => $errstr ?: 'connect failed', 'errno' => (int) $errno, 'latency_ms' => $ms]);
} else {
fclose($sock);
$open++;
$emit(['event' => 'result', 'port' => $p, 'reachable' => true, 'latency_ms' => $ms]);
}
}
$emit([
'event' => 'end',
'open' => $open,
'closed' => $closed,
'duration_ms' => (int) ((microtime(true) - $scan_started) * 1000),
]);
exit;
}
// Batched mode (default) — one JSON envelope at the end.
$scan_started = microtime(true);
$results = [];
foreach ($ports as $p) {
$t0 = microtime(true);
$sock = @stream_socket_client("tcp://$host:$p", $errno, $errstr, $timeout);
$ms = (int) ((microtime(true) - $t0) * 1000);
if ($sock === false) {
$results[] = ['port' => $p, 'reachable' => false, 'error' => $errstr ?: 'connect failed', 'errno' => (int) $errno, 'latency_ms' => $ms];
} else {
fclose($sock);
$results[] = ['port' => $p, 'reachable' => true, 'latency_ms' => $ms];
}
}
$duration = (int) ((microtime(true) - $scan_started) * 1000);
$open = 0;
foreach ($results as $r) if (!empty($r['reachable'])) $open++;
echo json_encode([
'ok' => true,
'host' => $host,
'port_spec' => $port_spec,
'count' => count($results),
'open' => $open,
'closed' => count($results) - $open,
'timeout_s' => $timeout,
'duration_ms' => $duration,
'results' => $results,
], JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
exit;
}
/**
* Parse a port spec — single, range, or comma list — into a sorted,
* deduped array of ints. Returns false on any syntax error or out-of-range.
* "443" → [443]
* "80-443" → [80, 81, …, 443]
* "22,80,443" → [22, 80, 443]
* "80,8000-8010" → [80, 8000, …, 8010]
*/
function phproxy_parse_port_spec(string $spec): array|false
{
$spec = trim($spec);
if ($spec === '') return false;
$set = [];
foreach (explode(',', $spec) as $chunk) {
$chunk = trim($chunk);
if ($chunk === '') continue;
if (strpos($chunk, '-') !== false) {
$parts = explode('-', $chunk, 2);
$a = (int) trim($parts[0]);
$b = (int) trim($parts[1]);
if ($a < 1 || $a > 65535 || $b < 1 || $b > 65535 || $b < $a) return false;
for ($i = $a; $i <= $b; $i++) $set[$i] = true;
} else {
if (!ctype_digit($chunk)) return false;
$p = (int) $chunk;
if ($p < 1 || $p > 65535) return false;
$set[$p] = true;
}
if (count($set) > 1024) return false; // hard ceiling to prevent memory abuse; dispatcher rejects >128 with a clearer error
}
if (empty($set)) return false;
ksort($set);
return array_keys($set);
}
// --- SSL CERT INSPECTOR API (?api=cert&host=example.com&port=443) ------
if (isset($_GET['api']) && $_GET['api'] === 'cert') {
header('Content-Type: application/json; charset=utf-8');
$host = (string) ($_GET['host'] ?? '');
$port = (int) ($_GET['port'] ?? 443);
if (!$phproxy_api_validate_host($host)) {
http_response_code(400);
echo json_encode(['ok' => false, 'error' => 'Invalid or blacklisted host']);
exit;
}
if ($port < 1 || $port > 65535) {
http_response_code(400);
echo json_encode(['ok' => false, 'error' => 'Invalid port (1–65535)']);
exit;
}
// First handshake — let OpenSSL negotiate freely so we capture the
// server's preferred TLS version + cipher AND the peer cert chain.
$ctx = stream_context_create([
'ssl' => [
'capture_peer_cert' => true,
'capture_peer_cert_chain' => true,
'verify_peer' => false,
'verify_peer_name' => false,
'SNI_enabled' => true,
'peer_name' => $host,
],
]);
$started = microtime(true);
$sock = @stream_socket_client("ssl://$host:$port", $errno, $errstr, 10, STREAM_CLIENT_CONNECT, $ctx);
$ms = (int) ((microtime(true) - $started) * 1000);
if ($sock === false) {
echo json_encode(['ok' => false, 'host' => $host, 'port' => $port, 'error' => $errstr ?: 'SSL handshake failed', 'errno' => (int) $errno, 'latency_ms' => $ms]);
exit;
}
$meta_main = stream_get_meta_data($sock);
$params = stream_context_get_params($sock);
fclose($sock);
$leaf = $params['options']['ssl']['peer_certificate'] ?? null;
$chain = $params['options']['ssl']['peer_certificate_chain'] ?? [];
if (!$leaf) {
echo json_encode(['ok' => false, 'host' => $host, 'port' => $port, 'error' => 'No peer certificate received']);
exit;
}
$parse_cert = function ($cert) {
$p = @openssl_x509_parse($cert);
if (!is_array($p)) return null;
// SAN entries — flatten DNS:/IP Address: prefixes for display
$san = [];
if (!empty($p['extensions']['subjectAltName'])) {
foreach (explode(',', $p['extensions']['subjectAltName']) as $entry) {
$entry = trim($entry);
if (str_starts_with($entry, 'DNS:')) $san[] = substr($entry, 4);
elseif (str_starts_with($entry, 'IP Address:')) $san[] = substr($entry, 11);
elseif ($entry !== '') $san[] = $entry;
}
}
// Public key — type, size, curve (EC), and the public-key PEM block
$key_type = ''; $key_bits = 0; $key_curve = ''; $pub_pem = '';
$pub = @openssl_pkey_get_public($cert);
if ($pub !== false) {
$details = @openssl_pkey_get_details($pub);
if (is_array($details)) {
$key_bits = (int) ($details['bits'] ?? 0);
$pub_pem = (string) ($details['key'] ?? '');
$type_const = $details['type'] ?? -1;
if ($type_const === OPENSSL_KEYTYPE_RSA) $key_type = 'RSA';
elseif ($type_const === OPENSSL_KEYTYPE_DSA) $key_type = 'DSA';
elseif ($type_const === OPENSSL_KEYTYPE_DH) $key_type = 'DH';
elseif (defined('OPENSSL_KEYTYPE_EC') && $type_const === OPENSSL_KEYTYPE_EC) {
$key_type = 'EC';
$key_curve = (string) ($details['ec']['curve_name'] ?? '');
}
}
}
// Fingerprints — colon-separated like every cert tool prints them
$fmt_fp = function (string $hex): string {
$hex = strtoupper($hex);
return implode(':', str_split($hex, 2));
};
$fp_sha256 = @openssl_x509_fingerprint($cert, 'sha256') ?: '';
$fp_sha1 = @openssl_x509_fingerprint($cert, 'sha1') ?: '';
$fp_md5 = @openssl_x509_fingerprint($cert, 'md5') ?: '';
// Cert in PEM form (raw, full)
$pem = '';
@openssl_x509_export($cert, $pem);
$valid_from = $p['validFrom_time_t'] ?? 0;
$valid_to = $p['validTo_time_t'] ?? 0;
return [
'version' => (int) ($p['version'] ?? 0) + 1, // X.509 reports 0/1/2; humans say v1/v2/v3
'serial_hex' => $p['serialNumberHex'] ?? '',
'serial_dec' => (string) ($p['serialNumber'] ?? ''),
'subject' => $p['name'] ?? '',
'subject_parts' => $p['subject'] ?? [], // full DN as keyed array (CN, O, OU, C, ST, L, …)
'subject_cn' => $p['subject']['CN'] ?? '',
'subject_org' => $p['subject']['O'] ?? '',
'issuer_dn' => isset($p['issuer']) ? phproxy_dn_join($p['issuer']) : '',
'issuer_parts' => $p['issuer'] ?? [],
'issuer_cn' => $p['issuer']['CN'] ?? '',
'issuer_org' => $p['issuer']['O'] ?? '',
'valid_from' => $valid_from ? gmdate('Y-m-d\TH:i:s\Z', $valid_from) : '',
'valid_to' => $valid_to ? gmdate('Y-m-d\TH:i:s\Z', $valid_to) : '',
'days_left' => $valid_to ? (int) floor(($valid_to - time()) / 86400) : 0,
'san' => $san,
'sig_algorithm' => $p['signatureTypeSN'] ?? '',
'sig_algorithm_long' => $p['signatureTypeLN'] ?? '',
'sig_oid' => isset($p['signatureTypeNID']) ? (string) $p['signatureTypeNID'] : '',
'purposes' => $p['purposes'] ?? [],
'extensions' => $p['extensions'] ?? [], // all extensions, raw text per OpenSSL
'key_type' => $key_type,
'key_bits' => $key_bits,
'key_curve' => $key_curve,
'public_key_pem' => $pub_pem,
'fingerprints' => [
'sha256' => $fp_sha256 ? $fmt_fp($fp_sha256) : '',
'sha1' => $fp_sha1 ? $fmt_fp($fp_sha1) : '',
'md5' => $fp_md5 ? $fmt_fp($fp_md5) : '',
],
'pem' => $pem,
];
};
$cert_info = $parse_cert($leaf);
$chain_info = [];
foreach ($chain as $c) {
$ci = $parse_cert($c);
if ($ci !== null) $chain_info[] = $ci;
}
// Probe TLS versions individually. For each, force the version via
// crypto_method and record which the server actually accepts plus
// the cipher it negotiates. ~4 extra ~100-500ms handshakes.
$tls_probes = [
'TLSv1.3' => defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') ? STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT : 0,
'TLSv1.2' => defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT') ? STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT : 0,
'TLSv1.1' => defined('STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT') ? STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT : 0,
'TLSv1.0' => defined('STREAM_CRYPTO_METHOD_TLSv1_CLIENT') ? STREAM_CRYPTO_METHOD_TLSv1_CLIENT : 0,
];
$tls_results = [];
foreach ($tls_probes as $label => $method) {
if ($method === 0) {
$tls_results[] = ['version' => $label, 'supported' => false, 'error' => 'OpenSSL on this PHP build cannot speak ' . $label];
continue;
}
$pctx = stream_context_create([
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
'SNI_enabled' => true,
'peer_name' => $host,
'crypto_method' => $method,
],
]);
$pt0 = microtime(true);
$psock = @stream_socket_client("ssl://$host:$port", $en, $es, 5, STREAM_CLIENT_CONNECT, $pctx);
$pms = (int) ((microtime(true) - $pt0) * 1000);
if ($psock === false) {
$tls_results[] = ['version' => $label, 'supported' => false, 'error' => $es ?: 'handshake refused', 'latency_ms' => $pms];
continue;
}
$pmeta = stream_get_meta_data($psock);
@fclose($psock);
$crypto = $pmeta['crypto'] ?? [];
$tls_results[] = [
'version' => $label,
'supported' => true,
'cipher_name' => (string) ($crypto['cipher_name'] ?? ''),
'cipher_bits' => (int) ($crypto['cipher_bits'] ?? 0),
'cipher_version' => (string) ($crypto['cipher_version'] ?? ''),
'protocol' => (string) ($crypto['protocol'] ?? ''),
'latency_ms' => $pms,
];
}
// Negotiated handshake summary (what the server picked when given free choice).
$main_crypto = $meta_main['crypto'] ?? [];
echo json_encode([
'ok' => true,
'host' => $host,
'port' => $port,
'negotiated' => [
'protocol' => (string) ($main_crypto['protocol'] ?? ''),
'cipher_name' => (string) ($main_crypto['cipher_name'] ?? ''),
'cipher_bits' => (int) ($main_crypto['cipher_bits'] ?? 0),
'cipher_version' => (string) ($main_crypto['cipher_version'] ?? ''),
],
'tls_versions' => $tls_results,
'leaf' => $cert_info,
'chain' => $chain_info,
'chain_length' => count($chain_info),
'duration_ms' => $ms,
], JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
exit;
}
// --- IP INFO API (?api=ipinfo[&ip=1.2.3.4]) ------------------------------
// Returns information about the client, the server, and the server's
// outgoing IP — plus reverse DNS, the X-Forwarded-For chain, request
// headers and host info. Pure local PHP — no external lookups, no
// library, no API key. Geo / ASN / city are intentionally not included.
if (isset($_GET['api']) && $_GET['api'] === 'ipinfo') {
header('Content-Type: application/json; charset=utf-8');
$started = microtime(true);
// If the caller passed ?ip=…, that's the single IP we describe.
$custom_ip = trim((string) ($_GET['ip'] ?? ''));
if ($custom_ip !== '' && !filter_var($custom_ip, FILTER_VALIDATE_IP)) {
http_response_code(400);
echo json_encode(['ok' => false, 'error' => 'Invalid IP address', 'received' => $custom_ip]);
exit;
}
$remote = (string) ($_SERVER['REMOTE_ADDR'] ?? '');
$xff_raw = (string) ($_SERVER['HTTP_X_FORWARDED_FOR'] ?? '');
$xff_chain = [];
if ($xff_raw !== '') {
foreach (explode(',', $xff_raw) as $h) {
$h = trim($h);
if ($h !== '' && filter_var($h, FILTER_VALIDATE_IP)) $xff_chain[] = $h;
}
}
// Prefer the first XFF entry (original client) when behind a reverse proxy.
$client_ip = !empty($xff_chain) ? $xff_chain[0] : $remote;
// Server's own primary IP via gethostbyname(hostname). Often the
// internal Docker IP — useful but not "what the internet sees".
$hostname = gethostname() ?: '';
$server_ip = '';
if ($hostname !== '') {
$resolved = @gethostbyname($hostname);
if ($resolved !== false && $resolved !== $hostname) $server_ip = $resolved;
}
// Real outgoing IP — what the internet actually sees when this server
// makes outbound HTTP calls. UDP "connect" trick: no packets sent,
// but the kernel picks the outgoing interface so the local socket
// name gives us the right answer.
$outgoing_ip = phproxy_outgoing_ip();
$shape = function (string $ip): array {
if ($ip === '') return ['ip' => ''];
$is_priv = !filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
return [
'ip' => $ip,
'family' => str_contains($ip, ':') ? 'IPv6' : 'IPv4',
'is_private' => (bool) $is_priv,
'reverse' => $is_priv ? '' : (@gethostbyaddr($ip) ?: ''),
];
};
if ($custom_ip !== '') {
echo json_encode([
'ok' => true,
'lookup' => $shape($custom_ip),
'duration_ms' => (int) ((microtime(true) - $started) * 1000),
], JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
exit;
}
echo json_encode([
'ok' => true,
'client' => $shape($client_ip),
'server' => $shape($server_ip),
'outgoing' => $shape($outgoing_ip),
'forwarded' => array_map($shape, $xff_chain),
'request' => [
'method' => $_SERVER['REQUEST_METHOD'] ?? '',
'protocol' => isset($_SERVER['HTTPS']) || ($_SERVER['SERVER_PORT'] ?? '') == '443' ? 'HTTPS' : 'HTTP',
'remote_addr' => $remote,
'host_header' => $_SERVER['HTTP_HOST'] ?? '',
'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
'accept_language' => $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? '',
'accept' => $_SERVER['HTTP_ACCEPT'] ?? '',
'referer' => $_SERVER['HTTP_REFERER'] ?? '',
'dnt' => $_SERVER['HTTP_DNT'] ?? '',
'sec_gpc' => $_SERVER['HTTP_SEC_GPC'] ?? '',
'sec_ch_ua' => $_SERVER['HTTP_SEC_CH_UA'] ?? '',
'sec_ch_ua_mobile'=> $_SERVER['HTTP_SEC_CH_UA_MOBILE']?? '',
'sec_ch_ua_platform' => $_SERVER['HTTP_SEC_CH_UA_PLATFORM'] ?? '',
],
'host' => [
'hostname' => $hostname,
'php_version' => PHP_VERSION,
'php_os' => PHP_OS,
'server_software' => $_SERVER['SERVER_SOFTWARE'] ?? '',
'server_port' => $_SERVER['SERVER_PORT'] ?? '',
],
'duration_ms' => (int) ((microtime(true) - $started) * 1000),
], JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
exit;
}
/**
* Build a single-line DN string from the keyed array openssl_x509_parse()
* returns. Order matches what `openssl x509 -text` prints.
*/
function phproxy_dn_join(array $parts): string
{
$order = ['C', 'ST', 'L', 'O', 'OU', 'CN', 'emailAddress', 'serialNumber'];
$out = [];
foreach ($order as $k) {
if (isset($parts[$k]) && $parts[$k] !== '') $out[] = "$k=" . (is_array($parts[$k]) ? implode('+', $parts[$k]) : $parts[$k]);
}
foreach ($parts as $k => $v) {
if (in_array($k, $order, true)) continue;
if ($v === '' || $v === null) continue;
$out[] = "$k=" . (is_array($v) ? implode('+', $v) : $v);
}
return implode(', ', $out);
}
/**
* Determine the outgoing IPv4 address this server uses when reaching out
* to the wider internet. UDP "connect" trick: no packets are actually
* sent, but the kernel picks the outgoing interface so stream_socket_get_name
* on the local side returns the right answer.
*/
function phproxy_outgoing_ip(): string
{
$sock = @stream_socket_client('udp://1.1.1.1:53', $en, $es, 1);
if ($sock === false) {
$sock = @stream_socket_client('udp://8.8.8.8:53', $en, $es, 1);
}
if ($sock === false) return '';
$name = @stream_socket_get_name($sock, false); // local side
@fclose($sock);
if (!is_string($name) || $name === '') return '';
// "1.2.3.4:54321" or "[::1]:54321" — strip port.
if (preg_match('/^\[([^\]]+)\]:\d+$/', $name, $m)) return $m[1];
if (preg_match('/^([0-9.]+):\d+$/', $name, $m)) return $m[1];
return $name;
}
if (isset($_GET['api']) && $_GET['api'] === 'fetch') {
// Helper for any JSON error response in this dispatcher
$api_json_err = function (int $status, string $msg, array $extra = []): void {
http_response_code($status);
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['ok' => false, 'error' => $msg] + $extra, JSON_UNESCAPED_SLASHES);
exit;
};
if ($_SERVER['REQUEST_METHOD'] !== 'POST') $api_json_err(405, 'POST required');
$raw_in = file_get_contents('php://input') ?: '';
$req_in = json_decode($raw_in, true);
if (!is_array($req_in) || empty($req_in['url'])) $api_json_err(400, 'Invalid JSON body or missing "url"');
// SSRF guard — refuse the same blacklisted host ranges the browser flow
// blocks (loopback / RFC1918). Replicate the regex here to fail fast.
$api_host_block = '#^127\.|192\.168\.|10\.|172\.(1[6-9]|2[0-9]|3[01])\.|localhost$|^::1$#i';
$api_url_host = (string) (@parse_url((string) $req_in['url'], PHP_URL_HOST) ?: '');
if ($api_url_host === '' || preg_match($api_host_block, $api_url_host)) {
$api_json_err(400, 'Target host blacklisted or unparseable', ['host' => $api_url_host]);
}
$api_result = phproxy_api_fetch($req_in);
if (($req_in['return'] ?? 'json') === 'raw') {
// Emit the upstream response verbatim. Drop hop-by-hop and encoding
// headers we've already decoded for the client.
if (isset($api_result['status'])) http_response_code($api_result['status']);
$first_ct = true;
foreach (($api_result['headers'] ?? []) as $hname => $hvalue) {
$lhname = strtolower($hname);
if (in_array($lhname, ['transfer-encoding', 'content-encoding', 'content-length', 'connection'], true)) continue;
// For Content-Type, replace any previous (default Apache sets one);
// for everything else, append.
$replace = ($lhname === 'content-type' && $first_ct);
header($hname . ': ' . $hvalue, $replace);
if ($lhname === 'content-type') $first_ct = false;
}
echo $api_result['body_raw'] ?? '';
exit;
}
// JSON envelope. UTF-8 bodies go in directly, binary gets base64'd.
header('Content-Type: application/json; charset=utf-8');
$body_raw = $api_result['body_raw'] ?? '';
if ($body_raw !== '' && mb_check_encoding($body_raw, 'UTF-8')) {
$api_result['body'] = $body_raw;
$api_result['body_encoding'] = 'utf8';
} else {
$api_result['body'] = base64_encode($body_raw);
$api_result['body_encoding'] = 'base64';
}
unset($api_result['body_raw']);
echo json_encode($api_result, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
exit;
}
//
// CONFIGURABLE OPTIONS
//
$_config =
[
'url_var_name' => '_proxurl',
'flags_var_name' => '_proxfl',
'get_form_name' => '_proxgfn',
'basic_auth_var_name' => '_proxba',
'site_name' => 'PHProxy',
'max_file_size' => -1,
'allow_hotlinking' => 0,
'upon_hotlink' => 1,
'compress_output' => 0,
];
// NOTE on order: new flags MUST be appended to the head of $_flags so the
// bitfield positions of existing flags stay stable (the cookie stores the
// flag bitfield as a left-padded binary string — adding to the tail would
// shift the existing flags and break every saved cookie).
$_flags =
[
// new in v1.3.x — anonymity seed URL encryption (on by default)
'encrypt_url' => 1,
// new in v1.3.0 (privacy / blocking)
'strip_tracking' => 0,
'send_gpc' => 0,
'send_dnt' => 0,
'block_media' => 0,
'block_fonts' => 0,
'block_3p' => 0,
'strip_iframes' => 0,
// original flags (positions preserved)
'include_form' => 1,
'remove_scripts' => 1,
'accept_cookies' => 1,
'show_images' => 1,
'show_referer' => 1,
'rotate13' => 0,
'base64_encode' => 1,
'strip_meta' => 0,
'strip_title' => 1,
'session_cookies' => 1,
];
$_frozen_flags =
[
'encrypt_url' => 0,
'strip_tracking' => 0,
'send_gpc' => 0,
'send_dnt' => 0,
'block_media' => 0,
'block_fonts' => 0,
'block_3p' => 0,
'strip_iframes' => 0,
'include_form' => 0,
'remove_scripts' => 0,
'accept_cookies' => 0,
'show_images' => 0,
'show_referer' => 0,
'rotate13' => 0,
'base64_encode' => 0,
'strip_meta' => 0,
'strip_title' => 0,
'session_cookies' => 0,
];
$_labels =
[
'encrypt_url' => ['Encrypted (rotating key)', 'AES-CTR encrypt URLs with a 1-hour session seed; old logs go unusable'],
'strip_tracking' => ['Strip tracking params', 'Drop utm_*, fbclid, gclid and friends from URLs'],
'send_gpc' => ['Send Sec-GPC: 1', 'Global Privacy Control signal'],
'send_dnt' => ['Send DNT: 1', 'Do-Not-Track header'],
'block_media' => ['Block media', 'Remove <video> and <audio> from proxied pages'],
'block_fonts' => ['Block web fonts', 'Remove font CDN links and @font-face rules'],
'block_3p' => ['Block 3rd-party resources', 'Don\'t proxy assets from a different host than the page'],
'strip_iframes' => ['Strip iframes', 'Remove <iframe> elements from proxied pages'],
'include_form' => ['Show top bar while browsing', 'Pin the URL bar to the top of every proxied page'],
'remove_scripts' => ['Block JavaScript', 'Strip <script> tags from proxied HTML'],
'accept_cookies' => ['Allow cookies', 'Store and forward cookies from proxied sites'],
'show_images' => ['Load images', 'Show images on proxied pages'],
'show_referer' => ['Send Referer header', 'Forward Referer to the target'],
'rotate13' => ['ROT13', 'ROT13 the URL in the address bar'],
'base64_encode' => ['Base64', 'Base64-encode the URL in the address bar'],
'strip_meta' => ['Strip <meta> tags', 'Remove meta tags from proxied pages'],
'strip_title' => ['Hide page title', 'Strip <title> so the browser tab is anonymous'],
'session_cookies' => ['Session-only cookies', 'Forget cookies when the browser closes'],
];
$_hosts =
[
'#^127\.|192\.168\.|10\.|172\.(1[6-9]|2[0-9]|3[01])\.|localhost#i',
];
$_hotlink_domains = [];
$_insert = [];
//
// END CONFIGURABLE OPTIONS. The ride for you ends here. Close the file.
//
$_iflags = '';
$_system =
[
'ssl' => extension_loaded('openssl') && version_compare(PHP_VERSION, '4.3.0', '>='),
'uploads' => ini_get('file_uploads'),
'gzip' => extension_loaded('zlib') && !ini_get('zlib.output_compression'),
'stripslashes' => true,
];
$_proxify =
[
'text/html' => 1,
'application/xml+xhtml' => 1,
'application/xhtml+xml' => 1,
'text/css' => 1,
];
$_version = 'v1.3.3';
$_http_host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : (isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'localhost');
// https://stackoverflow.com/questions/4504831/serverhttp-host-contains-port-number-too
$pos = strpos($_http_host, ':');
if ($pos) {
$_http_host = substr($_http_host, 0, $pos);
}
$_script_url = 'http' . ((isset($_ENV['HTTPS']) && $_ENV['HTTPS'] == 'on') || $_SERVER['SERVER_PORT'] == 443 ? 's' : '') . '://' . $_http_host . ($_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443 ? ':' . $_SERVER['SERVER_PORT'] : '') . $_SERVER['PHP_SELF'];
$_script_base = substr($_script_url, 0, strrpos($_script_url, '/')+1);
$_url = '';
$_url_parts = [];
$_base = [];
$_socket = null;
$_request_method = $_SERVER['REQUEST_METHOD'];
$_request_headers = '';
$_cookie = '';
$_post_body = '';
$_response_headers = [];
$_response_keys = [];
$_http_version = '';
$_response_code = 0;
$_content_type = 'text/html';
$_content_length = false;
$_content_disp = '';
$_set_cookie = [];
$_retry = false;
$_quit = false;
$_basic_auth_header = '';
$_basic_auth_realm = '';
$_auth_creds = [];
$_response_body = '';
$pos = isset($_COOKIE['userAgent']) ? $_COOKIE['userAgent'] : null;
if(!isset($pos) || $pos == ""){ // empty means old method
$_user_agent = isset($_SERVER['HTTP_X_IORG_FBS']) ? 'SamsungI8910/SymbianOS/6.1 PHProxy/'.$_version : $_SERVER['HTTP_USER_AGENT'];
}else if($pos == '.'){ // dot means use the browsers UA
$_user_agent = $_SERVER['HTTP_USER_AGENT'];
}else if($pos == '-'){ // dash means dont set UA
$_user_agent = null;
}else{
$_user_agent = $pos;
}
# to bind to a specific ip set $_bindip to desired IP
# if you do not need to set a specific port use 0 as default
# example:
# $_bindip = '192.168.1.100:0';
# for default ip set value to default
# $_bindip = 'default';
$_bindip = 'default';
// Functions declaration
function show_report(array $data): void
{
phproxy_render_entry_form($data);
exit(0);
}
function add_cookie(string $name, mixed $value, int $expires = 0): string
{
return rawurlencode(rawurlencode($name)) . '=' . rawurlencode(rawurlencode($value)) . (empty($expires) ? '' : '; expires=' . gmdate('D, d-M-Y H:i:s \G\M\T', $expires)) . '; path=/; domain=.' . $GLOBALS['_http_host'];
}
function set_post_vars(array $array, ?string $parent_key = null): array
{
$temp = [];
foreach ($array as $key => $value) {
$key = isset($parent_key) ? sprintf('%s[%s]', $parent_key, urlencode($key)) : urlencode($key);
if (is_array($value)) {
$temp = array_merge($temp, set_post_vars($value, $key));
} else {
$temp[$key] = urlencode($value);
}
}
return $temp;
}
function set_post_files(array $array, ?string $parent_key = null): array
{
$temp = [];
foreach ($array as $key => $value) {
$key = isset($parent_key) ? sprintf('%s[%s]', $parent_key, urlencode($key)) : urlencode($key);
if (is_array($value)) {
$temp = array_merge_recursive($temp, set_post_files($value, $key));
} else if (preg_match('#^([^\[\]]+)\[(name|type|tmp_name)\]#', $key, $m)) {
$temp[str_replace($m[0], $m[1], $key)][$m[2]] = $value;
}
}
return $temp;
}
function url_parse(string $url, array &$container): bool
{
$temp = @parse_url($url);
if (!empty($temp)) {
$temp['port_ext'] = '';
$temp['base'] = $temp['scheme'] . '://' . $temp['host'];
if (isset($temp['port'])) {
$temp['base'] .= $temp['port_ext'] = ':' . $temp['port'];
} else {
$temp['port'] = $temp['scheme'] === 'https' ? 443 : 80;
}
$temp['path'] = isset($temp['path']) ? $temp['path'] : '/';
$path = [];
$temp['path'] = explode('/', $temp['path']);
foreach ($temp['path'] as $dir) {
if ($dir === '..') {
array_pop($path);
} else if ($dir !== '.') {
for ($dir = rawurldecode($dir), $new_dir = '', $i = 0, $count_i = strlen($dir); $i < $count_i; $new_dir .= strspn($dir[$i], 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789$-_.+!*\'(),?:@&;=') ? $dir[$i] : rawurlencode($dir[$i]), ++$i);
$path[] = $new_dir;
}
}
$temp['path'] = str_replace('/%7E', '/~', '/' . ltrim(implode('/', $path), '/'));
$temp['file'] = substr($temp['path'], strrpos($temp['path'], '/') + 1);
$temp['dir'] = substr($temp['path'], 0, strrpos($temp['path'], '/'));
$temp['base'] .= $temp['dir'];
$temp['prev_dir'] = substr_count($temp['path'], '/') > 1 ? substr($temp['base'], 0, strrpos($temp['base'], '/') + 1) : $temp['base'] . '/';
$container = $temp;
return true;
}
return false;
}
/**
* Parse the raw Cookie request header into wire-form (name, value) pairs.
* Unlike $_COOKIE, this preserves the exact wire-form name as the browser
* sent it — no URL decoding, no PHP dot→underscore mangling. We need this
* to be able to expire proxy-stored cookies via setrawcookie() with the
* matching name (PHP's setcookie() would URL-encode again and produce a
* triple-encoded name that doesn't match the browser's stored cookie).
*/
function phproxy_raw_cookies(): array
{
$out = [];
$raw = isset($_SERVER['HTTP_COOKIE']) ? (string) $_SERVER['HTTP_COOKIE'] : '';
if ($raw === '') return $out;
foreach (explode(';', $raw) as $pair) {
$pair = ltrim($pair);
if ($pair === '') continue;
$eq = strpos($pair, '=');
if ($eq === false) {
$out[$pair] = '';
} else {
$out[substr($pair, 0, $eq)] = substr($pair, $eq + 1);
}
}
return $out;
}
/**
* Decode a wire-form cookie name that follows the proxy's
* COOKIE;<name>;<path>;<domain> format. Returns [name, path, domain] or
* null if the wire form doesn't match. Walks back the double URL-encoding
* that add_cookie() applies on the way out.
*/
function phproxy_decode_proxy_cookie_id(string $wire_name): ?array
{
// Double-rawurldecode the wire form to get the human-readable id
$decoded = rawurldecode(rawurldecode($wire_name));
if (strpos($decoded, 'COOKIE;') !== 0) {
return null;
}
$parts = explode(';', $decoded, 4);
if (count($parts) !== 4) {
return null;
}
return [
'name' => $parts[1],
'path' => $parts[2],
'domain' => $parts[3],
];
}
/**
* Decode the value half of a proxy-stored cookie (which has the format
* "<value>;<secure_flag>" where secure_flag is "secure" or empty).
* Walks back the double-rawurlencode applied on the way out.
*/
function phproxy_decode_proxy_cookie_value(string $wire_value): array
{
$decoded = rawurldecode(rawurldecode($wire_value));
$semi = strrpos($decoded, ';');
if ($semi === false) {
return ['value' => $decoded, 'secure' => false];
}
return [
'value' => substr($decoded, 0, $semi),
'secure' => strtolower(trim(substr($decoded, $semi + 1))) === 'secure',
];
}
/**
* Shared User-Agent preset list used by both the entry form's Headers tab
* and the inline panel injected onto proxied pages.
*/
function phproxy_ua_presets(): array
{
return [
'' => '— Default browser User-Agent —',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36' => 'Chrome on Windows',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15' => 'Safari on macOS',
'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1' => 'Safari on iPhone',
'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Mobile Safari/537.36' => 'Chrome on Android',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36' => 'Chrome on Linux',
'Mozilla/5.0 (X11; CrOS x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36' => 'Chrome on ChromeOS',
'curl/8.5.0' => 'curl 8.5',
'Wget/1.21.4' => 'wget 1.21',
'.' => '★ Use my real browser User-Agent',
'-' => '★ Send no User-Agent at all',
];
}
/**
* Parse $_SERVER['HTTP_COOKIE'] and bucket the non-settings entries into
* the structure the panel template expects. Used by both the entry form
* and the inline panel injection.
*/
function phproxy_panel_buckets(): array
{
$settings = ['flags', 'userAgent', 'PHPSESSID', 'phproxy-theme', 'phproxy-seed', 'phproxy-seed-ttl', 'phproxy-seed-bits', 'phproxy-show-raw', 'phproxy-panel-tab'];
$visible = [];
$headers = [];
foreach (phproxy_raw_cookies() as $wire => $val) {
if (in_array($wire, $settings, true)) continue;
if (strpos($wire, 'hdr_') === 0) {
$headers[substr($wire, 4)] = rawurldecode($val);
continue;
}
$parsed = phproxy_decode_proxy_cookie_id($wire);
if ($parsed !== null) {
$v = phproxy_decode_proxy_cookie_value($val);
$visible[$wire] = [
'display_name' => $parsed['name'],
'host' => ltrim($parsed['domain'], '.'),
'domain' => $parsed['domain'],
'path' => $parsed['path'],
'value' => $v['value'],
'raw_value' => $val,
'raw_name' => $wire,
'secure' => $v['secure'],
'is_proxy' => true,
];
} else {
$visible[$wire] = [
'display_name' => rawurldecode($wire),
'host' => '',
'domain' => '',
'path' => '',