-
Notifications
You must be signed in to change notification settings - Fork 93
/
Copy pathwatchbird-source.php
1985 lines (1902 loc) · 71.8 KB
/
watchbird-source.php
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
/*
A Simple PHP WAF for AWD
/$$ /$$ /$$$$$$ /$$$$$$$$ /$$$$$$ /$$ /$$ /$$$$$$$ /$$$$$$ /$$$$$$$ /$$$$$$$
| $$ /$ | $$ /$$__ $$|__ $$__//$$__ $$| $$ | $$| $$__ $$|_ $$_/| $$__ $$| $$__ $$
| $$ /$$$| $$| $$ \ $$ | $$ | $$ \__/| $$ | $$| $$ \ $$ | $$ | $$ \ $$| $$ \ $$
| $$/$$ $$ $$| $$$$$$$$ | $$ | $$ | $$$$$$$$| $$$$$$$ | $$ | $$$$$$$/| $$ | $$
| $$$$_ $$$$| $$__ $$ | $$ | $$ | $$__ $$| $$__ $$ | $$ | $$__ $$| $$ | $$
| $$$/ \ $$$| $$ | $$ | $$ | $$ $$| $$ | $$| $$ \ $$ | $$ | $$ \ $$| $$ | $$
| $$/ \ $$| $$ | $$ | $$ | $$$$$$/| $$ | $$| $$$$$$$/ /$$$$$$| $$ | $$| $$$$$$$/
|__/ \__/|__/ |__/ |__/ \______/ |__/ |__/|_______/ |______/|__/ |__/|_______/
Credits:
[AWD_PHP watchbird] (Original WAF Framework)
[Longlone](https://github.com/WAY29) (Main developer)
[Leohearts](https://leohearts.com) (Main developer)
[guoqing](https://blog.izgq.net/archives/1029/) (Function: getFormData(), Regenerating RAW multipart/form-data post data), 已联系授权
Lisence:
GNU AGPLv3 (GNU Affero General Public License v3.0)
https://choosealicense.com/licenses/agpl-3.0/
Permissions Conditions Limitations
Commercial use Disclose source Liability
Distribution License and copyright notice Warranty
Modification Network use is distribution
Patent use Same license
Private use State changes
Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) (For Function: getFormData() Only)
https://creativecommons.org/licenses/by-nc-sa/4.0/
You are free to:
Share — copy and redistribute the material in any medium or format
Adapt — remix, transform, and build upon the material
Under the following terms:
Attribution — You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use.
NonCommercial — You may not use the material for commercial purposes.
ShareAlike — If you remix, transform, or build upon the material, you must distribute your contributions under the same license as the original.
No additional restrictions — You may not apply legal terms or technological measures that legally restrict others from doing anything the license permits.
*/
$config_path = '/tmp/watchbird/watchbird.conf';
$check_upload_path = "/tmp/wb_check_upload";
// $level = 4; // 0~4 等级越高,防护能力越强,默认为4
error_reporting(0);
ob_end_clean();
function is_browser($v,$vv){
return strstr($v, $vv);
}
function get_fake_flag(){
global $config;
$flag = trim(file_get_contents($config->flag_path));
$str="QWERTYUIOPASDFGHJKLZXCVBNM1234567890qwertyuiopasdfghjklzxcvbnm";
str_shuffle($str);
$fake_flag='flag{'.substr(str_shuffle($str),0,strlen($flag)-6).'}';
return $fake_flag;
}
function get_preg_flag(){ // 获取自己flag的正则表达式并保存在文件里
global $config;
$result = '';
$flag = file_get_contents($config->flag_path);
$flag = trim($flag);
if ($flag === ""){
return 'flag{sauhiudsahiudhasiuhduihwauidhwsuisdhaiuhduiahuiduishudiahusdhauwshdushuidaud|';
}
if(strlen($flag) >= 18)
{
$flag1 = substr($flag, 0, strlen($flag)/3);
$flag1 = preg_quote($flag1, '/');
$result .= $flag1.'*|';
$flag2 = substr($flag, strlen($flag)/3, strlen($flag)*2/3);
$flag2 = preg_quote($flag2, '/');
$result .= $flag2.'*|';
$flag3 = substr($flag, strlen($flag)*2/3);
$flag3 = preg_quote($flag3, '/');
$result .= $flag3.'*|';
}else{
$result = 'flag{|'.preg_quote($flag).'|';
}
// echo $result;
return $result;
}
class configmanager
{
// 功能开启选项
public $flag_path = '/flag'; // 自己flag所在的路径
public $LDPRELOAD_PATH = '/var/www/html/waf.so'; //共享库路径
public $password_sha1 = 'unset';
public $open_basedir = '/';
// public $level = 4; // 0~4 等级越高,防护能力越强,默认为4
// level处理
public $waf_headers = 1; // headers防御
public $waf_ddos = 1; // ddos防御
public $waf_upload = 1; // 上传防御
public $waf_special_char = 0; // 特殊字符防御
public $waf_sql = 1; // sql防御
public $waf_rce = 1; // rce防御
public $waf_ldpreload = 1; //基于LD_PRELOAD的rce防护
public $waf_lfi = 1; // LFI/LFR 防御
public $waf_unserialize = 1; // phar反序列化防御
public $waf_flag = 1; // getflag防御
public $response_content_match = 1; // 匹配响应中有无flag特征
public $debug = 0; // debug模式
public $scheduled_killall = 0;
public $scheduled_killall_killweb = 1;
public $allow_ddos_time = 5; // 每秒最多5个访问
public $waf_fake_flag = "flag{Longlone:W0r1<_HaRd3r}"; // 虚假flag,需开启waf_flag
public $remote_ip = "127.0.0.1"; // 服务器ip
public $remote_port = 80; // 服务器端口
public $max_log_size = 40000; //单个日志文件最大大小
//名单配置
public $upload_whitelist = "/jpg|png|gif|txt/i"; // upload白名单
public $sql_blacklist = "/drop |dumpfile\b|INTO FILE|union select|outfile\b|load_file\b|multipoint\(/i";
public $rce_blacklist = "/`|var_dump|str_rot13|serialize|base64_encode|base64_decode|strrev|eval\(|assert|file_put_contents|fwrite|curl_exec\(|dl\(|readlink|popepassthru|preg_replace|preg_filter|mb_ereg_replace|register_shutdown_function|register_tick_function|create_function|array_map|array_reduce|uasort|uksort|array_udiff|array_walk|call_user_func|array_filter|usort|stream_socket_server|pcntl_exec|passthru|exec\(|system\(|chroot\(|scandir\(|chgrp\(|chown|shell_exec|proc_open|proc_get_status|popen\(|ini_alter|ini_restore|ini_set|LD_PRELOAD|ini_alter|ini_restore|ini_set|base64 -d/i";
function change($key, $val)
{
if ($key == "config_path" || $key == 'check_upload_path') {
die("dont try to rce :3");
}
global $config_path;
$this->$key = $val;
echo $key;
echo $val . "\n";
if (is_numeric($val)) {
$this->$key = intval($val);
}
file_put_contents($config_path, serialize($this));
die('succ');
}
}
class watchbird{
private $request_url;
private $request_method;
private $request_data;
private $headers;
private $raw;
private $dir;
private $logdir;
private $uploaddir;
private $tokendir;
private $allow_time;
private $response_content;
private $timestamp;
/*
watchbird类
*/
// 自动部署构造方法
function __construct(){
//echo $_SERVER['SERVER_PORT']."\n";
global $config, $content_disallow, $waf_fake_flag2;
$this->dir = '/tmp/watchbird/';
$this->logdir = $this->dir.'log/';
$this->uploaddir = $this->dir.'upload/';
$this->ipdir = $this->dir.'ip/';
$this->tokendir = $this->dir . 'token/';
if ($config->waf_ldpreload == 1) {
putenv("LD_PRELOAD=" . $config->LDPRELOAD_PATH);
}
$this->headers = getallheaders(); //获取header
foreach ($this->headers as $key => $val){
if ($val == ""){
unset($this->headers[$key]);
}
}
$this->timestamp = getMillisecond();
if ($config->open_basedir !== '/') {
ini_set("open_basedir", $config->open_basedir . ':/tmp/');
}
if(isset($_SERVER['HTTP_WATCHBIRDTOKEN']) && file_exists($this->tokendir . $_SERVER['HTTP_WATCHBIRDTOKEN'])){
unlink($this->tokendir . $_SERVER['HTTP_WATCHBIRDTOKEN']);
putenv("php_timestamp=".$_SERVER['HTTP_WATCHBIRDTIMESTAMP']);
return 0;
}
else{
putenv("php_timestamp=" . $this->timestamp); // 用于ld_preload rce防护记录日志
}
$this->allow_time = $config->allow_ddos_time; // 获取每秒最大访问次数
if ($config->waf_ddos == true){
$this->watch_ddos();
}
$this->e_mkdir($this->dir);
$this->e_mkdir($this->logdir);
$this->e_mkdir($this->uploaddir);
$this->e_mkdir($this->ipdir);
$this->e_mkdir($this->tokendir);
$this->request_url = $this->filter_0x25(urldecode($_SERVER['REQUEST_URI'])); // 获取url来进行检测
$this->request_data = file_get_contents('php://input'); // 获取post
if ($config->waf_headers == true)
{
$this->watch_headers(); // 监测headers
}
$this->write_access_log_probably(); // 记录访问纪录, 类似于日志
$this->write_access_logs_detailed(); // 记录详细访问请求包
if ($config->waf_upload==true) {
$this->watch_upload(); // 记录上传纪录
}
if($_SERVER['REQUEST_METHOD'] != 'POST' && $_SERVER['REQUEST_METHOD'] != 'GET'){
$method = $_SERVER['REQUEST_METHOD'];
$this->write_attack_log("Catch attack: Suspicious method [ ".$method."] ");
}
foreach ($_GET as $keywords){ // 监测GET参数,出现问题则记录
$this->watch_attack_keyword($this->watch_special_char($keywords));
}
if ($this->request_data != '')
{
foreach ($_POST as $keywords){ // 监测POST参数,出现问题则记录
$this->watch_attack_keyword($this->watch_special_char($keywords));
}
}
if ($config->response_content_match){ // 深度检测响应包
ob_end_clean(); // 处理BOM头
$this->getcont(); // 开始自检
if (preg_match($content_disallow, $this->response_content)!==0){
$this->write_flag_log();
die($waf_fake_flag2);
}
else {
$co=explode("\r\n\r\n",$this->response_content,2)[1];
$raw_header=explode("\r\n\r\n",$this->response_content,2)[0];
$res_header = explode("\r\n",explode("\r\n",$raw_header,2)[1]);
foreach ($res_header as $leo1){
if (stripos($leo1, 'transfer-encoding') !== false) {continue;}
header($leo1,true);
}
// header("Content-Encoding: identity", true);
// while (preg_match("/^[0-9,a-z]{5}/", $co)) {
// $co = substr($co, 5);
// }
// while (preg_match("/^[0-9,a-z]{4}/",$co)){
// $co=substr($co,4);
// }
// $co=substr($co,strpos($co,pack("CCC",0xef,0xbb,0xbf))); // 处理BOM头
// if (substr($co,0,3) == pack("CCC",0xef,0xbb,0xbf)){
// $co=substr($co,3);
// }
if (substr($co,-7)=="\r\n0\r\n\r\n" && preg_match("/^[0-9, a-f]/", $co)){
// $co=rtrim($co,"\r\n0\r\n\r\n");
// $co .= "\r\n\r\n";
// header("Transfer-Encoding: chunked", true); // finally!
$co = decode_chunked($co);
}
die($co); // 将内容返回给用户
}
}
}
/*
判断文件夹是否存在并创建文件夹
*/
function e_mkdir($folder){
if (is_dir($folder) == false)
{
mkdir($folder, 0777, true);
return true;
}
return false;
}
/*
删除文件夹下所有文件
*/
function deldir($dir) {
$dh=opendir($dir);
while ($file=readdir($dh)) {
if($file!="." && $file!="..") {
$fullpath=$dir."/".$file;
if(!is_dir($fullpath)) {
unlink($fullpath);
}
else {
$this->deldir($fullpath);
}
}
}
}
/*
die并且输出logo
*/
function logo(){
global $config;
$logo = <<<LOGO
__ ___ _____ ____ _ _ ____ ___ ____ ____
\ \ / / \|_ _/ ___| | | | __ )_ _| _ \| _ \
\ \ /\ / / _ \ | || | | |_| | _ \| || |_) | | | |
\ V V / ___ \| || |___| _ | |_) | || _ <| |_| |
\_/\_/_/ \_\_| \____|_| |_|____/___|_| \_\____/
LOGO;
$UAs=array("MSIE", "Firefox", "Chrome", "Safari", "Opera");
$UA=$_SERVER["HTTP_USER_AGENT"];
if (count(array_filter(array_map("is_browser", array_fill(0, count($UAs), $UA), $UAs)))){
$logo="<pre>\n".$logo."\n</pre>";
$logo=str_replace("\r","", $logo);
$logo=str_replace("\n","</br>", $logo);
}
echo $logo;
if ($config->debug){
echo debug_backtrace()[1]['function'];
}
die();
}
/*
DDOS防御
*/
function watch_ddos(){
$IP = $_SERVER['REMOTE_ADDR'];
$IP = str_replace(":", '_', $IP);
$date = date('H_i_s');
$IP_dir = $this->ipdir . '/' . $IP . '/';
$this->e_mkdir($IP_dir);
$IP_date_file = $IP_dir . $date . '_log.txt';
if (is_file($IP_date_file))
{
$time = intval(file_get_contents($IP_date_file));
$time += 1;
if ($time > $this->allow_time)
{
$this->logo();
}
else{
file_put_contents($IP_date_file, $time, LOCK_EX);
}
}
else{
$this->deldir($IP_dir);
file_put_contents($IP_date_file, 1, LOCK_EX);
}
}
/*
监测headers
*/
function watch_headers(){
global $config;
foreach($this->headers as $k=>$v) {
if (preg_match($config->sql_blacklist, urldecode($v)) || preg_match($config->rce_blacklist, urldecode($v))) {
$this->headers[$k] = '';
// $URI = explode('?',$this->request_url);
// header('Location: http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER["SERVER_PORT"].$URI[0]);
$this->logo();
}
}
}
/*
监测不可见字符造成的截断和绕过效果,注意网站请求带中文需要简单修改
*/
function watch_special_char($str){
global $config;
$txt = '';
for($i=0;$i<strlen($str);$i++){
$ascii = ord($str[$i]);
if($ascii>126 || $ascii < 32){ // 有中文这里要修改
if(!in_array($ascii, array(9,10,13))){
$txt .= "Interrupt";
}else{
$txt .= " Catch attack: Suspected attack character < ".$str[$i]. " > ";
}
break;
}
if (preg_match("/\||\`|\;|\,|\'|\"|<|>/", $str[$i]))
{
$txt .= " Catch attack: Suspected attack character < ".$str[$i]." > ";
break;
}
}
if ($txt != '')
{
if($config->waf_special_char == true){
$this->write_attack_log($txt);
$this->logo();
}
}
return $str;
}
/*
监测文件上传
*/
function watch_upload(){
global $config, $check_upload_path;
foreach ($_FILES as $key => $value) {
if($_FILES[$key]['error'] == 0){
$ext = substr(strrchr($_FILES[$key]["name"], '.'), 1);
$this->write_attack_log("Catch attack: < Evil Upload, please check ".$this->uploaddir." dir > ");
copy($_FILES[$key]["tmp_name"], $this->uploaddir.date("d_H_i_s").'.'.$ext.'.txt');
file_put_contents($check_upload_path,"check!");
if(!preg_match($config->upload_whitelist, $ext))
{
unlink($_FILES[$key]['tmp_name']);
echo 'Upload success! Check upload/'.substr(md5($_FILES[$key]["name"]), 0, rand(10, 30)).'.'.$ext;
die();
}
}
$new_file_content = file_get_contents($_FILES[$key]['tmp_name']);
if (preg_match("/<?php/i", $new_file_content) === 1){
$this->write_attack_log("Catch attack: < Evil Upload, please check " . $this->uploaddir . " dir > ");
copy($_FILES[$key]["tmp_name"], $this->uploaddir . date("d_H_i_s") . '.' . $ext . '.txt');
unlink($_FILES[$key]['tmp_name']);
echo 'Upload success. Check upload/' . substr(md5($_FILES[$key]["name"]), 0, rand(10, 30)) . '.' . $ext;
die();
}
}
}
/*
监测网站程序存在二次编码绕过漏洞造成的%25绕过,此处是循环将%25替换成%,直至不存在%25
*/
function filter_0x25($str){
if(strpos($str,"%25") !== false){
$str = str_replace("%25", "%", $str);
return $this->filter_0x25($str);
}else{
return $str;
}
}
/*
对非法请求进行重定向
*/
// function redirect(){
// $URI = explode('?',$this->request_url);
// header('Location: http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER["SERVER_PORT"].$URI[0]);
// die();
// }
/*
监测攻击关键字
*/
function watch_attack_keyword($str){
global $config;
if(preg_match($config->sql_blacklist, $str)){
if($config->waf_sql == true){
$this->write_attack_log("Catch attack: < SQLI > ");
$this->logo();
}
}
if(substr_count($str,$_SERVER['PHP_SELF']) < 2){
$tmp = str_replace($_SERVER['PHP_SELF'], "", $str);
if(preg_match("/\.\.|.*\.php[2357]{0,1}|\.phtml/i", $tmp)){
if($config->waf_lfi == true){
$this->write_attack_log("Catch attack: < LFI/LFR > ");
$this->logo();
}
}
}else{
if($config->waf_lfi == true){
$this->write_attack_log("Catch attack: < LFI/LFR > ");
$this->logo();
}
}
if(preg_match($config->rce_blacklist, $str)){
if($config->waf_rce == true){
$this->write_attack_log("Catch attack: < RCE > ");
$this->logo();
}
}
if(preg_match("/phar|zip|compress.bzip2|compress.zlib/i", $str)){
if($config->waf_unserialize == true){
$this->write_attack_log("Catch attack: < phar unserialize >");
$this->logo();
}
}
if(preg_match("/flag/i", $str)){
if($config->waf_flag == true){
$this->write_attack_log("Catch attack: < !!GETFLAG!! >");
die($config->waf_fake_flag);
}
}
}
// 记录每次大概访问记录,类似日志,以便在详细记录中查找
function write_access_log_probably() {
global $config;
$tmp = sha1("Syclover").$this->timestamp.sha1("Syclover");
$tmp .= "[" . date('H:i:s') . "]" . $_SERVER['REQUEST_METHOD'].' '.$_SERVER['REQUEST_URI'].' '.$_SERVER['SERVER_PROTOCOL'];
if (!empty($this->request_data)){
$tmp .= "\n".$this->request_data;
}
$tmp .= "\n";
file_put_contents($this->logdir.'all_requests'.'.txt', $tmp, FILE_APPEND | LOCK_EX);
if (filesize($this->logdir . 'all_requests' . '.txt') > $config->max_log_size) {
unlink($this->logdir . 'all_requests' . '.txt');
}
}
// 记录详细的访问头记录,包括GET POST http头, 以获取waf未检测到的攻击payload
function write_access_logs_detailed(){
global $config;
$tmp = sha1("Syclover"). $this->timestamp. sha1("Syclover");
$tmp .= "[" . date('H:i:s') . "]\n";
$tmp .= "SRC IP: " . $_SERVER["REMOTE_ADDR"]."\n";
$tmp .= $_SERVER['REQUEST_METHOD'].' '.$_SERVER['REQUEST_URI'].' '.$_SERVER['SERVER_PROTOCOL']."\n";
foreach($this->headers as $k => $v) {
if ($k==="isself"){
continue;
}
$tmp .= $k . ': ' . $v . "\n";
}
if (!empty($this->request_data)) {
$tmp .= "\n". $this->request_data . "\n";
}
$tmp .= "\n";
file_put_contents($this->logdir.'web_log'.'.txt', $tmp, FILE_APPEND | LOCK_EX);
if (filesize($this->logdir . 'web_log' . '.txt') > $config->max_log_size) {
unlink($this->logdir . 'web_log' . '.txt');
}
}
/*
记录攻击payload 第一个参数为记录类型 使用时直接调用函数
*/
function write_attack_log($alert){
global $config;
$tmp = sha1("Syclover").$this->timestamp. sha1("Syclover");
$tmp .= "[" . date('H:i:s') . "] {".$alert."}\n";
$tmp .= "SRC IP: " . $_SERVER["REMOTE_ADDR"]."\n";
$tmp .= $_SERVER['REQUEST_METHOD'].' '.$_SERVER['REQUEST_URI'].' '.$_SERVER['SERVER_PROTOCOL']."\n";
foreach($this->headers as $k => $v) {
if ($k==="isself"){
continue;
}
$tmp .= $k . ': ' . $v . "\n";
}
if (!empty($this->request_data)) {
$tmp .= "\n". $this->request_data . "\n";
}
file_put_contents($this->logdir.'under_attack_log.txt', $tmp, FILE_APPEND | LOCK_EX);
if (filesize($this->logdir . 'under_attack_log' . '.txt') > $config->max_log_size) {
unlink($this->logdir . 'under_attack_log' . '.txt');
}
if ($alert == 'Catch attack: < !!GETFLAG!! >') // 顺便写入另外一个日志
{
file_put_contents($this->logdir.'flag_eye_to_eye.txt', $tmp, FILE_APPEND | LOCK_EX);
if (filesize($this->logdir . 'flag_eye_to_eye' . '.txt') > $config->max_log_size) {
unlink($this->logdir . 'flag_eye_to_eye' . '.txt');
}
}
}
/*
将流量发送到本地服务器进行自检
*/
function getcont(){
global $config;
$headerstr = "";
$this->response_content = "";
$this->headers['watchbirdtimestamp'] = $this->timestamp;
$this->headers['Connection'] = "Close";
$this->headers["Accept-Encoding"] = "identity";
$token = rand();
$this->headers['WatchbirdToken'] = $token;
touch ($this->tokendir . $token);
foreach($this->headers as $k => $v) {
$headerstr .= $k . ': ' . $v . "\r\n";
}
$fp = fsockopen($config->remote_ip, $config->remote_port, $errno, $errstr, 30);
if (!$fp) {
echo "500 Internal Server Error.";
}
else {
$out = $_SERVER['REQUEST_METHOD'].' '.$_SERVER['REQUEST_URI'].' '.$_SERVER['SERVER_PROTOCOL']."\r\n";
$out .= $headerstr;
$out .= "\r\n";
$out .= $this->request_data . "\r\n";
if ($this->request_data===''&&$_SERVER['REQUEST_METHOD']=="POST"){
$out .= getFormData();
}
stream_set_timeout($fp, 5);
fwrite($fp, $out);
//echo $out;
while (!feof($fp)) {
$tmp3 = fgets($fp, 4);
if ($tmp3 === false){
break;
}
$this->response_content .= $tmp3;
}
fclose($fp);
if ($config->debug){
echo $out;
echo $this->response_content;
}
}
}
/*
当响应包中存在flag时写入日志
*/
function write_flag_log(){
global $config;
$tmp = sha1("Syclover").$this->timestamp.sha1("Syclover");
$tmp .= "[" . date('H:i:s') . "] \n";
$tmp .= "\nRequest:\n";
$tmp .= "SRC IP: " . $_SERVER["REMOTE_ADDR"]."\n";
$tmp .= $_SERVER['REQUEST_METHOD'].' '.$_SERVER['REQUEST_URI'].' '.$_SERVER['SERVER_PROTOCOL']."\n";
foreach($this->headers as $k => $v) {
// if ($k==="isself"){
// continue;
// }
$tmp .= $k . ': ' . $v . "\n";
}
if (!empty($this->request_data)) {
$tmp .= "\n". $this->request_data . "\n";
}
$tmp .= "\nResponse\n";
$tmp .= $this->response_content;
file_put_contents($this->logdir.'flag_log.txt', $tmp, FILE_APPEND | LOCK_EX);
if (filesize($this->logdir . 'flag_log' . '.txt') > $config->max_log_size) {
unlink($this->logdir . 'flag_log' . '.txt');
}
}
}
function getMillisecond(){
list($s1,$s2)=explode(' ',microtime());
return (float)sprintf('%.0f',(floatval($s1)+floatval($s2))*1000);
}
// 还原 rfc1867, rfc2046 格式的FormData, 来自https://blog.izgq.net/archives/1029/
function getFormData(){
// body-part array
$body = array();
// 普通参数
foreach ($_POST as $key => $value) {
if (!is_array($value)) {
$body_part = "Content-Disposition: form-data; name=\"$key\"\r\n";
$body_part .= "\r\n$value";
$body[] = $body_part;
} else {
// 数组的情况处理 如 param1[]=xxxx
$result = array();
convert_array_key($value, $key, $result);
foreach ($result as $k => $v) {
$body_part = "Content-Disposition: form-data; name=\"$k\"\r\n";
$body_part .= "\r\n$v";
$body[] = $body_part;
}
}
}
// 上传文件处理
foreach ($_FILES as $key => $value) {
if (!is_array($value['type'])) {
$body_part = "Content-Disposition: form-data; name=\"$key\"; filename=\"{$value['name']}\"\r\n";
$body_part .= "Content-type: {$value['type']}\r\n";
$body_part .= "\r\n" . file_get_contents($value['tmp_name']);
$body[] = $body_part;
} else {
// 文件key是数组的情况 如 file1[]=xxxx
$result = array();
convert_array_key($value['type'], "", $result);
foreach ($result as $k => $v) {
$filename = query_multidimensional_array($value['name'], $k);
$type = query_multidimensional_array($value['type'], $k);
$tmp_name = query_multidimensional_array($value['tmp_name'], $k);
$body_part = "Content-Disposition: form-data; name=\"{$key}{$k}\"; filename=\"{$filename}\"\r\n";
$body_part .= "Content-type: {$type}\r\n";
$body_part .= "\r\n" . file_get_contents($tmp_name);
$body[] = $body_part;
}
}
}
// 提取boundary
$boundary = substr($_SERVER['CONTENT_TYPE'], strpos($_SERVER['CONTENT_TYPE'], "=") + 1);
// multipart-body
$multipart_body = "--$boundary\r\n";
// 拼接各个域
$multipart_body .= implode("\r\n--$boundary\r\n", $body);
// 最后一个不同的 boundary
$multipart_body .= "\r\n--$boundary--";
return $multipart_body;
}
// 直接访问多维数组元素
// query: [0][0] -> $array[0][0]
function query_multidimensional_array(&$array, $query){
$query = explode('][', substr($query, 1, -1));
$temp = $array;
foreach ($query as $key) {
$temp = $temp[$key];
}
return $temp;
}
// DFS将数组变为一维形式
function convert_array_key(&$node, $prefix, &$result){
if (!is_array($node)) {
$result[$prefix] = $node;
} else {
foreach ($node as $key => $value) {
convert_array_key($value, "{$prefix}[{$key}]", $result);
}
}
}
if (!function_exists('getallheaders'))
{
function getallheaders()
{
$headers = [];
foreach ($_SERVER as $name => $value)
{
if (substr($name, 0, 5) == 'HTTP_'&&$value!='')
{
$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
}
}
return $headers;
}
}
function decode_chunked($str) // https://stackoverflow.com/a/10859409
{
for ($res = ''; !empty($str); $str = trim($str)) {
$pos = strpos($str, "\r\n");
$len = hexdec(substr($str, 0, $pos));
$res .= substr($str, $pos + 2, $len);
$str = substr($str, $pos + 2 + $len);
}
return $res;
}
class ui
{
public $passwdhash;
public $mdui_css = <<<CSS_RESOURCE
{{@res-file:mdui.min.css}}
CSS_RESOURCE;
public $mdui_js = <<<JS_RESOURCE
{{@res-file:mdui.min.js}}
JS_RESOURCE;
public $mdui_logo = <<<SVG_RESOURCE
{{@res-file:logo.svg}}
SVG_RESOURCE;
public $mdui_font = '';
function __construct()
{
$this->mdui_font = base64_decode('{{@res-file:mdui-icon.woff2.base64}}');
}
function show()
{
global $config;
// die(var_dump(get_object_vars($config)));
if ($this->passwdhash === 'unset'){
if (isset($_GET['passwd'])){
if (trim($_GET['passwd'] === "")){
die('密码不能为空');
}
$config->change('password_sha1', sha1($_GET['passwd']));
die('密码初始化成功');
}
}
if (sha1($_GET['passwd']) == $this->passwdhash) {
$_SESSION['login'] = 'success';
echo "login success.";
}
if ($_SESSION['login'] !== 'success') {
$this->login();
}
print(<<<HTML_CODE
<html>
<head>
<meta charset="UTF-8">
<title>Watchbird控制台</title>
<link rel="shortcut icon" href="?watchbird=resource&resource=logo">
<link rel="stylesheet" href="?watchbird=resource&resource=css">
<script src="?watchbird=resource&resource=js"></script>
<style>
*{font-family: Arial, Helvetica, sans-serif;}
textarea{font-family: monospace !important;}
.logger {
padding: 20px 0px;
display: grid;
gap: 30px;
height: 100%;
grid-template-rows: repeat(4,1fr);
}
@media (min-width: 800px){
.logger {
grid-template-columns: repeat(2,1fr);
grid-template-rows: repeat(2,1fr);
}
}
.logcontainer .mdui-card{
margin-top: 10px;
transition: 0.6s;
opacity: 0;
}
.logcontainer .mdui-card.active{
opacity: 1;
}
.logger div.mdui-col{
overflow: auto;
}
.dest-selector-multi{
min-width: 42px;
}
pre{
font-family: Arial, Helvetica, sans-serif;
font-weight: 300;
white-space: pre-wrap;
word-break: break-all;
padding-left: 10px;
padding-right: 10px;
}
*{
scrollbar-width: thin;
scrollbar-color: #cdcdcd rgba(0,0,0,0)
}
</style>
<script>
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function switchdrawer() {
var inst = new mdui.Drawer(document.getElementsByClassName("mdui-drawer")[0]);
inst.toggle();
}
function getLocalConfig(ConfigItem){
var ret = localStorage.getItem(ConfigItem);
return ret;
}
function setLocalConfig(ConfigItem, value) {
return localStorage.setItem(ConfigItem, value);
}
function changetheme() {
var body = document.querySelector("body");
var res = body.classList.replace("mdui-theme-layout-dark", "mdui-theme-primary-teal");
if (!res){
body.classList.replace("mdui-theme-primary-teal", "mdui-theme-layout-dark");
body.classList.remove("mdui-theme-accent-pink");
setLocalConfig("theme", "dark");
}
else{
body.classList.add("mdui-theme-accent-pink");
setLocalConfig("theme", "light");
}
}
async function checkLocalReplayerAvailablility(){
await fetch(document.getElementById("replayer_addr").value + "?watchbird=checkExistence")
.then(function(Response) {
return Response.text()
})
.then(function(txt) {
if (txt == "I'm still alive"){
document.getElementById("use_custom_replayer").checked = true;
}
})
}
document.addEventListener("DOMContentLoaded",function () {
if (getLocalConfig("theme") == "dark"){
changetheme();
}
if (getLocalConfig("submit_packet_body") != null){
document.getElementById("submit_packet_body").value = getLocalConfig("submit_packet_body");
}
if (getLocalConfig("submit_packet_header") != null){
document.getElementById("submit_packet_header").value = getLocalConfig("submit_packet_header");
}
if (getLocalConfig("flag_regex") != null){
document.getElementById("flag_regex").value = getLocalConfig("flag_regex");
}
if (getLocalConfig("replayer_addr") != null){
document.getElementById("replayer_addr").value = getLocalConfig("replayer_addr");
}
startDaemon();
startKillallTimer();
Notification.requestPermission().then(function (permission) {
if (permission === 'granted') {
console.log('用户允许通知');
} else if (permission === 'denied') {
console.log('用户拒绝通知');
}
});
checkLocalReplayerAvailablility();
});
async function tryKillallProcess(){
if (document.getElementById("config_scheduled_killall").checked){
let query_killall = "?watchbird=scheduled_killall";
if (document.getElementById("config_scheduled_killall_killweb").checked){
query_killall += '&watchbird_kill_all_process=1';
}
await fetch(query_killall);
}
}
async function startKillallTimer(){
document.getElementById("config_scheduled_killall").nextElementSibling.nextSibling.textContent = "每分钟关闭所有www用户进程并清理Crontab";
document.getElementById("config_scheduled_killall_killweb").nextElementSibling.nextSibling.textContent = "含apache/nginx进程";
document.getElementById("config_scheduled_killall").nextElementSibling.style.marginRight = "12px";
document.getElementById("config_scheduled_killall_killweb").nextElementSibling.style.marginRight = "12px";
while(1){
tryKillallProcess();
await sleep(60000);
}
}
async function startDaemon(){
while(1){
try{
await checklog();
}
catch{
await sleep(1000);
continue;
}
await sleep(1000);
}
}
function parseRequest(text){
text = text.substring(text.search("SRC IP"));
text = text.substring(text.search("\\n")).trim();
if (text.search("\\n\\nResponse") != -1){
text = text.substring(0, text.search("\\n\\nResponse")); //Dont forget that you're in PHP!
}
return text;
}
function addlistitem(str){
var newtextfield = document.createElement("div");
newtextfield.classList.add("mdui-textfield");
var textInput = document.createElement("textarea");
textInput.classList.add("mdui-textfield-input");
textInput.value = str;
textInput.spellcheck = false;
newtextfield.append(textInput);
document.getElementsByClassName("repeater")[0].getElementsByClassName("header-field")[0].append(newtextfield);
}
function handle_replay(){
var text = event.target.parentElement.previousElementSibling.innerText;
document.getElementsByClassName("repeater")[0].getElementsByClassName("header-field")[0].innerHTML = "";
text = parseRequest(text);
try{
document.getElementById("myhost").value = text.match(new RegExp("host: {0,}[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}", 'i'))[0].match(new RegExp("[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}"))[0];
}
catch{}
var postdata = "undefined";
var text_search_nn = text.search("\\n\\n");
if (text_search_nn != -1){
postdata = text.substring(text_search_nn+2);
text = text.substring(0, text_search_nn);
}
var queryList = text.split("\\n");
for (var i = 0;i < queryList.length;i++){
addlistitem(queryList[i]);
}
if (postdata != "undefined"){
addlistitem(postdata);
var newlabel = document.createElement("label");
newlabel.classList.add("mdui-textfield-label");
newlabel.innerText = "POST data";
document.getElementsByClassName("repeater")[0].getElementsByClassName("header-field")[0].lastElementChild.prepend(newlabel);
}
var inst = new mdui.Dialog(document.getElementsByClassName("repeater")[0]);
inst.open();
mdui.mutation();
}
async function submitFlag(flag){
var submit_packet_header = document.getElementById("submit_packet_header").value;
var submit_packet_body = document.getElementById("submit_packet_body").value;
submit_packet_body = submit_packet_body.replace("{flag_content}", flag);
var headerList = submit_packet_header.split("\\n");
var finalPacket = "";
var isPost = (submit_packet_body.trim().length != 0);
var ipAddr = "";