Threat Research

Offense and Defense – A Tale of Two Sides: PowerShell

By Anthony Giandomenico | March 02, 2020

FortiGuard Labs Threat Analysis

Introduction 

This is the start of a new blog series I’m calling “Offense and Defense – A Tale of Two Sides.” This monthly series will focus on the different tactics and techniques adversaries are known to use to complete their cyber missions, and how organizations can detect and ultimately prevent them. I will use the Mitre ATT&CK knowledgebase and terminology to guide us through the various techniques. If you don’t know what Mitre ATT&CK is all about, please visit the blog and video I did back in 2018, called Smarter Security Starts with Understanding How Cybercriminals Work

One of the reasons I am using the ATT&CK knowledge base is there’s a movement in the security industry to get more granular on assessing how effective or ineffective a given security posture is against real-world attacks. And a growing number of organizations and cybersecurity professionals are using the knowledge base to more accurately measure that effectiveness. If you’re not one of those organizations that is doing this yet, I highly recommend that you consider adopting it. You can thank me later.

For this first blog, I am going to start with an analysis of the ever-popular tool called PowerShell

PowerShell Overview 

Microsoft’s .NET is a free, cross-platform web services strategy designed to help administrators quickly build applications using multiple language editors and libraries. PowerShell, first released in November of 2006, is a command-line scripting language that was built on .NET to help administrators and power users rapidly automate some of the daily tasks required to manage the operating system. It is also used to quickly building cross-platform applications using multiple language editors and libraries. It has pretty much become de facto standard when it comes to administering the operating systems in a network. It is now opensource and installed by default on many Windows versions.

With that said, most of us also know that the bad guys have been pretty successful at taking advantage of this easy-to-use scripting language, including using it to install their malicious payloads. Here are a few of the reasons why: 

  • PowerShell now comes pre-installed on Windows machines
  • It provides an easy method for executing arbitrary payloads directly from memory – a potentially useful feature, but one that also allows the delivery of fileless malware 
  • It is easy to obfuscate to evade signature-based defenses
  • PowerShell is a trusted tool (Admins use it every day), and it is usually not hardened
  • Many malicious scripts using PowerShell are freely available, including tools such as PowerShellEmpire, PowerSploit, etc.

Because of these and similar advantages, cyber adversaries have been very successful in using PowerShell over the years. Fortunately, later versions of the scripting language include the ability to better secure your PowerShell environment. 

Defenses Against PowerShell Attacks

Here are some of PowerShell’s defenses you can leverage:

  • Constrained Language Mode 
    • Locks down direct access to: .NET scripting, the invocation of Win32 APIs via the Add-Type cmdlet, and interaction with COM objects (NOTE: careful with this, as you might break some of your existing PowerShell administration tasks)
       
  • PowerShell v5 (This version has a lot of good features for better security – so upgrade) 
    • Script block logging – Allows you to see what a script was trying to do. Prior to this version, this activity was not logged.
    • System-wide transcripts 
    • Anti-Malware integration (included with version 3) – AMSI (anti-malware scan interface) provides an interface for other security vendors to look at a script before it runs. (A good tool, but some bypass attacks still can get through) 
    • Applocker – Helps to validate the script against applocker policy.
       
  • Logging PowerShell Activity 
    • Enables logging via Group Policy for various PowerShell modules. 
       
  • Remove PowerShell v2
    • This is an older, insecure version that is not removed when you install version 5. If it’s present, attacks can still use this insecure version. (powershell.exe -Version 2.0 -Command {<scriptblock>} -ExecutionPolicy <ExecutionPolicy>)
       
  • Code Signing
    • You can code sign your PowerShell scripts and only have those signed scripts run. (There are still ways to get around that as well, but it helps) 
       
  • Just Enough Administration (JEA) 
    • Enables role-based administration through PowerShell remoting. This allows you to limit what is executed based on the logged-in user. 

As you may have noticed, peppered in between the security measures I suggested you take, I also mentioned that there are still ways for an adversary to get around some of those methods. Some of these bypass techniques are PowerShell downgrade attacks, process injection, and PowerShell obfuscation, etc. However, they are still valuable because not every attacker knows how to execute these bypass attacks, so they will provide protection against less skilled adversaries (which may be the majority of them.) Also keep in mind that you can run PowerShell scripts without calling powershell.exe. 

Real-World Examples & Detections 

