天天看點

CTF線下AWD攻防步驟總結

CTF線下AWD攻防步驟總結

Hello,我是普通Gopher,00後男孩,極緻的共享主義者,想要成為一個終身學習者。專注于做最通俗易懂的計算機基礎知識類公衆号。每天推送Golang技術幹貨,内容起于K8S而不止于K8S,涉及Docker、微服務、DevOps、資料庫、虛拟化等雲計算内容及SRE經驗總結

=======================

初次見面,我為你準備了100G學習大禮包:

1、《百餘本最新計算機電子圖書》

2、《30G Golang學習視訊》

3、《20G Java學習視訊》

4、《90G Liunx進階學習視訊》

5、《10G 算法(含藍橋杯真題)學習視訊》

6、《英語四級,周傑倫歌曲免費送!》

路過麻煩動動小手,點個關注,持續更新技術文章與資料!

ctf線下AWD攻防賽學習筆記:https://blog.csdn.net/qq_43442524/article/details/102653414

CTF AWD模式下簡單的CMS代碼審計:https://blog.csdn.net/qq_43442524/article/details/102409351

AWD競賽

CTF線下AWD攻防步驟總結

前半個小時應熟悉配置環境。準備網線、網線轉接口

最好的防禦就是攻擊,一定要做好安全加強

本次記錄的目的是為了給自己一個月來的準備弄個交代,感覺自己跟大佬們差的很遠,隻拿了三等,往後的路還很長,還是需要億點點的努力,無限進步.

工具連結:

https://github.com/PlutoaCharon/AWD-Attack-Defense

賽前準備

常用工具:

  • Burpsuite
  • sqlmap
  • nmap、masscan
  • nc
  • D盾
  • Xshell、Xftp
  • 菜刀或蟻劍
  • Chrome、Firefox各類插件

一句話木馬:

  • php
  • asp
  • aspx
  • jsp
  • 記憶體馬

代碼比較工具:

BeyondCompare(windows)

Kaleidoscope(mac)

提前準備好各種cms的poc exp (因為你們不允許聯網)phpwin phpcms dz

CMS_POC

防守步驟

0x00 ssh登陸,修改密碼

普通使用者提權成root,根據kernel版本号找到對應的poc,exp提權

0x01 下載下傳源碼,備份,/var/www/html 目錄

定時備份源碼:

#!/bin/bash
while [ 1 ]
do
time=`/bin/date +%H-%M-%S`
bak_file="/var/www/$time.tar.gz"
webdir="/var/www/html"
tar zcvf $bak_file $webdir >/dev/null 2>&1 &
sleep 60                               //一分鐘備份一次
done
           

備份資料庫

1、找資料庫配置檔案,找到

db_name、db_user

db_passwd

2、登陸資料庫,指令備份資料庫:

mysqldump -u db_user -p db_passwd db_name > bak.sql//備份指定資料庫

cd /var/lib/mysql

mysqldump -u db_user -p db_passwd > bak.sql//先進入資料庫目錄再備份

mysqldump --all-databases > bak.sql //備份所有資料庫

3、還原資料庫:

mysql -u db_user -p db_passwd db_name < bak.sql //還原指定資料庫

cd /var/lib/mysql

mysql -u db_user db_passwd < bak.sql //先進入資料庫目錄再還原

還有一種方法:

mysql -u db_name -p
input passwd 進入mysql控制台mysql>
mysql> show databases;看看有哪些資料庫
mysql> create database test ; 建立要還原的資料庫
mysql> use test;切換到剛建立的資料庫
mysql> source test.sql; 導入資料庫
           

關閉 MySQL 遠端登入

# mysql -u root -p
mysql> use mysql;
mysql> update user set host = 'localhost' where user='root' and host='%';
mysql> flush privileges;
mysql> exit;
           

隐藏使用者

檢視home目錄下是否有其他使用者
/etc/passwd是否有/bin/bash的使用者
           

0x02 掃描預留後門,禦劍,k8飛刀,D盾,掃描目錄,發現後門,注釋代碼

# 簡單的查找後門
find . -name '*.php' | xargs grep -n 'eval('
find . -name '*.php' | xargs grep -n 'assert('
find . -name '*.php' | xargs grep -n 'system('
           

0x03 修改資料庫密碼

mysql -u root -p
Show databases;
use mysql;
set password for [email protected] = password('123'); 或者
update user set password = PASSWORD('要更換的密碼') where user = 'root';
flush privileges;
show tables;可能有flag。
select * from typecho_flag;
           

0x04 關閉不必要的端口,要求的服務端口不能關

netstat -napt ,lsof -i

檢視端口,

kill -9 PID

殺掉程序

nmap -sV ip位址

(-sV參數可以探測目标主機的伺服器版本)

nmap

掃描對方開啟的端口,21,22,21,3306,進行爆破

msfconsole

進入

metasploit

,

hydra

可以對22端口進行爆破

0x05 代碼審計,使用seay源代碼審計,或者Rips代碼審計

可以參考我寫的這篇部落格

Rips工具使用

0x06 木馬清除

關于木馬

  • 關注服務的可用性狀況
  • 檢視檔案監控情況
  • 在被攻擊的時候進行響應,儲存相應的流量,查找/清除後門
建議使用apache使用者來删除

通過檔案監控檢視系統異常情況

檔案監控腳本

# -*- 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())
           

不死馬清理:

ps aux www|grep shell.php

找到pid後殺掉程序就可以,你删掉腳本是起不了作用的,因為php執行的時候已經把腳本讀進去解釋成opcode運作了

重新開機php等web服務

用一個

