Latest research, product updates and best practices on staying secure in the cloud | Permiso

Strategies Used by Adversaries to Steal Application Access Tokens

Written by The Permiso Team | Aug 15, 2024 1:02:47 PM

Introduction

In today's complex landscape of modern cybersecurity, organizations and cyber-defenders must remain vigilant as adversaries continuously refine their tactics, techniques, and procedures (TTPs) to exploit vulnerabilities in applications hosted across multi-cloud environments. This blog post aims to shed light on a specific technique outlined in the MITRE ATT&CK framework: Steal Application Access Token.

Overview of the Technique

The MITRE ATT&CK Cloud Matrix for Enterprise includes a broad spectrum of tactics and techniques that adversaries use in cloud environments like IaaS, Google Workspaces, and Azure AD. As shown in the Cloud Matrix image below, the Steal Application Access Token technique is used by adversaries at the Credential Access tactic phase of an attack lifecycle. This technique involves adversaries stealing application access tokens, such as account API tokens, to gain unauthorized access to remote systems and resources in cloud-based, containerized applications, and software-as-a-service (SaaS) platforms.

It is worth noting that the MITRE ATT&CK framework is continually updated to reflect the evolving cybersecurity threat landscape. Organizations and cyber-defenders must check the latest version to ensure they are using the most up-to-date technique identifiers and descriptions when developing robust defense strategies for their companies or security solution products.

 

Real-world Applications

An Application Access Token is a type of security token used to authenticate a user, process, or device to an application. This means that the entity in possession of the token is granted access to resources without the need for a username and password at each request. However, adversaries employ several strategies and publicly available open-source tools to exploit these tokens. They specifically target account API tokens in cloud and containerized environments, using them to access data and perform actions with the permissions of these accounts. This can lead to privilege escalation and further compromise of the environment, all to achieve their malicious objectives.

According to the blog post by Microsoft Incident Response titled "Token tactics: How to prevent, detect, and respond to cloud token theft," the adoption of new work models, such as hybrid work environments or work from home, enables employees to use personal or unmanaged devices to access company data. This work model poses a higher security risk compared to the use of organization-managed devices. It was observed that adversaries often target these employees to compromise organizational resources by replaying (manipulating) tokens issued to employee identities that have already completed multi-factor authentication.

In Kubernetes environments, processes operating inside a container often communicate with the Kubernetes API server using service account tokens. If a container is compromised, an adversary may be able to steal the container’s token, gaining access to Kubernetes API commands. Similarly, in continuous development/continuous integration (CI/CD) pipelines, instances frequently use API tokens to authenticate to other services for testing and deployment purposes. If these pipelines are compromised, adversaries can steal these tokens and leverage their privileges for unauthorized actions.

OAuth is a widely-used framework that issues tokens, allowing users access to systems. It is particularly useful for applications requiring access to cloud-based services or protected APIs. OAuth 2.0 employs a variety of authorization protocols to facilitate this access. A commonly used protocol within this framework is the Microsoft's Authorization Code Grant flow. The OAuth 2.0 authorization code grant type, also known as the 'auth code flow,' enables a client application to obtain authorized access to protected resources, such as web APIs, without the need to handle user credentials directly. Instead, it uses an authorization server as an intermediary. This method enhances security by minimizing the exposure of user credentials and manipulation on tokens for authentication and authorization processes. On the other hand, adversaries can exploit these OAuth authorization token by creating a malicious application that is designed to gain access to resources using the target user's OAuth token, a method known as token theft through social engineering. To achieve this (Phishing with OAuth and o365/Azure), the adversary will first register their application with an authorization server; for example, using the Microsoft Identity Platform via options like the Azure Portal, the Visual Studio IDE, the command-line interface, PowerShell, or REST API calls. After registration, the adversary can then dispatch a spear-phishing link to the target user, enticing them to grant access to the malicious application. Once the OAuth access token is obtained, the application can potentially gain long-term access to features of the user account through an Application Access Token.