Typically, the bad guys will leverage PowerShell in conjunction with a weaponized document, such as a Word or Excel file, to execute a malicious payload. Usually, the document will contain a macro which will call PowerShell to execute its malicious payload. Of course, there are many other ways that the tool can be used, but for now, let’s focus on some common techniques that use PowerShell to download and execute a file. 

PowerShell allows you to download a file by using Invoke-WebRequest, System.Net.WebClient, and Start-BitsTransfer. You can then use Start-Process, Invoke-item, or Invoke-Expression to run the downloaded file. If you ever see this combination, and you know your admins don’t use these tools to download and execute files, it could be malicious and something worth checking out. 

In addition to downloading a file, System.Net.Webclient also lets you download the contents of a file directly into a running process in memory and then run it. This is better known as “fileless malware,” and is used to try and bypass traditional AV products. Below are two methods using the System.Net.Webclient cmdlet, along with some real-world examples of malicious scripts we’ve seen in the wild used to download a malicious payload and then execute it. 

  • (New-object System.net.webclient).Downloadfile() – File is downloaded to disk 
  • (New-object System.net.webclient).DownloadString() – Moves contents directly into memory 

In figure 1 below, you can see an example of an attacker generating a PowerShell code that downloads an Emotet file from several URLs that are dynamically generated. If you want to read more about this threat, please check out our blog created last year: Analysis of a Fresh Variant of the Emotet Malware.

 

Figure 1. PowerShell code used to download an Emotet file

This next example, in figure 2, shows PowerShell downloading a widely known threat called NetWire RAT, which records all of a victim’s keyboard actions (keystroke logger). FortiGuard Labs previously blogged about a variant of this threat, called New NetWire RAT Variant Being Spread Via Phishing if you want to learn more. 

Figure 2. PowerShell downloading NetWire RAT

For an example of a recent threat leveraging PowerShell to load its payload, take a look at our Predator the Thief blog written earlier this year. It leverages a malicious Word doc -> macro-> obfuscated PowerShell to download-> Autoit to run a decoded Autoit script, which eventually loads a payload into a process via process hollowing. (This is a technique we will dive into later in the blog series) 

As you start to investigate the malicious ways that the bad guys are leveraging PowerShell, including those shown above, you’re going to find out that more investigating may be needed to determine if a detected process is malicious or not. One of the many ways to do that is to look at processes that have spawned other processes – in other words, look at the parent and grandparent processes. The important thing here is to know what’s normal and what’s not when it comes to parent and child process relationships. 

For example, it’s normal or typical to see powershell.exe spawned by explorer.exe, but if cmd.exe is the parent process for powershell.exe, that might be a bit more suspicious, as many of the malicious attacks come through the command line process. Yes, it could still be legit, but we can then go back to the process that spawned cmd.exe. If it’s being called by an MS office program, such as Word or Excel, there is a VERY good chance it’s malicious. When our FortiResponder team sees this sort of forensics tree in FortiEDR, it’s usually a phishing attack, and some user clicked on something they shouldn’t have. 

As you can see, it’s very important to understand process relationships. In addition to MS Office programs spawning cmd.exe and then powershell.exe, some other ones you may want to pay attention to are mshta, tasking, wuapp, wscript, and script. 

In addition, identifying the destination IP address is always a good practice if PowerShell is trying to download something. Keep a lookout for randomized script names every time it’s launched while the extension stays the same. In figure 3, below, you can see that the parent/child process relationship is suspicious, and when you investigate the IP address, you can recognize that it is a possible C&C server.

Figure 3. Suspicious Parent/Child relationship

Other signs to look for to detect malicious PowerShell activities are the flag options. Below are a few to look out for. 

  • Exec Bypass – This allows you to get around the execution policy after it has been set. Even if you have restrictions set for better security, this flag can bypass some of them. 
  • WindowsStyle hidden – As you can tell, this one will make hide operations from the user. 
  • Nop or Noprofile – This flag will ignore the commands in the profile that you have set.
  • Enc /Encode– This will encode using base64 encoding.
  • Mixed Case – Text is mixed between upper and lower case
  • lex – Runs commands or expressions 

Below, in figure 4, is an example of a PowerShell script encoded in Base64.

Figure 4. PowerShell script encoded in Base64

Most of what I stated above deals with adversaries leveraging PowerShell to execute payloads to gain initial access onto a machine. But keep in mind that PowerShell techniques can also be used to move laterally across the network and/or to establish persistence. 

