Skip to content
Smart contracts Audit finding Advanced

Incorrect HexString Parsing Leads To Compilation Error Or Type Confusion

Vyper's pre-parser for hex string literals tracks source locations incorrectly when earlier code transformations shift offsets, causing valid code to fail compilation or invalid code to compile with a type confusion. An attacker could exploit this to make a contract call pass a string where bytes are expected, leading to incorrect behaviour.

anatomist Follow

Originally disclosed on Immunefi

  • Disclosed after under an hour

#37582 [SC-Low] Incorrect HexString Parsing Leads To Compilation Error Or Type Confusion

Submitted on Dec 9th 2024 at 20:26:34 UTC by @anatomist for Attackathon | Ethereum Protocol

  • Report ID: #37582
  • Report Type: Smart Contract
  • Report severity: Low
  • Target: https://github.com/vyperlang/vyper
  • Impacts:
    • (Compiler) Incorrect bytecode generation leading to incorrect behavior
    • (Compiler) Unexpected behavior
    • (Compiler) Semantic analysis errors

Description

Brief/Intro

Hex string pre-parsing without considering position adjustments may result in mismatched offsets, and eventually cause compiler failure or type confusions.

Vulnerability Details

Vyper supports several custom syntax, and one of those are HexString, written in the x'01234' syntax, and treated as Bytes[] literal values. Since HexString is not legal python syntax, a pre-parsing pass must be made to "fix" the code before passing it to python.ast module for parsing. The fixing rule is relatively simple, it just strips the leading x, and track occurances in hex_string_locations.

class HexStringParser:
    def __init__(self):
        self.locations = []
        self._current_x = None
        self._state = ParserState.NOT_RUNNING

    def consume(self, token, result):
        # prepare to check if the next token is a STRING
        if token.type == NAME and token.string == "x":
            self._state = ParserState.RUNNING
            self._current_x = token
            return True

        if self._state == ParserState.NOT_RUNNING:
            return False

        if self._state == ParserState.RUNNING:
            current_x = self._current_x
            self._current_x = None
            self._state = ParserState.NOT_RUNNING

            toks = [current_x]

            # drop the leading x token if the next token is a STRING to avoid a python
            # parser error
            if token.type == STRING:
                self.locations.append(current_x.start)
                toks = [TokenInfo(STRING, token.string, current_x.start, token.end, token.line)]
                result.extend(toks)
                return True

            result.extend(toks)

        return False

Later when visiting ast nodes, the hex_string_locations are looked up and used to annotate ast nodes as Bytes type instead of Str type.

def visit_Constant(self, node):
    ...
    elif isinstance(node.value, str):
        key = (node.lineno, node.col_offset)
        if key in self._pre_parser.hex_string_locations:
            if len(node.value) % 2 != 0:
                raise SyntaxException(
                    "Hex string must have an even number of characters",
                    self._source_code,
                    node.lineno,
                    node.col_offset,
                )
            node.ast_type = "HexBytes"
        else:
            node.ast_type = "Str"
    ...

However, it is overlooked the pre-parsing of HexString may

  1. Get placed in a location where there were prior code adjustments that changes "fixed" occurance locations
  2. HexString consumes leading x and may change "fixed" code locations itself.

This has several implications. The immediate consequence is compilation failure. For example, the following code fails to compile while it should

event X:
    a: Bytes[2]

@deploy
def __init__():
    log X(a = x"6161")  #log changes offset of HexString, and the hex_string_locations tracked location is incorrect when visiting ast

Slightly more consequential, code that should fail to compile can now compile fine, and suffer a type confusion + incorrect value interpretation at the same time. For example, the following code shouldn't compile, but it does, and it incorrectly passes "6161" as second argument to FooBar.test instead of b"\x61\x61".

interface FooBar:
    def test(a: Bytes[2], b: String[4]): payable

@deploy
def __init__(ext: FooBar):
    extcall ext.test(x'6161', x'6161')  #ext.test(b'\x61\61', '6161') gets called

Additionally, the state machine of HexString pre-parser is also slightly flawed, and allows code such as the following to compile.

@deploy
def __init__():
    a: Bytes[2] = x x x x x"6161"

Impact Details

  1. Compilation failure for legal code
  2. Potential type confusion when coupled with a user mistake in type specification
  3. Allow illegal code to compile

References

  • https://github.com/vyperlang/vyper/blob/e98e004235961613c3d769d4c652884b2a242608/vyper/ast/pre_parser.py#L136
  • https://github.com/vyperlang/vyper/blob/e98e004235961613c3d769d4c652884b2a242608/vyper/ast/pre_parser.py#L282
  • https://github.com/vyperlang/vyper/blob/e98e004235961613c3d769d4c652884b2a242608/vyper/ast/parse.py#L398

Proof of Concept

Proof of Concept

Already shown in Vulnerability Details section.

The original report as published on Immunefi, by anatomist. Images and videos are our own copies; raw HTML is shown as text. View it on Immunefi.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

How it worked

Root cause

The hex string pre-parser records source locations without accounting for offset changes caused by other pre-parsing transformations or by its own removal of the leading 'x' token.

Impact

Legal code may fail to compile, and illegal code may compile and cause a type confusion where a string is passed instead of bytes, leading to incorrect behaviour.

What the attacker needed

Compiling Vyper code with hex strings; hex string near other pre-parsed syntax

Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

Vyper is a programming language for smart contracts. It has a special way to write byte strings, like x'6161', which is not valid Python, so a pre-processing step rewrites it before the real parser runs. That step records where each hex string was, but if other rewrites change the positions, the recorded locations become wrong, so the compiler may reject good code or accept bad code and misinterpret values.

What is Smart contracts?

Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.

More by anatomist

View all

11 more disclosed reports, best first.

More from Ethereum Protocol

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Smart contract vulnerabilities

The lesson behind this report.

Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.