According to TechTarget blog post on “Stolen OAuth tokens lead to 'dozens' of breached GitHub repos” published 18th April 2022. GitHub disclosed that numerous organizations had their private repositories accessed due to a data breach involving stolen OAuth tokens. The breach was linked to tokens maintained by Heroku and Travis CI, but not directly stolen from GitHub as it does not store tokens in a format that could be immediately used. The security breach was first detected on April 12 when unauthorized access was noticed in GitHub's npm production infrastructure through a compromised AWS API key. This key was traced back to the stolen OAuth tokens used to access private npm repositories. GitHub has since revoked the implicated tokens, and Travis CI has reissued new keys and tokens for their customers. Travis CI also confirmed a breach of a private OAuth key from a Heroku service, although it clarified that this did not compromise any customer repositories or data. Heroku responded by revoking all compromised OAuth tokens and temporarily suspending new token issuance. Likewise, the BleepingComputer security blog provided a detailed statistical report on on the OAuth token breach.

In a blog post by CrowdStrike incident response team, it was observed that adversaries use the sts:GetFederationToken API call to create federated sessions from IAM users In AWS environments. Federated tokens which allow users to assume temporary credentials, can give users extensive permissions which can unintentionally open doors to security risks if not properly monitored. An adversary who compromises a user’s AWS API credentials will be able to use the sts:GetFederationToken API call to create a federated user session, which will have the same permissions as the original user but may persist even if the original user credentials are deactivated. These tokens allow adversaries to manipulate internal tokens and access specific application data and transaction management tokens within AWS-hosted applications.

The adversary can use the compromised federated user session to perform the following actions:

  • Perform all actions that the IAM user can perform
  • Log into the console, even if the IAM user has no password.
  • Reactivate the deactivated credentials, establishing persistence.
  • Create, modify or attach additional IAM policies to the base IAM user, potentially escalating their privileges to access sensitive data within applications hosted on AWS.

Adversaries Procedure Examples

  1. Use of AADInternals Tool to steal users’ access tokens

    Adversaries can use AADInternals to steal users' access tokens via phishing emails, which involves several steps that exploit common vulnerabilities in human and system security. These attacks typically begin with a phishing email containing a malicious link. When a user clicks on this link, they are redirected to a counterfeit website that mimics a legitimate login page, such as one for Microsoft. This fake page is designed to capture the user's credentials and any session or access tokens during the login attempt. Once the attacker obtains these tokens, they can access the victim's account and associated resources, potentially without the user's knowledge. The AADInternals tool is used to automates aspects of this process, enabling adversaries to easily exploit captured tokens and credentials.

    An Adversary can utilize the AADInternal Function listed on the website to retrieve or export, refresh, renew, store and manipulate access tokens from cache, SQLite database and Azure CLI.

    For example, an adversary can run the command below to retrieve Azure Active Directory (ADD) Graph access token and save it to cache. The token will be valid for an hour, after that, a new access token is fetched using the refresh token.



    Adversary Command Execution

# Prompt for credentials and retrieve & store access token to cache
Get-AADIntAccessTokenForAADGraph -SaveToCache

# Show the cached credentials
Get-AADIntCache

OUTPUT

Name                        : user@sampledomain.com
ClientId                     : a7c2b83f-abc5-4b49-b65a-16284ef69a04
Audience                 : https://graph.microsoft.com
Tenant                       : 77f1c1c4-e18b-41a7-b589-5d8ae4731718
IsExpired                   : False
HasRefreshToken  : True

Name                         : guest@sampledomain.com
ClientId                      : 5e490afc-2b45-41d6-8cc0-e005fd06551f
Audience                  : https://management.azure.com
Tenant                       : 77f1c1c4-e18b-41a7-b589-5d8ae4731718
IsExpired                   : True
HasRefreshToken  : False

Similarly, an adversary can execute the command below to get OAuth Access Token for a given client and resource.

# Get access token for MS Graph API for "Microsoft Office" client using interactive login
$at=Get-AADIntAccessToken -ClientId "b830a68f-3489-4a83-b291-cf3107b1a456" -Resource "https://graph.microsoft.com" 