Once you get a good understanding of the various ways that the bad guys can use PowerShell, you need to make sure you are collecting the right logs as well as setting the right security controls. If you’re leveraging our FortiEDR technology and/or our FortiResponder MDR service, you are in good shape as we either protect against or will detect and respond to all known (and many unknown threats) when it comes to PowerShell. Another good Fortinet Security Fabric control you can use for detection is FortiSIEM with our Windows agent/Sysmon. This includes many pre-canned rules that can trigger on malicious activity being executed via PowerShell. Figure 5, below, shows an alert triggering on PowerShell opening and then trying to download something. 

Figure 5. Alert triggered by PowerShell opening and downloading a file

If you do not have either of these controls or a similar technology in place and you want to do this on your own, make sure you are logging the process information (look for event 4688/4104) on the endpoints, and have the ability to view PowerShell script (script-block logging) contents. This will allow you to start creating your own triggers, although it may be tough as there are a variety of indicators to take into consideration, and they are always growing. Figure 6 provides is an example of a PowerShell script downloading and executing MimiKatz with the intent to dump credentials. 

Figure 6. PowerShell script downloading and executing MimiKatz

Reproducing the Technique

As you become more familiar with the malicious ways PowerShell can be used, you will need to test your own defenses or hire a consulting company to test them for you. Either way, it’s always good to understand the tools you can use. Some of these tools are listed below.

 Simulation Tools 

  • Atomic Red Team
    • Test controls by executing simple and atomic tests that exercise the same techniques used by adversaries.
       
  • APT Simulator 
    • A Windows Batch script that uses a set of tools and output files to make a system look as if it was compromised.
       
  • Caldera (mostly post-compromise)
    • An automated adversary emulation system that performs post-compromise adversarial behavior within Windows Enterprise networks.

Open Source Defense Testing Tools 

  • Kali Linux /Metasploit
    • Debian-based Linux distribution aimed at advanced Penetration Testing and Security Auditing. Kali contains several hundred tools that are geared towards various information security tasks, such as Penetration Testing, Security Research, Computer Forensics, and Reverse Engineering.
       
  • PowerShell Empire (no longer maintained, but still good) 
    • Empire is a pure PowerShell post-exploitation agent built on cryptographically-secure communications and a flexible architecture.
       
  • PowerSploit
    • PowerSploit is a collection of Microsoft PowerShell modules that can be used to aid penetration testers during all phases of an assessment.
       
  • Unicorn Python Script 
    • A simple tool for using a PowerShell downgrade attack and then injecting shellcode straight into memory. There are many more tools to use, but these are a few that work well. You will have to experiment with these tools, but Video 1, below, demonstrates creating an obfuscated macro that can be used to create a typical malicious Word document for testing. It contains a PowerShell script that establishes a connection to a remote server using Unicorn script (a PowerShell Downgrade Attack) and Metasploit. A tool like this can help you test your security defenses and ensure you have the right controls and logging in place.

Video 1. Creating an obfuscated macro for testing.

Conclusion 

As you can see, the PowerShell tool can be used for both good and evil. When threat actors use these pre-installed tools, it is called “Living off the Land” since there is no need to install additional tools to achieve their malicious tasks. The key here to detecting and ultimately protecting your organization against these techniques is to first understand what normal PowerShell behavior in your environment looks like, and to then understand the signs of malicious behavior. This will allow you to test your environment for malicious technique coverage, so you can gain a better understanding of how strong your security posture is. 

Keep in mind that I have only touched on a few of the things you need to look out for, so make sure you keep up to date with all the latest malicious techniques ­– or better yet, make sure your vendor’s security controls are keeping up with the latest threats and are able to address the risk and identify malicious activities via techniques such as via EDRUEBA and SIEM. In closing, as you go through the process of testing each PowerShell attack technique, it is important to understand the technique, simulate the attack technique, monitor your security controls, evaluate if any gaps exist, and document and make improvements needed for coverage. 

Stay tuned for our next Mitre ATT&CK technique blog. 

Find out more about how FortiResponder Services enable organizations to achieve continuous monitoring as well as incident response and forensic investigation.

Learn more about FortiGuard Labs threat research and the FortiGuard Security Subscriptions and Services portfolioSign up for the weekly Threat Brief from FortiGuard Labs. 

Learn more about Fortinet’s free cybersecurity training initiative or about the Fortinet Network Security Expert programNetwork Security Academy program, and FortiVet program.