lunedì 26 febbraio 2018

Analyzing the nasty .NET protection of the Ploutus.D malware.

Twitter: @s4tan

EDIT: The source code is now online: https://github.com/enkomio/Conferences/tree/master/HackInBo2018

Recently the ATM malware Ploutus.D reappeared in the news as being used to attack US ATM ([1]). In this post I'll show a possible analysis approach aimed at understanding its main protection. The protection is composed of different layers of protection, I'll focus on the one that, in my hopinion, is the most annoying, leaving the others out. If you want a clear picture of all the implied protections, I strongly recommend you to take a look at the de4dot Reactor deobfuscator code.

Introduction

Reversing .NET malware, in most cases, is not that difficult. This is mostly due to the awesome tool dnSpy ([2]), which allows debugging of the decompiled version of the Assembly. Most of the .NET malware use some kind of loader which decrypts a blob of data and then loads the result through a call to the Assembly.Load method ([3]).

From time to time some more advanced protection are involved, like the one analysed by Talos in [4]. What the article doesn't say is that in this specific case the malware uses a multi files assembly ([5]).

This implies that instead of using the Assembly.Load method, it uses the way less known Assembly.LoadModule method ([6]). This protection method is a bit more difficult to implement but I have to say that is way more effective as obfuscation. The malware also encrypt the method bodies and decrypt them only when necessary. This protection is easily overcome by calling the "Reload All Method Bodies" command in dnSpy at the right moment (as also showed in the Talos article).

Ploutus.D is also protected with an obfuscator which encrypts the method bodies and decrypts them only when necessary. The protector used is .NET Reactor ([7]) as also pointed out in a presentation by Karspersky ([8]). This particular protection is called NecroBit Protection, and from the product website we can read that:

NecroBit is a powerful protection technology which stops decompilation. NecroBit replaces the CIL code within methods with encrypted code. This way it is not possible to decompile/reverse engineer your method source code.


The difference with the previous case is that if we try to use the "Reload All Method Bodies" feature in dnSpy, it will fail (this is not technically correct since there is nothing to reload as we will see).

Reversing Ploutus.D obfuscation

To write this blog post I have reversed the sample with MD5 ae3adcc482edc3e0579e152038c3844e. When I start to analyse a .NET malware, as first task I ran my tool Shed ([9]) in order to have a broad overview of what the malware does and to try to extract dynamically loaded Assemblies. In this case I was able to extract some useful strings (like the configured backend usbtest[.]ddns[.]net) but not the Assembly with the method bodies decrypted (however this is not an error and as we will see it is the correct behaviour).

The next step is to debug the program with dnSpy. If you run it the following Form will be displayed:

I started to dig a bit on the classes that extend the Form class in order to identify which commands are supported. Unfortunately most of the methods of these classes are empty, as can be seen from the following screenshot:


It is interesting to note that all the static constructors are not empty. All of them are pretty simple (in some cases they have just one instruction), what it is interesting is that all of them call the same method: P9ZBIKXMsRMxLdTfcG.Nf9E3QXmJD();, which is marked as internal unsafe static void Nf9E3QXmJD().

By analysing it, the thing start to get interesting since this method is pretty huge, especially since it implements a very annoying control flow obfuscation. It is interesting to notice that if we set a breakpoint on this method and re-start the debugging session, it is amongst the first methods invoked by the program. Scrolling through the code we can find the following interesting statement:

if (P9ZBIKXMsRMxLdTfcG.Ax6OYTY7tiMf4Yu1B4(P9ZBIKXMsRMxLdTfcG.XnSi7dQe0TUTJbDcxg(P9ZBIKXMsRMxLdTfcG.CQNheW6eOQNeBsXbJC(processModule)), "clrjit.dll"))


This piece of code is particularly interesting, since it tries to identify the clrjit.dll module. Once found, it identifies the CLR version, which in my case is 4.0.30319.0. Then, it extracts the resource m7fEJg2w6sBe9LM3D3.i4tjc9Xt0Vhu5G72Uh.

After a while the getJit string appears in the execution. This function is exported by clrjit.dll and it is a very important method since it allows to get a pointer to the compileMethod method. To know more about it you could refer to my Phrack article about .NET program instrumentation ([10]). We can also identify a call to the VirtualProtect method.

With these information we can start to make some assumption, like that the malware hook the compileMethod method in order to force the compilation of the real MSIL bytecode. Let's verify our assumption, in order to do so we need to change tool, in particular we will use WinDbg with the SOS extension (if you want to know more about debugging .NET applications with WinDbg take a look at my presentaion [11]).

In order to inspect the program at the right moment, we will set an exception when the clrjit.dll library is loaded. This is easily done with the command:

sxe ld clrjit.dll
once that this exception is raised let's inspect the clrjit module as showed in the following image:



The getJit method is an exported by clrjit dll and returns the address of the VTable of an ICorJitCompiler object, where the first item is a pointer to the compileMethod method, as can be seen from the source code ([12]). But, since we don't trust the source code, let's debug the getJit method till the ret instruction and inspect the return value stored in eax:


as can be seen from the image above, the address of the compileMethod is at 0x70f049b0. Now let's the program run until the main windows is displayed and then break the process in the debugger. Let's display again the content of the VTable (which was 0x70f71420).


As can be seen from the image above the value of the first entry of the VTable changed to from 0x70f049b0 to 002a0000. So our assumption about the hooking of the compileMethod was right :)

Now we want to identify which method hooked the compileMethod method. To do this we will load the SOS extension (with the command .loadby SOS clrjit), set a breakpoint at the compileMethod method and when the brakpoint hits, type !CLRStack command to see which method was set as replacement. In order to trigger the compileMethod breakpoint I clicked on a random button in the interface.


from the image above we can spot that the interested method is qtlEIBBYuV. Find below the decompiled code of the metohd (I have renamed the argument names and added some comments):

What is interesting from the code above is that:
  • it reads the address of the COREINFO_METHOD_INFO structure at (1)
  • writes back the real MSIL bytecode at (2)
  • updates the fields ILCode and ILCodeSize at (3) and (4)
  • finally call the original compileMethod at (5)
In this way, it is sure that the correct MSIL code is compiled and executed (for more info on this structure please refer to [10,12]).

Finally, we have a pretty good understanding of how the real code is protected, now we can try to implement a simple program which dumps the real MSIL bytecode and rebuilds the assembly. The de4dot tool, instead, uses a different approach, which is based on emulating the decryption code of the method body and then rebuild the assembly.

Let's the code speak

A possible approach to dump the real MSIL bytecode is:
  • Hook the compileMethod before the malware
  • Force all static constructors to be invoked and force compilation of all methods via RuntimeHelpers.PrepareMethod. This will ensure that we are able to grab all the ILCode of the various methods.
  • When the hook is invoked store the values of the fields ILCode and ILCodeSize. We have to record also which method is currently compiled, this is done with the code getMethodInfoFromModule from [10].
  • Rebuild the assembly by using Mono.Cecil or dnlib (my choice)
However, for this specific case, I'll use a slightly different approach, which is not as generic as the previous one but it is simpler and more interesting imho :)

As we have seen from the code above, the P9ZBIKXMsRMxLdTfcG.k6dbsY0qhy is a dictionary of objects which contains the real MSIL bytecode as value and as key the address of the MSIL buffer. What we can do is to read the value of this object via reflection and rebuild the original binary. All this without implying the hooking of any methods :)

I have implemented a simple program that extracts those values via reflection, calculates the address of each method and rebuild the assembly. If you want to take a look it, here is the code.

After dumped the real MSIL, we can see that now the methods are not empty anymore:


Conclusion

The purpose of this post was to show how to analyse, in an effective way, a strongly obfuscate malware with the help of different tools and the knowledge of the internal working of the .NET framework.

As an alternative, if you want to obtain a de-obfuscated sample I encourage you to use the de4dot tool (and to read the code since this project is a gold mine of information related to the .NET internals).

At the time of this writing the sample is not correctly deobfuscated by de4dot due to an error in the string decryption step. To obtain a deobfuscated sample with the real method body, just comment out the string decryption step in ObfuscatedFile.cs.

Too often developers underestimate the power of reflection and as a result it is not uncommon to bypass protection (included license verification code) only by using reflection and nothing more :)

References

[1] First ‘Jackpotting’ Attacks Hit U.S. ATMs - https://goo.gl/6WY14V
[2] dnSpy - https://github.com/0xd4d/dnSpy
[3] Assembly.Load Method (Byte[]) - https://goo.gl/owZtC1
[4] Recam Redux - DeConfusing ConfuserEx - https://goo.gl/oKgj1k
[5] How to: Build a Multifile Assembly - https://goo.gl/mVdHuU
[6] Assembly.LoadModule Method (String, Byte[]) - https://goo.gl/D6N797
[7] .NET REACTOR - http://www.eziriz.com/dotnet_reactor.htm
[8] Threat hunting .NET malware with YARA.pdf - https://goo.gl/RxEw1G
[9] Shed, .NET runtime inspector - https://github.com/enkomio/shed
[10] http://www.phrack.org/papers/dotnet_instrumentation.html
[11] .NET for hackers - https://www.slideshare.net/s4tan/net-for-hackers
[12] getJit() - https://github.com/dotnet/coreclr/blob/master/src/inc/corjit.h#L241