# Get access token and refresh token for MS Graph API for "Microsoft Office" client using interactive login and save to cache
$at=Get-AADIntAccessToken -ClientId "b830a68f-3489-4a83-b291-cf3107b1a456" -Resource "https://graph.microsoft.com" 

OUTPUT

AccessToken saved to cache.

Tenant      : 2b2f77e4-ada3-4fcf-bf4c-2d91a3cf60e4
User           : user@company.com
Resource : https://graph.microsoft.com
Client        : b830a68f-3489-4a83-b291-cf3107b1a456

2. The APT28 strategy for token theft
The APT28 threat group has been active since at least 2004 and is attributed to a variety of aliases across different cybersecurity reports and intelligence agencies, including: IRON TWILIGHT, SNAKEMACKEREL, Swallowtail, Group 74, Sednit, Sofacy, Pawn Storm, Fancy Bear, STRONTIUM, Tsar Team, Threat Group-4127, TG-4127, Forest Blizzard, and FROZENLAKE. This threat group over the years utilized various types of cyber tools and strategies, including spear-phishing emails, malware, and information-stealing trojans to compromise their targets. It was reported in Trend Micro APT & Targeted Attacks blog post titled “Pawn Storm Abuses OAuth In Social Engineering Attacks” that this APT group abused OAuth to achieve their credential phishing schemes. They utilized several rogue applications to steal user OAuth access tokens including applications masquerading as "Google Defender" "Google Email Protection," and "Google Scanner" for Gmail users. They also targeted Yahoo users with applications masquerading as "Delivery Service" and "McAfee Email Protection.

3. The APT29 strategy for for token theft
The APT29 threat group has been operating since at least 2008 and is known for targeting government networks in Europe and NATO member countries, research institutes, and think tanks. This APT group is attributed to Russia's Foreign Intelligence Service (SVR) and a variety of aliases across different cybersecurity reports and intelligence agencies, including: IRON RITUAL, IRON HEMLOCK, NobleBaron, Dark Halo, StellarParticle, NOBELIUM, UNC2452, YTTRIUM, The Dukes, Cozy Bear, CozyDuke, SolarStorm, Blue Kitsune, UNC3524 and Midnight Blizzard. In a report by “SVR cyber actors adapt tactics for initial cloud access”, the NCSC (National Cyber Security Centre) and partners observed SVR actors using stolen cloud-based access tokens to access their victims’ accounts, without the need for passwords.

4. Use of Peirates Tool to steal users’ access tokens
Adversaries can use publicly available tool on GitHub called Peirates to gathers Kubernetes service account tokens using a variety of techniques. This tool is a post-exploitation Kubernetes exploitation framework with a focus on gathering service account tokens for lateral movement and privilege escalation.

An adversary can execute the command below to automates known techniques to steal and collect service account tokens, secrets, obtain further code execution, and gain control of the cluster. The techniques include enumerating secrets from etcd, exploiting insecurely configured RBAC permissions, intercepting tokens from insecure pod communication, extracting tokens from compromised containers, and scraping tokens from Kubernetes API server logs.

$kubectl attack --techniques all --output /tmp/attack_summary.txt

OUTPUT

[INFO] Starting kubectl attack: Comprehensive Kubernetes Exploitation
[INFO] Technique 1: Enumerating secrets from etcd...

[SUCCESS] Found 42 secrets in etcd, details stored in /tmp/etcd_secrets.txt

[INFO] Technique 2: Exploiting insecurely configured RBAC permissions...
[WARNING] Detected 5 roles with excessive permissions, detailed report at /tmp/rbac_issues.txt

[INFO] Technique 3: Intercepting tokens from insecure pod communication...
[FAILURE] No insecure communications detected. Ensure to test with more network traffic.

[INFO] Technique 4: Extracting tokens from compromised containers...
[SUCCESS] Extracted tokens from 3 containers, tokens stored in /tmp/compromised_tokens.txt

[INFO] Technique 5: Scraping tokens from Kubernetes API server logs...
[SUCCESS] Scraped 12 tokens from logs, see /tmp/api_server_tokens.txt for details

