By Netanel Golani, Threat Hunting Expert at Team Axon
Introduction
The rise of ransomware in recent years continues to pose an increasing threat, especially as more businesses and individuals entrust their data to cloud storage services.
Attacks have been seen in many cloud providers’ storage systems such as in Microsoft OneDrive and S3 buckets in AWS, and can be motivated by a variety of goals like financial gain, disruption and sabotage, or political or ideological motives.
Specifically in OneDrive environments, hunting for ransomware attacks is slightly different than in other architectures. According to our analysis, threat actors need to perform their malicious encryption of the files’ content from outside the OneDrive application. Fortunately, this constraint actually helps threat hunters narrow the scope of monitored activities when hunting for ransomware execution.
Nevertheless, during research conducted by Team Axon, we have encountered incidents where machines have been compromised and attackers encrypted files within OneDrive. In this paper, we will cover how ransomware can be carried out in OneDrive environments with a given initial access. We will show what it will look like from the threat actors’ point of view, and what can be done to detect and prevent it from happening in your environment.
What's included:
- Initial Access to OneDrive
- Taking a Walk in the Adversary's Shoes
- Threat Hunting for Ransomware
- Prevention
Initial Access to OneDrive
The main purpose of this article is not to be a guide for maliciously accessing OneDrive, however, it is important to fully understand the main vectors that enable access to OneDrive.
The first step that an attacker would take would be to attempt to gain access to the Microsoft 365 environment. Initial access can be obtained from existing resources such as users and registered applications in Entra (formerly Azure AD).
Existing User
To access any folder on OneDrive, an access token must be in hand. An access token is a key that is generated for a registered entity in Entra (such as a user or an application) when it needs to access certain resources or perform actions on them.
By targeting an existing user, threat actors may generate an access token via credential theft, or by directly stealing a previously generated access token.
If credentials are stolen, a threat actor can get authorized to create an access token. OneDrive would then recognize this access token as valid, meaning the threat actor would have access to the user’s OneDrive folders and may also (with specific sharing permissions) have access to organizational OneDrive folders.
Some threat actors may choose to steal an access token directly from compromised devices (PC, phone, tablet, etc) that already store a valid access token within Microsoft 365 applications. For example, until recently, an access token could be extracted from the OneDrive application's local logs in a compromised machine.
It was also discovered that the access token can be extracted from the local Microsoft 365 registered processes dump (e.g winword.exe, onenote.exe, powerpnt.exe, outlook.exe, excel.exe, OneDrive.exe) by looking for regex matching patterns of JWT strings.
Registered Application
An application can be permitted to access OneDrive resources either through direct permission after obtaining administrator consent (Application Permission), or by an existing user (Delegated Permission) after obtaining explicit consent from the user.
Every registered application in Azure Active Directory is represented by a Service Principal. Similarly to the idea of having service accounts, the Service Principal is the registered entity that can be granted permission to access resources and perform actions on behalf of the registered application or a user. Specifically, the least required permissions to read, write or delete (which are eventually required to execute a ransomware attack) will be Files.ReadWrite.All.
Example of an over-permissive application with Files.ReadWrite.All permissions.
Threat actors have found multiple ways to maliciously obtain secrets or certificates of a registered application. One example is finding them plaintext in insecure CI\CD pipelines and code bases in development environments.
The 'Client secrets" tab in Microsoft Azure allows adding certificates and secrets to the Service Principal that is addressed to the application.
By authenticating as a Service Principal (via certificates or secrets), an access token can easily be generated and used to access resources available to the application.
Overall, in both vectors, the common practice by threat actors is extracting an access token and using it while performing malicious actions.
An access token is typically used by Microsoft Graph API. The Microsoft Graph API is a unified API endpoint that allows developers to access a wide range of Microsoft 365 services, including OneDrive.
A simple Python code for generating an access token using a secret key of a registered application using Microsoft Graph API that lists files in the user's personal drive.
Taking a Walk in the Adversary’s Shoes
Attack Outline
Ransomware in a cloud environment can appear in many ways, but the main goal remains the encryption of files. As mentioned previously, threat actors must utilize external services to encrypt the files’ content.
Even though it is technically possible to encrypt the content of a file using the creation of Flows in Power Automate, the creation of such flow requires reading the files’ content for encrypting it outside of OneDrive.
This limitation greatly impacts how the threat actors shape their execution flow, and from a threat hunter standpoint, narrows down the scope of activities to look for.
Ransomware attacks in OneDrive can occur in per file in the following order:
- Downloading the file from OneDrive to threat-actor-controlled storage (threat actor’s C2 server, online storage service, or the threat actor's machine itself). This can be operated from a web interface such as SharePoint, from a synced desktop with a OneDrive client agent, from third party application access, or other methods involving Microsoft Graph API.
- Encrypting the content of the file (threat actor’s C2 server, online storage service with encryption capabilities, or the threat actor's machine itself). It is also possible to encrypt the content of a file using the creation of Flows in Power Automate.
- Modifying the original file with the encrypted content, or uploading a new file with the encrypted content and deleting the original file.
A threat actor can also decide to deploy ransomware by just collecting the files and permanently deleting them from OneDrive. However, in large OneDrive environments, it will require the threat actor to have enough storage resources to store all the stolen files until the ransom is (or is not) paid. Due to the low probability of such an approach, we will explore scenarios where the threat actor downloads, encrypts and modifies the files.
Disarming Recovery Methods
For the threat actor to have the upper hand, they must execute the above steps while also disrupting every recovery method available to the targeted environment. This causes the files to become unrecoverable, and the victims cannot undo these actions.
Let’s break down how a threat actor can potentially achieve this so we as threat hunters can build accurate detections upon the generated logs.
OneDrive’s File Versioning feature can keep a very high number of previous versions of each file, even if those files are deleted and restored later from the OneDrive Recycle Bin, and there is no direct way of modifying the version history of a file. This is important because it means the attacker cannot tamper with previous versions of files for recovery-disarming purposes.
However, threat actors may still find indirect workarounds to bypass this limitation. To keep users from restoring their files from encryption, threat actors would typically perform a permanent delete of any original version of the files. There are two methods for permanent deletion:
- Delete from second-stage Recycle Bin: OneDrive has two stages of recycling bins. After recycling a file for the first time, it goes to the first-stage recycle bin. After deleting a file from this bin, it moves to the second-stage Recycle Bin. Only after deleting the file from the second-stage bin, the file will be permanently deleted, along with its version history.
- PermanentDelete via Graph API: Microsoft Graph is a RESTful web API that enables accessing Microsoft Cloud service resources. One of the offered API functions is for permanently deleting a file (PermanentDelete) along with its version history.
By using one of these methods, a threat actor may potentially prevent the targeted organization from being able to recover its encrypted data.
Once the previous versions of files are not recoverable, the threat actor may then plan how to encrypt the files’ content.
As previously mentioned, OneDrive does not have encryption capabilities, so the threat actor must get their hands on the files’ actual content in order to be able to encrypt them.
They may choose one of two options to ‘safely’ modify the content of the files:
Option 1:
1. Delete the original file either by PermanentDelete or double-recycling
2. Upload the encrypted file with the encrypted content
Option 2:
1. Modify the original file by replacing its content with the encrypted content
2. Duplicate it to the same directory so that the new file won’t have a version history
3. Delete the original file either by PermanentDelete, or double-recycling
Before ransomware execution
After ransomware execution
Ransomware Execution Options
Now that we understand the constraints and basic operations that OneDrive offers, we have the tools to understand how threat actors can ultimately build the ransomware attack flow.
One more decision the threat actor needs to make is should the ransomware attack be executed with controlled execution stages, or should it be autonomous and immediate.
Here’s a breakdown of the two approaches:
- Immediate execution - The attacker executes an automated and scripted attack that iterates over all the accessible files and immediately completes the encryption process.
- Staged execution - The attacker executes the ransomware in two stages: first, clone all the files into the attacker's storage, and then uploads the encrypted content, either on-demand or with a built-in delay mechanism.
At first glance, the immediate execution sounds more attractive to a threat actor, but there are trade-offs for both. Here is a breakdown of each approach:
Ultimately, threat actors may combine these two approaches into one, as they can selectively pick files for ransom assessment (e.g. by keywords or file extensions) and tune their ransom demands and targeted folders accordingly.
A combined approach will eventually end up in the form of an immediate execution.
In order to help OneDrive users improve their organizations’ readiness to detect related logs generated as part of the ransomware execution, team Axon has created a new proof-of-concept tool to simulate the execution of ransomware in OneDrive.
The tool is called OneDriveRansomwareSimulator and is available in Axon’s Github account here.
Threat Hunting for Ransomware
Now that we have a better understanding of the mindset of a threat actor, we can create a strategy for hunting the threat within our environment.
As threat hunters, we must remember a guiding principle - we should not necessarily look for the easiest or most automated way to hunt but for the most in-depth way. It doesn’t matter if the process is messy - we must be able to determine with certainty whether or not a threat has occurred.
With that said, we need to start our hunt by setting clear assumptions so we can make sure to scope the threat accurately. This includes acknowledging what is not included in our hunt (e.g., we won’t hunt down the initial access), and building baselines to help reduce false positives.
Hunting Thesis Assumptions
- Encryption/Exfiltration is best performed by threat actors when it is automated (especially when it targets large environments). Therefore, we expect to see a pattern (a single log or a combination of logs) that can be found throughout all involved files in the attack.
- The actual encryption of the files is done outside of the Microsoft 365 environment due to the lack of built-in file encryption capabilities in OneDrive.
- The source of the intrusion into OneDrive doesn’t matter to us in our hunting scope. All initial access vectors are valid, and whether the attack is sourced from a user, a service account, or an application, our hunting strategy remains the same. Initial access to the environment can (and should) be hunted for in another threat-hunting campaign.
Evaluating Time Thresholds
One important way to prevent a false positive during this hunt is to distinguish between “grouped” activities that were initiated legitimately by a user, and activities initiated by an automated tool (e.g., select all files, folders, and sub-folders recursively and delete them).
Because of this, we need to tune our search to find only “non-human” actions.
We want to look for sets of activities conducted against multiple files at the same time because ransomware is typically performed over large groups of files in a short time frame. Because of this, hunting for OneDrive ransomware attacks by looking for single file encryption using Microsoft 365 Audit logs is not as effective.
To improve the possibility of catching an automated ransomware attack that corresponds to our thesis, we must inspect the logs through two lenses:
- Activities made over a single file
- Activities made over multiple files
Looking at both helps us better form a baseline for our thresholds when it comes to different execution forms, such as the ones we discussed earlier (immediate vs staged execution), as well as address each scope differently.
To do that, we used our OneDriveRansomware simulation tool to gather accurate metrics to support our hunt.
Based on the results from the executed simulation in a lab environment over an average-size dataset of XLSX, PDF, PPTX, and TXT files, and using Graph API by Microsoft and a decent internet connection, here are time estimations for the execution of each attack.
Action | Mean Execution Time |
Target file content retrieval | ± 0.5 Seconds |
Python encryption of content | ± 0.03 Seconds |
Deletion of the target file | ± 0.5 Seconds |
Upload\modification of an encrypted file | ± 2.5 Seconds |
Total Execution Time | ± 3.53 Seconds |
Using these results, we can calculate the number of files that can be handled by an automated ransomware tool:
- An immediate ransomware execution - 16 files per minute
- A staged ransomware execution will allow the handling per stage:
- Content retrieval stage - 120 files per minute
- Content modification stage - 20 files per minute
Ultimately, the numbers in the table can be used as a benchmark when it comes to the threshold of our hunt and avoiding multiple false positives.
Building the Queries
Finally, we can now create our detection rules for each execution form:
- Hunting for immediate ransomware execution: Look for modification (encryption) patterns such as content retrieval, target file deletion, and modification/upload that happen to multiple files in succession with the following conditions:
- A single file encryption process should take up to 3.5 seconds
- The entire encryption process is done to at least 16 files over 60 seconds
- Hunting for staged ransomware execution: The stages will have up to a week time difference between them (one week is the likely maximum time difference between stages).
- First stage - Look for content retrieval patterns within up to 0.5 seconds per file and occurring on at least 120 files over 60 seconds
- Second stage - Look for one of two patterns within up to 3 seconds per file and occurring on at least 20 files over 60 seconds:
- Mass modification of existing files
- Mass deletion and upload of files
- Due to the possibility of file order inconsistency between matched grouped files stages (for example, files were retrieved in alphabetic order, but encrypted in a reversed alphabetic order), we will tune the rule a bit more by extending the time-range to 5 minutes (instead of 1 minute), increase the thresholds accordingly, and require a match of at least 75% between the files in the first stage and the second stage.
Note: Neither the number of files per minute nor the time encryption runtime per file are constants. These numbers may vary depending on the nature of the environment, the threat actor’s infrastructure, and other considerations that are related to the hunting framework we are working on.
Hunting Query
The following link contains threat-hunting queries for both forms of ransomware execution as discussed (Immediate + Staged execution): https://github.com/axon-git/threat-hunting/tree/main/OneDrive%20Ransomware
Nice-to-Haves
In addition to the obvious action of encrypting files in the file system, other visible artifacts are expected to be seen once a ransomware attack occurs. Knowing them may help us determine whether it is a real attack taking place or if it is just mass modification activities that are taking place by an innocent user.
Ransom note
Threat actors will leave a plaintext note to the users with an unfortunate notice of a ransom, instructions on the ransom payment methods, and deadlines. This is the clearest evidence for detecting a ransom that took place.
However, in terms of detection, the content of target files is not visible in Microsoft audit logs, and the file name may not be indicative enough. Moreover, there is no guarantee that a threat actor would leave such a note in OneDrive itself, but may find it more appropriate to send the note over other channels.
File Extension
In some cases, the attacker may change the extension of the files. The purpose of this behavior can be to set a clear and intimidating appearance of the impact. Nevertheless, this behavior is not mandatory for the encryption process.
Scrambled\encrypted file names
In case of downloading a file and deleting it right after, a new file is expected to be uploaded. However, since there is no guarantee of having similar names, newly encrypted files can have randomized strings as names, which the attacker can resolve to the original name in case of decryption. In terms of detection, it’s best not to rely much on the newly uploaded file name for correlation.
All of these signatures can help in a ‘visual’ assessment of cases where ransomware is suspected of taking place, but will probably not be enough to generate automated signals within a SIEM product.
Investigating a True Positive
Once a suspicion is raised using the above detection methodology, it is important to respond with two tasks in parallel:
- Track the source of the activities
- “Manually” confirm the encryption of the files
The following questions will help in scoping the suspicion and creating an accurate response:
- Track the source of the activities
- Who is the registered user who executed the suspicious activities?
- Were the activities made by the user itself or by an application on her behalf?
- What interface was in use during the activities? Such information can be obtained by retrieving the user agent and application ID.
- What other activities were completed by the user / on behalf of the user in the same session? These activities can be tracked using session ID (if it exists) or by scoping the relevant activities in an estimated time frame.
- “Manually” confirm the encryption of the volumes
- Do all file names have the same extension added to them, suggesting an encryption occurred? (e.g. revenues23.docx.enc)
- Do applications crash/fail to load file content from the encrypted volumes? A quick check can be done by trying to open files of formats like PNG, PDF, CSV, DOCX, etc.
- Were there any ‘ransom notes’ left by the suspected threat actor?
Ransomware is one of the most impactful cyber attacks today. Once a ransomware attack occurs, it is important to respond according to organizational security playbooks and regulatory requirements.
Such actions usually include:
- Informing relevant security personnel, including the organization's Incident Response team
- Informing regulators and law enforcement authorities
- Technical data collection and restoration instructions
Suggested playbooks can be found in Microsoft documentation:
Ransomware general response playbook:
https://learn.microsoft.com/en-us/microsoft-365/security/defender/playbook-responding-ransomware-m365-defender?view=o365-worldwide
OneDrive data restoration:
https://support.microsoft.com/en-gb/office/restore-deleted-files-or-folders-in-onedrive-949ada80-0026-4db3-a953-c99083e6a84f
Prevention
Like most attacks in cloud-based infrastructures, prevention usually comes down to Identity and Access Management (IAM), which includes securing users, groups, roles, applications, integrations and other managed resources.
Multiple attack vectors can end up granting unauthorized third-party access. Therefore, its highly recommended to examine a wide range of hygiene aspects to prevent such attacks from happening.
Here are some of the most impactful measures that can be taken to help mitigate the threat:
User Access
- Make sure users are MFA-enrolled and enforce strong passwords.
- Restrict user permissions and access rights to only what is necessary. Limit write access and restrict sensitive folders to authorized users only.
Registered Applications
- Make sure that all certificates and secrets (allowing sign-ins as a service principal of a registered application) are safely stored in secret managers and not placed in plaintext raw code bases and external-facing services that are prone to compromise.
- Validate that the existing permissions granted to applications (via the API Permissions tab) are adequately aligned with their needs, and that all are essential.
DLP And Retention Policies
- Secure folders and files in OneDrive with appropriate DLP and Retention Policies to make sure files can be restored. In some cases, OneDrive may fail to restore the files but it is still best to use this practice to have some way to restore your data.
Summary
The shift towards targeting cloud-based platforms not only underscores the adaptability and sophistication of cybercriminals but also raises serious concerns about the security of the data we store in the cloud, making it imperative for both individuals and organizations to remain vigilant and proactive in defending their digital assets.
In this blog post, we have explored attack flows of ransomware in OneDrive and threat-hunting practices. Ensuring your organization is protected against this evergrowing attack is extremely important in mitigating the risks posed by threats to your cloud environment.
We hope that you are able to use the OneDriveRansomwareSimulator to help protect your organization and that you have found this blog post informative and useful.
Keep your Microsoft 365 close, and OneDrive even closer.
Important: The OneDriveRansomwareSimulator tool was created as a proof-of-concept tool to increase awareness around ransomware attacks in Microsoft-based cloud environments, specifically in the OneDrive application. It is designed to help improve organizations’ readiness to detect related logs that are generated as part of the ransomware execution. This tool should be used solely for authorized security research purposes. The tool is provided “as is” and Hunters disclaims any and all warranties and liabilities regarding the use/misuse of this tool. Use it responsibly!
To stay updated on threat hunting research, activities, and queries, follow Team Axon’s Twitter account (@team__axon).
HUNTERS © 2024 All rights reserved
The Hunters and Axon Team trademarks, service marks and logos used herein are owned by Cyber Hunters Ltd. All other trademarks used herein are the property of their respective owners.ז