## 思路1:
1、改服务器密码
(1)linux:passwd
(2)如果是root删除可登录用户:cat /etc/passwd | grep bash userdel -r 用户名
(3)mysql:update mysql.user set password=md5(‘密码’) where user=‘root’;
进入mysql:5.7之后的版本
update user set authentication_string=password(“您要修改的密码”) where user=“root”;
(4)mysql删除匿名空用户:delete from mysql.user where user=’ ';
(5)数据库刷新:flush privileges;
(6)修改网站后台密码:页面,源码,御剑扫描,尝试弱口令进去改管理密码
2、web防护
(1)打包网站目录/var/www/html :tar -cvf xxx.tar 打包对象/*
(2)ssh ftp 将文件拉到本地
①ssh :scp root@192.168.16.8:/root/flag.txt /root/
②ftp:#ftp [IP地址] #get [文件名] 或者用ftp登入软件下载
(3)d盾查杀木马文件,删除文件
①:rm -rf 文件
②:echo其为空:html目录下:echo > xx.php 两个空格
3、站点实时守护
(1)查看进程 关闭现有连接的IP
①:who获取pts,pkill -kill -t pts/进程号
(2)http下新增文件 删除:find ./ -cmin -30 rm -rf 或制空 echo
(3)不死马抗衡删除
创建文件:vim killshell.sh
#!/bin/bash
while true
do
rm -rf xxx.php
done
赋予权限 运行:chmod 777 killshell.sh nohup ./killshell.sh &
进程查看:ps -aux | grep killshell.sh
(4)发现存在漏洞页面,考虑制空
echo > xxx.php
ps:
平台可能root密码为toor 或者内核溢出提权4.4.0-31-generic Ubuntu 内核。
chmod 777 payload (可能需要编译)
./payload
root后删除curl ,防止读取文件 rm -rf /bin/curl
攻击思路:
(1)22端口的弱口令攻击
(2)通过已知的木马,编写读取脚本
(3)不死马种植
思路2:
文件备份与监控
部署监控脚本:无python环境使用jiank_kpy2_z
上传文件后:chmod +x jiank_kpy_z
./执行,选择监控位置:/www/wwwroot/xxx
自动备份文件:www/wwwroot
有python环境:python3 py3监控.py
waf脚本:linux
找到网站子目录上传waf 找到index.php文件包含 waf文件
在第二行包含 include ‘waf3_ruoji_1.php’;保存
会在tmp/1log生成日志文件
当攻击者访问带有flag语句 则会执行假的flag输出
ip封禁
当监控到访问数据包
ip_heimd上传到子目录下
并且包含在waf前面
include ‘ip_heimd.php’;
include ‘waf3_ruoji_1.php’;
考虑封多个IP?
python3搅屎:将对方url输入 持续发送垃圾数据包
ip资产收集 py脚本 循环url
指纹识别 离线 目录扫描 御剑 d盾 w13scan
waf监控脚本
实时监测本地文件的缺失增加
# -*- coding: utf-8 -*-
import os
import re
import hashlib
import shutil
import ntpath
import time
import sys
# 设置系统字符集,防止写入log时出现错误
reload(sys)
sys.setdefaultencoding('utf-8')
CWD = raw_input('脚本监控位置:') # 脚本监控位置
CWD_path =raw_input('备份文件位置位置:')# 备份文件路径
FILE_MD5_DICT = {} # 文件MD5字典
ORIGIN_FILE_LIST = []
# 特殊文件路径字符串
Special_path_str = 'drops_B0503373BDA6E3C5CD4E5118C02ED13A' #drops_md5(icecoke1024)
bakstring = 'back_CA7CB46E9223293531C04586F3448350' #bak_md5(icecoke1)
logstring = 'log_8998F445923C88FF441813F0F320962C' #log_md5(icecoke2)
webshellstring = 'webshell_988A15AB87447653EFB4329A90FF45C5'#webshell_md5(icecoke3)
difffile = 'difference_3C95FA5FB01141398896EDAA8D667802' #diff_md5(icecoke4)
Special_string = 'drops_log' # 免死金牌
UNICODE_ENCODING = "utf-8"
INVALID_UNICODE_CHAR_FORMAT = r"\?%02x"
# 文件路径字典
spec_base_path = os.path.realpath(os.path.join(CWD_path, 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
# 文件MD5消失即为文件被删除,恢复文件
except Exception, e:
print u'[*] 文件被删除 : ' + getUnicode(filepath)
shutil.copyfile(os.path.join(Special_path['bak'], ntpath.basename(filepath)), filepath)
for value in Special_path:
mkdir_p(Special_path[value])
ORIGIN_FILE_LIST = getfilelist(CWD)
FILE_MD5_DICT = getfilemd5dict(ORIGIN_FILE_LIST)
print u'[+] 被删除文件已恢复!'
try:
f = open(os.path.join(Special_path['log'], 'log.txt'), 'a')
f.write('deleted_file: ' + getUnicode(filepath) + ' 时间: ' + getUnicode(time.ctime()) + '\n')
f.close()
except Exception as e:
print u'[-] 记录失败 : 被删除文件: ' + getUnicode(filepath)
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=[]):
for filepath in filelist:
if Special_path_str not in filepath:
shutil.copy2(filepath, Special_path['bak'])
if __name__ == '__main__':
print u'---------持续监测文件中------------'
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)
print u'[*] 所有文件已备份完毕!'
while True:
file_list = getfilelist(CWD)
# 移除新上传文件
diff_file_list = list(set(file_list) ^ set(ORIGIN_FILE_LIST))
if len(diff_file_list) != 0:
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上传文件: ' + getUnicode(filepath)
shutil.move(filepath, os.path.join(Special_path['webshell'], ntpath.basename(filepath) + '.txt'))
print u'[+] 新上传文件已删除!'
except Exception as e:
print u'[!] 移动文件失败, "%s" 疑似WebShell,请及时处理.'%getUnicode(filepath)
try:
f = open(os.path.join(Special_path['log'], 'log.txt'), 'a')
f.write('new_file: ' + getUnicode(filepath) + ' 时间: ' + str(time.ctime()) + '\n')
f.close()
except Exception as e:
print u'[-] 记录失败 : 上传文件: ' + 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'[*] 该文件被修改 : ' + getUnicode(filekey)
shutil.move(filekey, os.path.join(Special_path['difffile'], ntpath.basename(filekey) + '.txt'))
shutil.copyfile(os.path.join(Special_path['bak'], ntpath.basename(filekey)), filekey)
print u'[+] 文件已复原!'
except Exception as e:
print u'[!] 移动文件失败, "%s" 疑似WebShell,请及时处理.'%getUnicode(filekey)
try:
f = open(os.path.join(Special_path['log'], 'log.txt'), 'a')
f.write('difference_file: ' + getUnicode(filekey) + ' 时间: ' + getUnicode(time.ctime()) + '\n')
f.close()
except Exception as e:
print u'[-] 记录失败 : 被修改文件: ' + getUnicode(filekey)
pass
time.sleep(2)
waf黑名单策略(慎用)
<?php
$log_file_path = './log.txt';
$blackIp = ['127.0.0.1'];
/**
* [access 日志记录模块]
* @return [type] [description]
*/
function access(){
global $log_file_path;
if($_FILES!=[]){
$tmp = [];
foreach ($_FILES as $key => $value) {
array_push($tmp,["filename"=>$_FILES[$key]["name"],"contents"=>base64_encode(file_get_contents($_FILES[$key]["tmp_name"]))]);
}
$flow = array(
'Userip'=>$_SERVER['REMOTE_ADDR'],
'Path' =>'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"],
'Post'=>$_POST,
"File"=>$tmp,
'Cookie'=>$_COOKIE,
'Time'=> date('Y-m-s h:i:s',time())
);
}else{
$flow = array(
'Userip'=>$_SERVER['REMOTE_ADDR'],
'Path' =>'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"],
'Post'=>$_POST,
'Cookie'=>$_COOKIE,
'Time'=> date('Y-m-s h:i:s',time())
);
}
$log_path = $log_file_path;
$f = fopen($log_path,'a');
fwrite($f,"\n".json_encode($flow,true));
fclose($f);
}
/**
* [banIP IP封禁模块]
* @return [type] [description]
*/
function banIP(){
global $blackIp;
if(is_file('black.txt')){
$blackIp = array_filter(explode("\n",file_get_contents('black.txt')));
}
$userIP = $_SERVER['REMOTE_ADDR'];
$_not_found = <<<END
<!DOCTYPE html PUBLIC '-//IETF//DTD HTML 2.0//EN'>
<html><head>
<meta http-equiv='content-type' content='text/html; charset=windows-1252'>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL / was not found on this server.</p>
</body>
</html>
END;
if(in_array($userIP,$blackIp)){
$staus_code = "HTTP/1.1 404 Not Found";
header($staus_code);
die($_not_found);
}
}
access();
banIP();
?>
日志审计系统
<?php
session_start();
header("Content-Type:text/html;charset=utf-8");
ini_set('date.timezone','Asia/Shanghai');
$passwd="aaa";//修改密码
$logfilename = "/var/www/html/log.txt";
if(@$_SESSION['user']!=1){
login();
if(isset($_POST['pass'])){
$pass=$_POST['pass'];
login_check($pass);
}
die();
}
/**主功能部分**/
$ip = [];
$maxnum=10;//每页最大数量
$page=intval(@$_GET['p']);
empty($page)?$page=1:$page=intval(@$_GET['p']);
$file = fopen($logfilename, "r") or exit("Unable to open file!");
$filter = "\\<.+javascript:window\\[.{1}\\\\x|<.*=(&#\\d+?;?)+?>|<.*(data|src)=data:text\\/html.*>|\\b(alert\\(|confirm\\(|expression\\(|prompt\\(|benchmark\s*?\(.*\)|sleep\s*?\(.*\)|\\b(group_)?concat[\\s\\/\\*]*?\\([^\\)]+?\\)|\bcase[\s\/\*]*?when[\s\/\*]*?\([^\)]+?\)|load_file\s*?\\()|<[a-z]+?\\b[^>]*?\\bon([a-z]{4,})\s*?=|^\\+\\/v(8|9)|\\b(and|or)\\b\\s*?([\\(\\)'\"\\d]+?=[\\(\\)'\"\\d]+?|[\\(\\)'\"a-zA-Z]+?=[\\(\\)'\"a-zA-Z]+?|>|<|\s+?[\\w]+?\\s+?\\bin\\b\\s*?\(|\\blike\\b\\s+?[\"'])|\\/\\*.*\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT\s*(\(.+\)\s*|@{1,2}.+?\s*|\s+?.+?|(`|'|\").*?(`|'|\")\s*)|UPDATE\s*(\(.+\)\s*|@{1,2}.+?\s*|\s+?.+?|(`|'|\").*?(`|'|\")\s*)SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE)@{0,2}(\\(.+\\)|\\s+?.+?\\s+?|(`|'|\").*?(`|'|\"))FROM(\\(.+\\)|\\s+?.+?|(`|'|\").*?(`|'|\"))|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)|<.*(iframe|frame|style|embed|object|frameset|meta|xml|a|img)|hacker|eval\(.*\)|phpinfo\(\)|assert\(.*\)|\`|\~|\^|<\?php|[oc]:\d+:|pcntl_alarm|pcntl_fork|pcntl_waitpid|pcntl_wait|pcntl_wifexited|pcntl_wifstopped|pcntl_wifsignaled|pcntl_wifcontinued|pcntl_wexitstatus|pcntl_wtermsig|pcntl_wstopsig|pcntl_signal|pcntl_signal_get_handler|pcntl_signal_dispatch|pcntl_get_last_error|pcntl_strerror|pcntl_sigprocmask|pcntl_sigwaitinfo|pcntl_sigtimedwait|pcntl_exec|pcntl_getpriority|pcntl_setpriority|pcntl_async_signals|system\(.*\)|exec\(.*\)|shell_exec\(.*\)|popen\(.*\)|proc_open\(.*\)|passthru\(.*\)|symlink\(.*\)|link\(.*\)|syslog\(.*\)|imap_open\(.*\)|flag|cat\s|etc\spasswd|IFS|display_errors|catch|ini_set|set_time_limit(0)";
function Check_Flux($Value,$ArrFiltReq){
foreach ($Value as $key => $value) {
if(!is_array($value)){
if (preg_match("/".$ArrFiltReq."/is",$value,$m)==1){
return 1;
}
}else{
if (preg_match("/".$ArrFiltReq."/is",implode($value))==1){
return 1;
}
}
}
return 0;
}
function login(){
echo "<center><h3>日志审计系统登陆</h3></center>";
echo "<center><form action=\"\" method=\"POST\">
<input type=\"password\" name=\"pass\">
<input type=\"submit\" name=\"submit\" value=\"Go\">
</form></center>";
}
function jsonIndentFormat($jsonStr)
{
$result = '';
$indentCount = 0;
$strLen = strlen($jsonStr);
$indentStr = ' ';
$newLine = "\r\n";
$isInQuotes = false;
$prevChar = '';
for($i = 0; $i <= $strLen; $i++) {
$char = substr($jsonStr, $i, 1);
if($isInQuotes){
$result .= $char;
if(($char=='"' && $prevChar!='\\')){
$isInQuotes = false;
}
}
else{
if(($char=='"' && $prevChar!='\\')){
$isInQuotes = true;
if ($prevChar != ':'){
$result .= $newLine;
for($j = 0; $j < $indentCount; $j++) {
$result .= $indentStr;
}
}
$result .= $char;
}
elseif(($char=='{' || $char=='[')){
if ($prevChar != ':'){
$result .= $newLine;
for($j = 0; $j < $indentCount; $j++) {
$result .= $indentStr;
}
}
$result .= $char;
$indentCount = $indentCount + 1;
}
elseif(($char=='}' || $char==']')){
$indentCount = $indentCount - 1;
$result .= $newLine;
for($j = 0; $j < $indentCount; $j++) {
$result .= $indentStr;
}
$result .= $char;
}
else{
$result .= $char;
}
}
$prevChar = $char;
}
return $result;
}
function login_check($pass){
$passwd=$GLOBALS['passwd'];
if($pass!=$passwd){//此处修改密码
die("Password error!");
}else{
$_SESSION['user']=1;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<style type="text/css">
a{text-decoration:none}
ul.pagination {
display: inline-block;
padding: 0;
margin: 0;
}
ul.pagination li {display: inline;}
ul.pagination li a {
color: black;
float: left;
padding: 8px 16px;
text-decoration: none;
}
ul.pagination li a.active {
background-color: #4CAF50;
color: white;
}
ul.pagination li a:hover:not(.active) {background-color: #ddd;}
</style>
<title>日志</title>
<body >
<center><h2>日志审计系统</h2></center>
<table class="table table-border table-bordered table-bg" style="margin-top: 10px">
<thead>
<tr class="text-c">
<th width="40">ID</th>
<th >访问IP</th>
<th width="150">数据</th>
<th width="150">时间</th>
<th width="130">类型判断</th>
</tr>
</thead>
<tbody>
<?php
$i=0;
while(!feof($file))
{
$information = fgets($file);
if(empty($information)||$page*$maxnum==$i){
break;
}elseif(empty(json_decode($information,true)['Path'])){
continue;
}elseif($i<($page-1)*$maxnum&&$page!=1){
$i++;
continue;
}else{
$i++;
}
if(Check_Flux(json_decode($information,true),$filter)){
$style="danger";
}elseif(isset(json_decode($information,true)['File'])){
$style="upload";
}else{
$style="active";
}
$information = json_decode($information,true);
?>
<tr class="text-c <?php if($style=="active"&&$i%2==0){
echo "success";
}elseif($style=="active"&&$i%2!=0){
echo "active";
}else{
echo 'danger';
}
;?>">
<td><?php echo $i;?></td>
<td><?php echo $information['Userip'];?></td>
<td ><pre id="json" style="width: 500px;height: 200px;font-size: 10px"><?php
echo jsonIndentFormat(json_encode($information));
?></pre></td>
<td><?php echo $information['Time'];?></td>
<td><?php
if($style=="danger")
echo"疑似攻击";
elseif($style=="upload")
echo "文件上传";
else
echo "正常";
?></td>
</tr>
<?php
}
fclose($file); ?>
</tbody>
</table>
<div style="margin-top: 10px" class="text-c ">
<ul class="pagination">
<li><a href="?p=<?php if($page>1)echo $page-1;?>">上一页</a></li> 、
<li><a href="?p=<?php echo $page+1;?>">下一页</a></li>
</ul>
</div>
<div class="text-c ">
<!--<p target="_blank">共页<br>共1条数据</p>-->
</div>
<style type="text/css">
/*默认table*/
table{width:100%;empty-cells:show;background-color:transparent;border-collapse:collapse;border-spacing:0}
table th{text-align:left; font-weight:400}
/*带水平线*/
.table th{font-weight:bold}
.table th,.table td{padding:8px;line-height:20px}
.table td{text-align:left}
.table tbody tr.success > td{background-color:#dff0d8}
.table tbody tr.error > td{background-color:#f2dede}
.table tbody tr.warning > td{background-color:#fcf8e3}
.table tbody tr.info > td{background-color:#d9edf7}
.table tbody + tbody{border-top:2px solid #ddd}
.table .table{background-color:#fff}
/*带横向分割线*/
.table-border{border-top:1px solid #ddd}
.table-border th,.table-border td{border-bottom:1px solid #ddd}
/*th带背景*/
.table-bg thead th{background-color:#F5FAFE}
/*带外边框*/
.table-bordered{border:1px solid #ddd;border-collapse:separate;*border-collapse:collapse;border-left:0}
.table-bordered th,.table-bordered td{border-left:1px solid #ddd}
.table-border.table-bordered{border-bottom:0}
/*奇数行背景设为浅灰色*/
.table-striped tbody > tr:nth-child(odd) > td,.table-striped tbody > tr:nth-child(odd) > th{background-color:#f9f9f9}
/*竖直方向padding缩减一半*/
.table-condensed th,.table-condensed td{padding:4px 5px}
/*鼠标悬停样式*/
.table-hover tbody tr:hover td,.table-hover tbody tr:hover th{background-color: #f5f5f5}
/*定义颜色*/
/*悬停在行*/
.table tbody tr.active,.table tbody tr.active>td,.table tbody tr.active>th,.table tbody tr .active{background-color:#F5F5F5!important}
/*成功或积极*/
.table tbody tr.success,.table tbody tr.success>td,.table tbody tr.success>th,.table tbody tr .success{background-color:#DFF0D8!important}
/*警告或出错*/
.table tbody tr.warning,.table tbody tr.warning>td,.table tbody tr.warning>th,.table tbody tr .warning{background-color:#FCF8E3!important}
/*危险*/
.table tbody tr.danger,.table tbody tr.danger>td,.table tbody tr.danger>th,.table tbody tr .danger{background-color:#F2DEDE!important}
/*表格文字对齐方式,默认是居左对齐*/
.table .text-c th,.table .text-c td{text-align:center}/*整行居中*/
.table .text-r th,.table .text-r td{text-align:right}/*整行居右*/
.table th.text-l,.table td.text-l{text-align:left!important}/*单独列居左*/
.table th.text-c,.table td.text-c{text-align:center!important}/*单独列居中*/
.table th.text-r,.table td.text-r{text-align:right!important}/*单独列居右*/
.text-l{text-align:left}/*水平居左*/
.text-r{text-align:right}/*水平居中*/
.text-c{text-align:center}/*水平居右*/
.va *{vertical-align:sub!important;*vertical-align:middle!important;_vertical-align:middle!important}
.va-t{ vertical-align:top!important}/*上下居顶*/
.va-m{ vertical-align:middle!important}/*上下居中*/
.va-b{ vertical-align:bottom!important}/*上下居底*/
pre {
outline: 1px solid #ccc; padding: 5px; margin: 5px;
text-align: left;
white-space:pre-wrap;
word-wrap:break-word;
overflow-y:hidden;
overflow-y:scroll;
}
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }
</style>
<script type="text/javascript">
// 方法实现
function syntaxHighlight(json) {
if (typeof json != 'string') {
json = JSON.stringify(json, undefined, 2);
}
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}
var preobject = document.getElementsByTagName("pre") ;
for(i=0;i<preobject.length;i++){
preobject[i].innerHTML = (syntaxHighlight(preobject[i].innerText));
}
</script>
</body></html>
做一个简单的记录,最近刚比赛完