[INFO] Attack summary completed. Reports are stored under /tmp/ for review.

Kubernetes Attack Summary Report

Kubernetes Attack Summary Report
---------------------------------

Technique 1: Enumerating Secrets from etcd
-----------------------------------------
- Total Secrets Found: 42
- Critical Secrets: 15
- Output File: /tmp/etcd_secrets.txt
- Action Recommended: Review and restrict access to etcd, implement encryption at rest and in transit.

Technique 2: Exploiting Insecurely Configured RBAC Permissions
--------------------------------------------------------------
- Vulnerable Roles Found: 5
- High-Risk Permissions: Pod creation, Service manipulation
- Output File: /tmp/rbac_issues.txt
- Action Recommended: Apply principle of least privilege, regularly audit roles and permissions.

Technique 3: Intercepting Tokens from Insecure Pod Communication
----------------------------------------------------------------
- Insecure Communications Detected: None
- Attempted Intercepts: 37
- Action Recommended: Implement network policies, use encrypted communication channels.

Technique 4: Extracting Tokens from Compromised Containers
---------------------------------------------------------
- Tokens Extracted: 3
- Compromised Containers: web-app-1, api-gateway, db-service
- Output File: /tmp/compromised_tokens.txt
- Action Recommended: Harden container security, use read-only filesystems where possible.

Technique 5: Scraping Tokens from Kubernetes API Server Logs
-----------------------------------------------------------
- Tokens Found in Logs: 12
- Log Source: Kubernetes API Server
- Output File: /tmp/api_server_tokens.txt
- Action Recommended: Configure logging to exclude sensitive information, monitor logs for suspicious activity.

Summary
-------
This report outlines the vulnerabilities detected and the actions recommended to secure the Kubernetes environment. 
Review each technique's output and implement the suggested security measures to enhance cluster security.

 

Detection and Mitigation

Detection Strategies

Microsoft Incident Response in their blog post recommends that organizations and cyber-defenders should take a significant step toward reducing the risk of token theft by ensuring that they have full visibility of where and how their users are authenticating through enforcing location, device compliance, and session lifetime controls to all applications.

To further strengthen security posture and enhance the detection of potential unauthorized activities within Azure cloud environment, it is crucial for organizations and cyber-defenders to adopt the following detection strategies:

  • Monitor specific operations within Azure: they should focus on monitoring Microsoft 365 (M365) audit logs related to specific operations such as:
    • "Add app role assignment grant to user"
    • "Consent to application" (permissions and access grants within Microsoft Entra ID workloads - Formerly Azure Active Directory)
    • Monitor similar events generated in Entra ID (Azure AD) audit logs.
  • Use the Azure KQL (Kusto Query Language) command below to detect potential unauthorized or stolen access token activities within Microsoft 365 data source and Azure Active Directory.

source == "*Azure:m365" 
and workload == "AzureActiveDirectory" 
and (operation == "Add app role assignment grant to user" or operation == "Consent to application")

 

  • Organizations and cyber-defenders should consider adopting a Cloud Access Security Broker (CASB) security product for the following purpose:
    • To monitor and automatically trigger alerts based on specific policy criteria such as "High severity app permissions”. Simply for apps requesting high-risk permissions.
    • To actively search for potentially malicious apps such as filtering apps with few authorizations from users, identifying apps requesting permissions that do not align with their stated purpose and noting apps that have not been reauthorized recently ("Last authorized" fields). However, it is important to note that some activities might be incorrectly logged as user actions.
    • Investigate specific apps by examining the application activity logs, which details the actions performed by the apps. Similarly, Use App stores such as Google play store, Microsoft store and Apple App store for further investigation of suspicious apps.
  • Ultimately, organizations and cyber-defenders should enable various activity logs for their applications and use audit tools to monitor actions enabled by OAuth 2.0 access. These tools can help identify actions that suggest privilege escalation, such as the creation of roles or modification of policies, which could occur after an adversary gains initial access.