22 commenti:

  1. This concept is a good way to enhance the knowledge.thanks for sharing. please keep it up core Java online training Bangalore

    RispondiElimina
    Risposte
    1. Great Article Cyber Security Projects projects for cse Networking Security Projects JavaScript Training in Chennai JavaScript Training in Chennai The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

      Elimina
    2. CRYPTO ACCOUNT TAKEOVER (ATO) attacks are on the rise and are costing individuals, businesses, and organizations significant financial and damage that are often difficult to recover quickly.
      Cybercriminals use stolen credentials such as usernames and passwords obtained by malware and social engineering to gain sensitive information, and they’re using that same data to access websites and bankings/Bitcoin accounts wallet to transfer money, execute fraudulent transactions and bring people down to a Zero point financially.

      Dhacker is a group of equipped Hackers come together as a team to track down & to recover whatever that has being stolen from you from the most difficult internet SCAMMERS. NOTE!! We've received countless heartbreaking reports of notorious cyber scammers and we’ve successful recover them back.

      contact us on ((Binary Recovery. Files stolen, University Graded, Private Key Recovery, Wiping Criminal Records, Blank ATM Card, FB & IG Telegram Hack, & Phone Hacking)) border us with your jobs & allow us give you positive result with our hacking skills.
      Email binaryoptionservice01@gmail.com pointekhack@gmail.com cyberhackertap@gmail.com we Guarantee you up to %85
      REMEMBER YOUR HAPPINESS IS OUR PRIDE

      Elimina
    3. CRYPTO ACCOUNT TAKEOVER (ATO) attacks are on the rise and are costing individuals, businesses, and organizations significant financial and damage that are often difficult to recover quickly.
      Cybercriminals use stolen credentials such as usernames and passwords obtained by malware and social engineering to gain sensitive information, and they’re using that same data to access websites and bankings/Bitcoin accounts wallet to transfer money, execute fraudulent transactions and bring people down to a Zero point financially.

      Dhacker is a group of equipped Hackers come together as a team to track down & to recover whatever that has being stolen from you from the most difficult internet SCAMMERS. NOTE!! We've received countless heartbreaking reports of notorious cyber scammers and we’ve successful recover them back.

      contact us on ((Binary Recovery. Files stolen, University Graded, Private Key Recovery, Wiping Criminal Records, Blank ATM Card, FB & IG Telegram Hack, & Phone Hacking)) border us with your jobs & allow us give you positive result with our hacking skills.
      Email binaryoptionservice01@gmail.com pointekhack@gmail.com cyberhackertap@gmail.com we Guarantee you up to %85
      REMEMBER YOUR HAPPINESS IS OUR PRIDE

      Elimina
  2. Such an ideal piece of blog. It’s quite interesting to read content like this. I appreciate your efforts.
    read Major Differences Between Adware and Malware

    RispondiElimina
  3. It 's an amazing article and useful for developers
    .Net Online Course Hyderabad

    RispondiElimina
  4. If you want to read some high-quality articles, then this blog is surely going to be one of your favorites very soon! PRIVACY BREACH WHILE YOUR SMARTPHONE IS IDLE!

    RispondiElimina
  5. Now you buy one the top rate bitcoin mining machine asic antminer s9 for sale at very low price, it is on sale direct from china, Yes, 100% brand new working fine with complete packing and free shipment

    RispondiElimina
  6. I just loved your article on the beginners guide to starting a blog.If somebody take this blog article seriously
    in their life, he/she can earn his living by doing blogging.Thank you for this article.
    java online training

    RispondiElimina
  7. I just loved your article on the beginners guide to starting a blog.If somebody take this blog article seriously
    in their life, he/she can earn his living by doing blogging.Thank you for this article.
    best java online training

    RispondiElimina
  8. I just loved your article on the beginners guide to starting a blog.If somebody take this blog article seriously
    in their life, he/she can earn his living by doing blogging.Thank you for this article.
    best java online training

    RispondiElimina
  9. I got my PROGRAMMED ATM CARD to
    withdraw the maximum of $5,000 daily for a maximum of 30
    days via (wesleymarkhackers@gmail.com).

    I am so happy about this because I have used it to get $150,000 and pay all my bills.

    He also GRANT LOAN at 3% and RECOVERS LOST BITCOINS and also . you might have lost your bitcoin either by mismanagement or hacking.

    Contacting him now for a financial solution.

    email : wesleymarkhackers@gmail.com

    whatsapp: +19379917481

    RispondiElimina
  10. Are you interested in the service of a hacker to get into a phone, facebook account, snapchat, Instagram, yahoo, Whatsapp, get verified on any social network account, increase your followers by any amount, bank wire and bank transfer. Contact him on= hackintechnology@gmail.com +12132951376(WHATSAPP)

    RispondiElimina
  11. HOW I GO MY DESIRED LOAN AMOUNT FROM A RELIABLE AND TRUSTED LOAN COMPANY LAST WEEK. Email for immediate response: drbenjaminfinance@gmail.com Call/Text: +1(415)630-7138 Whatsapp +19292227023

    Hello everyone, My name is Mr.Justin Riley Johnson, I am from Texas, United State, am here to testify of how i got my loan from BENJAMIN LOAN INVESTMENTS FINANCE(drbenjaminfinance@gmail.com) after i applied Two times from various loan lenders who claimed to be lenders right here this forum,i thought their lending where real and i applied but they never gave me loan until a friend of mine introduce me to {Dr.Benjamin Scarlet Owen} the C.E.O of BENJAMIN LOAN INVESTMENTS FINANCE who promised to help me with a loan of my desire and he really did as he promised without any form of delay, I never thought there are still reliable loan lenders until i met {Dr.Benjamin Scarlet Owen}, who really helped me with my loan and changed my life for the better. I don't know if you are in need of an urgent loan also, So feel free to contact Dr.Benjamin Scarlet Owen on his email address: drbenjaminfinance@gmail.com BENJAMIN LOAN INVESTMENTS FINANCE holds all of the information about how to obtain money quickly and painlessly via Whatsapp +19292227023 Email: drbenjaminfinance@gmail.com and consider all your financial problems tackled and solved. Share this to help a soul right now, Thanks

    RispondiElimina
  12. My name is Jane Wembli Josh and i live in the USA California and life is worth living right now for me and my family and all this is because of one man sent by GOD to help me and my family, i once had a life filled with sorrow because my first SON needed a kidney transplant and all our savings were going towards his medications and this normally leaves us with no money to pay our bills or even put enough food on our table and our rent was due and no funds to pay these bills and life felt so unfair to me and every night my wife will cry herself to sleep every night until one day, i was browsing through yahoo answers and i saw a striking advert of a man that gives out personal loans and that the offer is opened to all and i have heard so many things about internet scams but at this point of my life, i was very desperate and ready to take any risk and at the end of the day, i applied for this loan and from one step to another, i got my loan within 12 hours through bank transfer and you know, it was all like a dream and i called Rev. Fr. Kevin Doran A Man who is the GOD sent lender i found and said, i have received my loan and he smiled stating that to GOD be the glory and i was so shocked as i have never ever seen anyone with such a GOD fearing and kind heart and today, i am the happiest man on earth because by GOD’S grace, my SON kidney transplant was successful and today he is healthy, i and my family are living very comfortable and happy and if you are in my former situation or in serious and legitimate need of a loan, you can reach this GOD sent lender via consumerloanfirm@gmail.com

    RispondiElimina
  13. Email: Deepwebhackers00@gmail.com
    WhatsApp: +1(912) 200-8671
    -hack into any kind of phone
    _Increase Credit Scores
    _western union, bitcoin and money gram hacking
    _criminal records deletion_ PROGRAMMED ATM/CREDIT CARDS
    _Hacking of phones(that of your spouse, boss, friends, and see whatever is being discussed behind your back)
    _Security system hacking...and so much more. Contact THEM now and get whatever you want at

    Prices for clone cards with their balance that we offer:


    * Gold VISA- € 450 ----> Balance € 250,000 Daily withdrawal of € 1,500, validity 24 months

    * Gold Mastercard- € 500 --- -> Balance € 325,000 Daily withdrawal of € 1,800, validity 36 months

    * Platinum Visa - € 550 ----> Balance € 480,000 Daily withdrawal of € 2,000, validity 24 months

    * Platinum Mastercard - € 600 ----> Balance € 620,000 Daily withdrawal of € 2,500, validity 36 months

    * Infinity Visa - € 750 ----> Balance € 750,000 Daily withdrawal of € 3,000, validity 24 months

    * Infinity Mastercard - 850 € ----> Balance 850,000 € Daily withdrawal of 3500 €, validity 36 months

    Once payment has been made 12h to 48h in Europe and 12h to 72H worldwide
    After your order will be available, at the delivery address given.
    Shipping is by courier with parcel tracking within 2hrs after payment

    If you order regularly with us, we guarantee that you will not miss anything in the near future.

    Email: Deepwebhackers00@gmail.com
    WhatsApp: +1(912) 200-8671

    RispondiElimina
  14. Very informative and impressive post you have written, this is quite interesting and i have went through it completely, an upgraded information is shared, keep sharing such valuable information. Web Security Courses

    RispondiElimina
  15. i was lost with no hope for my wife was cheating and had always got away with it because i did not know how or

    always too scared to pin anything on her. with the help a friend who recommended me to who help hack her phone,

    email, chat, sms and expose her for a cheater she is. I just want to say a big thank you to

    HACKINTECHNOLOGY@CYBERSERVICES.COM . am sure someone out there is looking for how to solve his relationship problems, you can also contact him for all sorts of hacking job..he is fast and reliable. you could also text +1 213-295-1376(whatsapp) contact and thank me later

    RispondiElimina