ignore_user_abort(true)

腳本,一直競争寫入(斷斷續續)。usleep要低于對方不死馬設定的值。

建立一個和不死馬生成的馬一樣名字的檔案夾。

不死馬、waf、抓流量的waf

不死馬使用原理就是不斷将的自己寫入,造成程序占用,被删除後一秒就已經生成新的了,還有就是.XXX檔案建立隐藏檔案不死馬。
waf,腳本waf可以防止一般情況下的危險字元,但是不能報太大希望,
           

require_once('waf.php');

抓流量waf,挂載後可以讓防守隊員_實時關注日志,一旦發現被getflag了,就通過日志相應的手法攻擊别人
           

waf腳本

PHPWaf用來記錄通路請求,通過分析通路請求來判斷對方的攻擊方式,作用是感覺漏洞,判斷攻擊方式,進而修複漏洞。
<?php
 //部署waf可能會導緻服務不可用,需要謹慎部署。
    error_reporting(0);
    define('LOG_FILENAME','log.txt');
    function waf()
    {
        if (!function_exists('getallheaders')) {
            function getallheaders() {
                foreach ($_SERVER as $name => $value) {
                    if (substr($name, 0, 5) == 'HTTP_')
                        $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
                }
                return $headers;
            }
        }
        $get = $_GET;
        $post = $_POST;
        $cookie = $_COOKIE;
        $header = getallheaders();
        $files = $_FILES;
        $ip = $_SERVER["REMOTE_ADDR"];
        $method = $_SERVER['REQUEST_METHOD'];
        $filepath = $_SERVER["SCRIPT_NAME"];
        
        //rewirte shell which uploaded by others, you can do more
        foreach ($_FILES as $key => $value) {
            $files[$key]['content'] = file_get_contents($_FILES[$key]['tmp_name']);
            file_put_contents($_FILES[$key]['tmp_name'], "virink");
        }
        unset($header['Accept']);//fix a bug
        $input = array("Get"=>$get, "Post"=>$post, "Cookie"=>$cookie, "File"=>$files, "Header"=>$header);
        //deal with
        $pattern = "select|insert|update|delete|and|or|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile|dumpfile|sub|hex";
        $pattern .= "|file_put_contents|fwrite|curl|system|eval|assert";
        $pattern .="|passthru|exec|system|chroot|scandir|chgrp|chown|shell_exec|proc_open|proc_get_status|popen|ini_alter|ini_restore";
        $pattern .="|`|dl|openlog|syslog|readlink|symlink|popepassthru|stream_socket_server|assert|pcntl_exec";
        $vpattern = explode("|",$pattern);
        $bool = false;
        foreach ($input as $k => $v) {
            foreach($vpattern as $value){
                foreach ($v as $kk => $vv) {
                    if (preg_match( "/$value/i", $vv )){
                        $bool = true;
                        logging($input);
                        break;
                    }
                }
                if($bool) break;
            }
            if($bool) break;
        }
    }
 
    function logging($var){
        file_put_contents(LOG_FILENAME, "\r\n".time()."\r\n".print_r($var, true), FILE_APPEND);
        // die() or unset($_GET) or unset($_POST) or unset($_COOKIE);
    }
    waf();
?>
           

waf的激活方式:

1. php.ini選項:auto_prepend_file =與auto_append_file =包含waf,需要權限較高。

2. config.php 中包含waf

3. 讓所有的檔案都包含waf
           

0x07流量分析

  1. 檢視目前通路量前十的連結

cat /var/log/apache2/access.log | cut -f4 -d | sort | uniq -c | sort -k -r | head -

  1. 檔案監控增删改查的檔案使用腳本Monitor(一個簡單的檔案監控示例腳本,可以監控建立、删除、移動、屬性修改操作,自動删除新增檔案或目錄。已使用pyinstaller打包成了linux可執行程式)
  2. chattr +i 指令鎖死網站目錄和檔案,防止其他隊伍删除網站當機。注:添加後不取消特殊權限 即使是root使用者也無法删除/修改檔案

    chattr -R +i /var/www/html

    chattr -R +i /var/www/html/*

    (取消指令将+号改成- chattr -R -i /var/www/html)

  3. 使用waf全局包含waf,注意waf的日志和weblogger日志與第二項檔案監控沖突,建議建立檔案夾将日志和weblogger日志放到指定檔案夾中,避開檔案監控,

    sudo find /var/www/html/path_you_want -type f -path “*.php” | xargs sed -i “s/<?php/<?php\nrequire_once(’/tmp/waf.php’);\n/g”

    #意思就是查找需要加waf的目錄下所有php檔案,在頭部添加一句,用require_once函數引入/tmp/waf.php檔案。因為sed指令利用 / 區分檔案中的原字元串和修改的字元串,是以我們要對 / 進行轉義。類似于在單引号中再次使用單引号時我們也要用反斜杠轉義。

  4. 背景一定要登陸背景,有沒有弱密碼,修改成強密碼。
  5. 不隻是背景,phpmyadmin、測試頁面容易出現sql注入,rce之類的這些

AWD資源小合集:

https://neversec.top/20190415/how-to-awd.html

參考網站:

https://blog.csdn.net/qq_42114918/article/details/82785960#comments

https://blog.csdn.net/qq_43625917/article/details/96158713

http://www.admintony.com/AWD%E8%A5%BF%E7%9F%B3%E6%B2%B9%E7%BA%BF%E4%B8%8B%E8%B5%9B%E6%80%BB%E7%BB%93.html

https://blog.csdn.net/like98k/article/details/80261603

http://www.8sec.cc/index.php/archives/97/