To counteract potential threats involving the sts:GetFederationToken API call, which enables adversaries to create federated sessions within the AWS cloud environment, organizations and cyber-defenders should effectively monitor and alert on users invoking the GetFederationToken API call. This can be tracked through CloudTrail with criteria such as eventName='GetFederationToken' and eventSource='sts.amazonaws.com'. Similarly, if federated sessions are not widely used in the AWS account or organization, cyber-defenders should be vigilant for event names related to userIdentity.type='FederatedUser', which may reveal indicators of compromise.

 

Mitigation Strategies

To effectively mitigate adversaries TTPs in Stealing or manipulation Application Access Token, organizations and cyber-defenders should adopt the following mitigation strategies:

  1. Audit

    • Audit all cloud and container accounts to verify their necessity and to ensure that the permissions assigned are appropriate.
    • Perform thorough audits on all OAuth applications regarding the permissions they have to access organizational data.
    • Initial extensive audits should be conducted on all applications to establish a security baseline. This should be followed by regular audits of any new or updated applications to continually assess and adjust security measures.
    • Applications that appear suspicious during audits should be investigated further. If found to be a risk, they should be removed to protect organizational data and integrity.
  2. Restrict Web-Based Content

    • Disable or block end-user consent such that users can not authorize third-party apps through OAuth 2.0. This will enable all application authorization requests to go through administrative approval.
    • Prevent users from registering new applications themselves. This will reduce the risk of unauthorized or risky applications being added.
    • Use Cloud Access Security Broker (CASB) to ban or restrict applications deemed unsafe or unnecessary, enhancing security and compliance.
    • For Azure Application Management:
      • Disable or turn off the "Users can register applications” feature to prevent users from registering new applications.
      • Disable or turn off the “Users can consent to apps accessing company data on their behalf" feature to block users from consenting to third-party multi-tenant applications accessing organizational data.
    • For AWS Application Management:
      • Uses the Six (6) IAM policies and permission provided by AWS to define what actions users, groups, or roles can or cannot perform to your applications.
      • Ensure proper IAM role management for applications that assume roles granting them permissions. Proper management ensures that roles can only be assumed by specified entities, and under defined conditions, using trust policies and permissions policies associated with those roles.
      • Use IAM policy condition keys to refine the permissions granted or denied to applications. For example, restrict application registration capabilities based on the requester's IP address, user agent, or time of day.
      • Use Service Control Policies (SCPs) to manage permissions for all accounts under the organization. For example, SCPs can prevent any account user from enabling certain application services or making high-risk API calls.
    • For GCP Application Management:
      • Use GCP granular IAM policies and custom IAM roles to determine what operations the role holder can perform on applications.
      • Disable specific Google services for a project or the entire organization, preventing users from using these services to register or manage applications.
      • Use GCP resource location restriction policy to controls where applications can be deployed and registered.
      • Use GCP OAuth consent screen configuration to manage how users grant permissions to apps. This includes setting up the scope of permissions an app can request and whether a verification process is needed before an app can be authorized by users
  3. User Account Management

    • Implement RBAC to ensure that users account have only the minimum necessary privileges. This reduces the risk of excessive permissions that could be exploited.
    • Use of Cloud Access Security Broker (CASB) to to establish and enforce usage policies and manage user permissions on cloud applications. This helps to prevent unauthorized access to application access tokens.
    • In Kubernetes applications, set automountServiceAccountToken: false in the YAML specifications for pods that do not require access to service account tokens. This setting prevents automatic mounting of tokens and enhance security by reducing potential exposure.
  4. User Training

    • Users should be educated about not authorizing third-party applications that they do not recognize to prevent potential security breaches.
    • Educate users to be vigilant about the redirect URLs during the authorization process. A misspelled or strangely worded URL that tries to mimic a legitimate service suggests that the site may be attempting to spoof a real service.
    • Educated users to be cautious about the permissions they grant to applications. Specific permissions to SaaS applications, such as offline access or access to read emails, should raise higher suspicions because adversaries can exploit SaaS APIs to access and potentially exfiltrate credentials and other sensitive information.

To mitigate the risk of adversaries abusing the sts:GetFederationToken API call to create federated sessions in AWS environment, AWS recommends the use of service control policies (SCPs) or explicit deny-all IAM policy as shown below to users based on IdP user name or revoke session token. The SCP policy will deny the users John Doe and Mary Major from accessing AWS, in member accounts, regardless of their session duration, because each action will check against their aws:userid and aws:SourceIdentity values and be denied accordingly.

SCP to deny access based on IdP user name

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Deny",
            "Action": "*",
            "Resource": "*",
            "Condition": {
                "StringLike": {
                    "aws:userid": [
                        "*:JohnDoe@example.com",
                        "*:MaryMajor@example.com"
                ]
            }
        }
    },
    {
            "Effect": "Deny",
            "Action": "*",
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "aws:SourceIdentity": [
                        "JohnDoe@example.com",
                        "MaryMajor@example.com"
                    ]
                }
            }
        }
    ]
}

For further reading, check out AWS detailed blog post on revoking role session tokens generated via an external identity provider that can be referenced for additional mitigation strategies.

Useful Resources

Preparing for the Future

In February 2023, Obsidian reported a notable attack trend where adversaries stole Application Access Tokens. During this incident, an attacker managed to install malware on a CircleCI employee's laptop, which went undetected by antivirus software. This malware enabled the theft of the employee's session tokens, which were secured with MFA. The compromised employee had privileged access, allowing the attacker to impersonate them remotely and escalate access to a subset of CircleCI's production systems, including access to stored GitHub tokens for customer environments. Coincidentally, on the same day, Slack reported a security breach involving one of its vendors. This breach led to the compromise of a Slack employee’s GitHub token and access to a private repository. It has not been confirmed whether this attack is related to the CircleCI incident.

Organizations and cyber-defenders can stay ahead of adversaries’ techniques to Steal Application Access Tokens by implementing robust security measures, continually monitoring their environment, and staying informed about the latest threat intelligence. Here are several strategies that can help prevent the theft and misuse of application access tokens:

  • Implement multi-factor authentication (MFA) for all users, especially those with access to sensitive systems and data.
  • Implement secure mechanisms for token generation, distribution, and revocation to manage the lifecycle of tokens effectively.
  • Conduct regular security audits of systems that issue and manage access tokens to ensure they adhere to security best practices.
  • Use short-lived tokens wherever possible and implement automatic expiration to reduce the window of opportunity for misuse.
  • Apply the principle of least privilege across all systems and services to ensure that users and applications have only the access necessary to perform their functions.
  • Employ security solutions like Web Application Firewalls (WAFs), Cloud Access Security Brokers (CASBs), and Endpoint Detection and Response (EDR) systems to provide additional layers of security.
  • Conduct regular security awareness training for all employees to educate them about the latest phishing tactics and other social engineering techniques used to steal credentials and tokens.
  • Keep up-to-date with the latest security research, threat intelligence, and advisories related to OAuth and token security to anticipate and mitigate emerging threats.

Conclusion

In this blog post, we discuss how adversaries can adopt the Steal Application Access Token technique to manipulate application account API tokens in cloud and containerized environments. This can lead to privilege escalation and further compromise of the environment, all aimed at achieving their malicious objectives.

Arvind Sakthivel, Global Practice Head IDAM at LTI - Larsen & Toubro Infotech, provides valuable insights into countering access token theft in his LinkedIn article titled “Access Token Breach? What Next...”. It is crucial for organizations and cyber-defenders to not only familiarize themselves with these best practices for managing access tokens as, discussed in this write-up, but also to actively implement them.

Furthermore, maintaining robust visibility and management of cloud applications, alongside adopting the comprehensive detection and mitigation strategies discussed in this blog, are essential steps for security teams aiming to safeguard their digital assets. We encourage security teams and leaders to continuously update their security measures in response to evolving threats and to stay engaged with the latest in cybersecurity defense tactics using frameworks like MITRE ATT&CK.

Reference Resources