banner

Cloud Red-Teaming

Last updated 

Photo Credits: CyberDB

Notes on the Cloud Assessment / Cloud Red-Teaming process. By no means comprehensive. An amalgamation of courses, presentations, and white papers I have recently attended and/or reviewed.

I: Intro Material

I.A: Test Types

  • Cloud assessments are similar to on-prem tests in start points and goals; they differ only in the specifics.
    • Attack Surface Discovery: Identify and enumerate exposed systems. Often a 'zero-knowledge' starting point. Typically starts with a domain name.
    • Perimeter Breach Attempt: Identify and enumerate exposed systems and try to breach the perimeter through them.
    • Assumed Breach: Start off with full or partial access to some portion of the client's environment. In the cloud context, this could be access to a resource (VM or container) in the cloud, or it could be an API key or set of cloud console credentials.
  • These notes will attempt to document a "full scope" test: from discovery, through perimeter breach, to post-exploitation

I.B: Methodology

  1. Attack Surface Discovery - domain enumeration and identification of the target's publicly accessible resources, whether SaaS tenants, IaaS, on-prem, etc.
  2. Enumeration - Identify vulnerabilities & opportunities for breaches. Can be traditional vulnerabilites or simply systems (e.g. AAD) that may offer a path forward
    • Scanning & Mapping - Where possible, leverage service APIs (e.g. AWS/GCP/Azure APIs) to do the gathering.
  3. Exploitation & Escalation - Gain initial and/or privileged access
  4. Elevated Reconnaissance - With any access gained, repeat reconnaissance; New privileges may provide access to previously invisible resources
  5. Pivots & Persistence - Conceptually, no change from on-prem testing. Many cloud-specific TTPs, though, to include exploitation of CI/CD tools and workflows.
    • Steps 3-5 are highly-related and often cyclical.
  6. Lessons Learned

I.C: Cloud Assessment Scope

  • Generally speaking, vulnerabilities in the platform itself are out of scope when conducting a test for a client - after all, they couldn't do anything about it.
  • Important to review cloud platform TOS:
    • AWS - demarcates based on service
    • Azure PenTesting and ROE. Used to require testers to fill out a form.
    • GCP. More vague than other platforms.
  • Note: Pretty much everyone prohibits DOS testing.

I.D: Cloud Platform Info

I.D.a: AWS

I.D.a.i: IAM
  • AAA System: AWS IAM
  • Note: AWS SSO is now AWS IAM Identity Center
  • Authorization is based on Policies, Identities/Principals, and Resources
    • Identities/Principals can be:
      • IAM users - identity 'lives' in AWS. long-term credentials
      • Federated users / IAM Identity Center users - identity 'lives' externally. given temporary credentials to access AWS resources. Preferred/suggested.
    • Policies
      • can be assigned to identities (user, group, role) or resources (e.g. S3 - BUT not every service supports this)
        • Identity-based policies can be:
          • managed - policy exists independently of any identity and can be assigned
          • inline - added directly to a users, group, or role. deleted when the identity is deleted. much harder to manage/control. not recommended.
        • All resource policies are inline
      • policies are subject to IAM Permission Boundaries, which "set the maximum permissions that an identity-based policy can grant to an IAM entity"
      • policies can be versioned
      • Service Control Policies (SCPs) are available at the AWS Organizations level to centrally control the maximum available permissions for all accounts in the organization. Like an account-level permissions boundary
      • session policies - can be specified when creating a temporary session for a role or federated user. Cannot exceed the identity-based policies for the role/user
    • Access Control Lists - pre-date resource policies. deprecated, but still supported by some services (S3)
    • resources/services generally require the appropriate IAM permissions to access other resources/services, just as if they were a typical identity
  • IAM supports RBAC and ABAC - policies can specify a "tag" instead of a user, group, or role
  • Amazon Resource Names (ARNs): used to specify all resources
    • format: `arn:partition:service:region:account-id:[resource-id|resource-type/resource-id]
  • accounts can have console access, programmatic access, or both. No service accounts, though resources can be given an IAM role. Native auth does not use OIDC, but can be federated with OIDC providers
  • built-in / "native" auth supports temporary (prefix: "ASIA") and permanent (prefix: "AKIA") access keys. Prefix: "ABIA" - STS Service Bearer Token.
  • Web Console Endpoints:
    • Root Accounts: https: //console.aws.amazon.com
    • Non-Root Accounts: https: //[account_id_or_alias].signin.aws.amazon.com/console/
    • Federated Login: https: //[account_id_of_alias].awsapps.com
      • Also supported by Amazon SSO and Workspaces
    • Note: The account ID is moderately sensitive data, capture it if possible
I.D.a.ii: AWS CLI
  • the aws cli command is a wrapper around a set of Python3 tools; it is most often installed with pip
  • auth - typically uses keys. Keys are stored in ~/.aws/credentials, profile config is stored in ~/.aws/config. Profiles can be named to allow running commands with specified credentials
    • alternatively, aws can authenticate via AWS SSO (device code flow or STS ephemeral keys)
  • example commands
    • aws help
    • aws [submodule, like s3] help
    • aws s3 ls [--profile credential_profile_name]
    • aws s3 cp s3://bucket/file /dest/file
    • aws ec2 list-instances
    • aws ec2 describe-instances
    • aws ec2 run-instances --image-id [id] --subnet-id [id] --security-group-ids [sg] --key-name [ssh key]
    • supported by most commands: --output [json|text|table]
  • both aws and az support JMESPath queries. e.g. [?storageProfile.osDisk.osType=='Linux'].{Name:name,admin:osProfile.adminUsername}
    • better option: return everything from tool, filter on client-end with jq
I.D.a.iii: Compute Services
  • Sidenote: AWS used to use Xen for virtualization, but their new proprietary solution, "Nitro," is based on KVM
  • EC2 - generic IaaS VMs, can be used with VPCs/anything else. Most other compute (e.g. EBS, ECS) uses EC2 in the background.
  • Lightsail - comparable to DigitalOcean/VPS alternatives. No VPCs, just a simple server environment.
  • Elastic Beanstalk - EC2+S3 combo for app deployments. Does some load balancing, auto-scaling, and health monitoring for you.
  • EKS - AWS k8s. There's also ECS, but use case seems unusual

I.D.b: Azure

I.D.b.i: Azure Access & Account Types
  • accounts have both programmatic and console access. Service accounts can have static passwords or certificate-based auth. Native auth uses OIDC.
  • all AuthN to the Azure platform goes through AAD
  • authorization, however, leverages "Azure RBAC"
  • CLI tool offers multiple OAuth2 flows
    • authorization code flow, device-code flow, service principal auth
    • tokens stored as JWTs in .azure/msal_token_cache.json
  • mgmt tools: CLI (az), PowerShell modules, web portal, web portal Cloud Shell
  • equivalent to ARN: RESTful API paths: /subscriptions/[id]/resourceGroups/[group]/providers/[service]/[resource-type]/[resource]
I.D.b.ii: Azure CLI
  • az command. setup with az configure
  • setup auth with...
    • az login - uses authentication code flow
    • az login --use-device-code - guess which flow this uses
    • az login --identity [--username [resource_id]] - login with Managed Service Identity (say, from a VM)
    • annnd, finally: az login -u [username] -p [password]
    • setup a service principal:
      • az ad sp create-for-rbac --name [name] --create-cert
      • az login --service-principal -u http://[name] -p [cert.pem] --tenant [tenant ID]
  • example commands: az vm list -o table
  • both aws and az support JMESPath queries. e.g. [?storageProfile.osDisk.osType=='Linux'].{Name:name,admin:osProfile.adminUsername}
I.D.b.iii: Microsoft Graph
  • historically, the various microsoft services (exchange, onenote, o365, etc.) have all had different APIs. Microsoft Graph is the org's new "universal API" for:
    • all O365 services
    • some Windows 10 / device management functionality
    • AAD
    • Enterprise Mobility + Security functionality
    • full list here
  • all (or at least, most) of the Graph API is available as a Postman collection
  • Note: based on personal experience, Microsoft Graph is very far from achieving its goal as a "universal API" for all things Microsoft
I.D.b.iv: Misc
  • the many Microsoft identity systems: AD, ADFS, AAD, AAD DS
  • AD vs AAD:
AttributeADAAD
Communication ProtocolLDAP/KerberosHTTPS
Auth ProtocolKerberos/NTLMOAuth, SAML, WS-Fed, SCIM
Global StructureDomains & ForestsTenants
Org StructureTrees & Folders, OUsno equivalent
Access Control Mechanisms"file based," granularrole/function/resource-based
  • limitations of AAD DS:
    • no schema extensions
    • no multi-forest or multi-domain support
    • no domain admins / enterprise admins
    • users and passwords come from AAD, cannot flow in other direction
  • AAD Identity Types
    • users, built-in or cross-tenant
      • cross-tenant users have special UPN: [username]_[sourcedomain]#EXT@[domain].onmicrosoft.com
    • service principals
    • applications (like OAuth applications) - can in fact be exploited
  • built-in AAD roles are for AAD, Intune, O365 - but do not apply to Azure
    • AAD roles:
      • global admin - assigned to the user that created the tenant
        • can grant themselves access to Azure resources, but won't have access by default
      • user admin - can add/remove users, change passwords
      • billing admin - can add new services and subscriptions, but can't add/remove roles
  • AAD provides identities, Azure RBAC associates identities to roles
  • Azure RBAC fundamental roles (can be applied to specific resources, or 'scopes'):
    • Owner - full access + can grant others access
    • Contributor - full access but cannot grant access
    • Reader - read-only
    • User access administrator - manage Azure RBAC itself
  • Azure Permissions are transitive / hierarchical:
    • Management Groups
    • Subscriptions
    • Resource Groups
    • Resources
  • Compute services run on a version of Hyper-V
  • All disks are formatted as VHDs

I.D.c: GCP

  • GCP - supports programmatic and console access. Service accounts use RSA keypair auth. Native auth uses OIDC.
  • GCP permissions are transitive / hierarchical:
    • Organization
    • Folder
    • Project
    • Resources
  • Only major platform without "AWS SSM/Run-Command"-like capability
  • Compute uses KVM virtualization

I.E: Containers

  • what are they?
    • foundational technology of many cloud workloads today
      • most serverless and cloud-native services run on containers
    • why use containers?
      • offer isolation between services
      • highly portable - reduce 'it runs on my machine' troubleshooting
      • reproducible software deployments
      • easy packaging and isolation of software dependencies
      • much lighter-weight than a VM, which would also provide the benefits above
    • Fundamental property of containers:
      • kernel-based isolation of...
        • the file system (e.g. chroot)
        • the process tree (e.g. namespaces)
  • how do they work? how can I use them?
    • Linux technologies for implementation
      • cgroups - primarily a method for limiting resource usage
      • capabilities - granular execution permissions for kernel subsystems
      • namespaces - process/resource separation
      • chroot - filesystem isolation
    • it is possible to run a Linux container without a runtime, just:
      • cgcreate, cgset, cgexec, unshare, ip netns, chroot, setcap, getcap
      • however, not at all practical - where runtimes like Docker become useful
    • several runtimes available to simplify building and running containers
      • some are low-level only, like containerd, cri-o, and runc
        • these are used by many of the higher-level tools (like k8s) that are dedicated to orchestration
      • higher-level tools further simplify building, running, and - especially - orchestrating containers
        • Kubernetes (k8s)
        • Docker Swarm
        • HashiCorp Nomad
        • AWS ECS and AWS Fargate
  • container networking
    • most higher-level tools provision or rely on a "service mesh" - a software layer that handles all communication between services in applications
      • like a virtual/software-defined network on top of the host network(s)
    • no major orchestration tools provision firewalling by default - so, typically, all containers can reach all other containers over the container networks

I.E.a: k8s

  • "open source system for automating deployment, scaling, and management of containerized applications"
  • started by Google, now maintained by CNCF
  • notable features
    • automated rollout and rollback
    • horizontal scaling
    • self-healing
    • secrets configuration and management
    • RBAC permissions in v1.8 or higher
      • permissions specified by resource (or non-resource API URL) + verbs
  • Components
    • Control Plane
      • Kube Controller Manager - orchestrates node controller, replication controller, endpoint controller, token controller
      • Cloud Controller Manager - allows k8s controller to interact with platform-specific functions
    • API Server - the k8s API is the means of interacting with the control plane
    • Etcd - persisten key-value store. Like the /etc directory but configured as a redis-like db
    • Kube-Scheduler - manages how pods are controlled, booted, watched, etc. across nodes
    • Nodes
      • kubelet - the k8s agent on a node; runs PodSpecs commands, makes sure containers are healthy
      • kube-proxy - extends the service mesh to the node
  • Tools
    • kubeadm - can be used to build/instantiate clusters. Go binary.
    • kubectl - main operator tool, used to interact with control plane through the API
      • credentials for kubectl are stored in ~/.kube/config by default; can combine multiple config files by exporting an env var KUBECONFIG with all paths joined by ':'
    • each kubelet stores credentials/secrets in /var/run/secrets/kubernetes.io/<user or role>/{token,namespace,ca.crt}
  • Deploying k8s
    • API server and etcd should never be publicly exposed
    • deployment types:
      • Completely Cloud Managed: AWS EKS, GKE, Azure Kubernetes Service
      • Commercially Supported: Rancher, VMWare
      • On-Premises
  • Workloads
    • Pods
      • the smallest workload unit
        • one or more containers
        • share the same samespace and ports
        • defined by 'PodSpec'
          • includes container name to pull, env variables, secrets locations, any mounts
      • Privileged pods can mount the host filesystem ("host mounts")
      • native 'secret' resource type
    • Deployments
      • a Kubernetes controller that matches the current state of your cluster to the desired state mentioned in the Deployment manifest. Usually for stateless apps
    • StatefulSets
      • Kubernetes resource used to manage stateful applications. It manages the deployment and scaling of a set of Pods, and provides guarantee about the ordering and uniqueness of these Pods. All Pods get their own PersistentVolumeClaim (PVC)
    • DaemonSets
      • a controller that ensures that the pod runs on all the nodes of the cluster. If a node is added/removed from a cluster, DaemonSet automatically adds/deletes the pod
    • source for deployments, statefulsets, and daemonsets

I.F: Cloud Native Applications

  • Recent years have seen the rise of "cloud native" apps; those that are based on cloud technologies/infrastructure
  • CNCF's (Cloud Native Computing Foundation) "properties" for cloud native apps:
    • Container managed
    • CI/CD
    • Continuously tested
    • Orchestrated and Defined
  • Generally associated with microservices
  • Resources:
  • Intra-App Communication
    • Traditional:
      • HTTP (slow but universal)
      • RPC
      • SMB (LAN, Windows)
      • Database protocols (LAN)
      • SOA Bus (slow)
    • Cloud Native:
      • HTTP(S) / REST
      • gRPC - designed for cloud, serialization protocol
      • session state storage - e.g. Redis (which works over RESP, not http), Memcached
  • Discovery might require new/non-traditional methods
    • mutate document type in http requests, e.g. from text/html to application/json
    • brute force method types: POST, GET, PUT, PATCH, etc.
  • Client-Side Apps
    • Some modern web apps export the 'heavy lifting' to the client... the application logic is written in the Javascript that the client pulls down, prompting the client to generate URLs, fetch resources, etc.S
    • Occasionally, developers will slip up and point clients to over-exposed resources, or even embed secrets (e.g. AWS keys) into client-side logic

I.F.a: Infrastructure as Code (IaC)

  • method of deploying and/or configuring infrastructure via templates/scripts/code to:
    • speed up deployment
    • ensure consistency and/or repeatability
  • Common Tools
    • AWS CloudFormation (just use terraform, though)
    • Terraform
    • Azure Automation and Runbooks
    • Config-oriented tools: Ansible, Salt, PowerShell Desired State Configuration
  • Possible introduction of vulnerabilities:
    • automation tools typically require API keys or some form of secrets to perform their work. If left in the environment unencrypted...
  • Example attacks mechanisms for Terraform
    • change the source code / repository it deploys from, adding or changing systems
    • attack the Terraform launch point and steal the keys it's using to connect to the infra platform
    • get access to the Terraform state file and read it offline, stealing possible secrets
      • terraform show -state=/path/to/terraform.tfstate
      • terraform output secret -raw -state=/path/to/terrform.tfstate
  • Deployment Systems
    • IaC usually integrated with CI/CD
    • example: git commit --> pull request --> approved pull to main (manual up to this point) --> monitored repo --> automation system builds container based on code --> [optional testing] --> deployment
    • if some portion of the build process can be compromised, severe impacts can follow
    • SolarWinds is notable example: APT was able to change source code prior to an automated code-signing step, creating a customer-trusted Trojan
    • common build systems:
      • Travis CI
      • Argo CD
      • flux
      • GitHub Workers / Gitlab Runners
      • Buildkite
      • AWS CodeBuild
      • Azure Pipelines
      • Drone
      • CircleCI
    • sensitive files to look for:
      • JENKINSFILE
      • .travis.yml
      • .circleci/config.yml
      • drone/.drone.yml

I.G: Serverless Functions

  • discussing separately from cloud platforms in order to highlight similarities and differences between the available services on AWS/Azure
  • AWS Lambda
    • runs software as discrete functions; receives API call, executes function, returns result
    • spins up a container-based environment with the user-selected libraries/platforms needed to execute the user-defined function
    • supported environments: NodeJS, Python, Go, Ruby, PHP, PowerShell, C#
    • typically limited to a single function; tasks spin down after max of 15 minutes
    • can be exposed to the internet through AWS API Gateway or function URLs
      • can also be accessed through other AWS resources (e.g. EC2) or tools (AWS CLI) w\o API Gateway
      • aws lambda invoke --function-name <name> <output-file>
    • the invoker must have appropriate IAM permissions
    • hard to protect - can't install an agent on the platform. Best option is to use a WAF.
    • runtime/container environment CAN be compromised
    • Lambda code is hosted in S3 with a signed URL
    • based on Firecracker, an open-source virtualization platform for "microVMs"
  • Azure Functions
    • supported "runtime stacks": .NET, NodeJS, Python, Java, PowerShell Core, and custom handlers
    • typically run on Windows
    • can be public ("public gateway function") or private
    • the interesting part:
      • do not containerize at the Function layer - functions are grouped into "apps" - all functions for an app are hosted on the same OS
      • all functions have write access to the OS disk
      • all functions are stored in D:\home\site\wwwroot\<function name>
      • secrets are typically stored in D:\home\data\Functions\secrets
      • the app does have outbound internet access
      • based on kudu
      • the impact: compromise one function, and you've compromised them all

I.H: Databases in the Cloud

  • much more common to see databases and other backend technologies exposed in cloud-based architectures than in traditional on-premises deployments
    • sometimes for convenience, e.g. easy manual connections to backends for troubleshooting/admin
      • I have seen this in my own experience as a consultant
    • services like DigitalOcean and Linode offer VPSs w\o private networking and/or charge extra for private networking, leading teams to expose services either accidentally or for cost savings
  • many of the databases used in cloud apps do not offer security/authn and/or charge extra for it
    • MongoDB (charges for it)
    • Redis (doesn't have it - unless you configure client SASL)
  • in-memory databases like redis are typically used for shared state
    • if one can access and modify redis db entries, they can potentially grant themselves a session, elevated privileges, etc.
  • database deployment types
    • IaaS - deploy a server on IaaS, then deploy a DB server on top of that. pretty similar to on-prem
    • PaaS - administrator doesn't spin up a server, manage OS, or even the DB softare. e.g. AWS RDS
    • DBaaS - completely managed. admin just needs a URL. often many customers' DBs on a single DB server
  • query languages
    • SQL: SELECT <cols> FROM <table> WHERE <filter>;
    • Mongo: <class>.<location>.<method, e.g. find>({<filter})
      • show dbs
      • use <database>
      • show <collections>
      • db.<database>.find().Pretty() - equivalent to SELECT *
      • db.<database>.findOne({lastName:{$gt:'D'}}) - example of filter
        • filter operators: $gt, $gte, $lt, $lte

DB Examples

DBPortClient/Verification ToolExample Cmd
MongoDB27017mongo client, nmapnmap -p 27017 --script=mongodb-databases <ip>
Redis6379redis-cli, nmap, netcatnmap -p 6379 --script=redis-info <ip>

I.I: Web Authentication Standards

  • Common Web Auth Types
    • Basic - base64-encoded username:password sent along with every request
    • Bearer - 'Authorization: Bearer [token]' - typical for APIs
    • SAML - early 2000s SSO protocol, still very much around.
    • OAuth and OIDC - the most modern / most common SSO protocol
      • Started with OAuth 1 in 2010. Now on OAuth 2.0 which was a major change - now more of a framework as opposed to a protocol
  • Links

I.I.a: OAuth

  • Entities
    • Resource Owner - the authenticating user
    • Client - the application you're using that prompts for auth with the authorization server -->
    • Authorization Server - the Auth provider (e.g. the 'google' in 'log in with google')
    • Resource Server - source of the resources that are being accessed. can be the same as the authorization server, but doesn't have to be
  • Terms
    • scope - the permissions being granted to the client
    • authorization grant - temporary value the resource owner gets from the authorization server. exchanged for an access token
    • access token - the token that gets used between the application/client and the authorization server. in oidc, the token is a JWT
    • refresh token - used by an application/client to retrieve a new access token the old one expires (which typically happens frequently/quickly). the refresh token is typically long-lived
  • Flows (or grants) (good diagrams on Okta Developer here)
    • Authorization Code Flow - the most common. user is redirected to authorization server, obtains authorization grant, then passes the grant to the client, which then retrieves a token on the backend
    • Client Credentials - for system-to-system connections. a client credential is generated for (and provided to) the application
    • Resource Owner Password Credentials - captures the resource owner's credentials for client auth to the resource server. Only for highly trusted systems and really shouldn't be used tbh
    • Implicit Flow - DEPRECATED. Much like Authorization Code Flow, but without the added step of authorization code --> access token. Less secure
    • Device Authorization Grant - diagram, allows for out-of-band auth. useful for devices without browsers
  • OIDC
    • adds additional info & functionality on top of OAuth 2.0
    • ID Token - per-user object with identity info in the form of a JWT
    • Userinfo Endpoint - API endpoint facilitating user info exchange between client & authorization servers
    • Standardized scopes - what it sounds like
    • Stadardized Authorization Implementation - what it sounds like
  • JWTs (JSON Web Tokens)
    • standard way of exchanging info between client and server
    • not encrypted, but they are signed for integrity
    • format:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
  • always three encoded values separated by '.', and the first two letters of the first two values is always 'ey'
  • can read JWTs at jwt.ms or jwt.io

I.I.b: SAML

  • SAML (Security Assertion Markup Language) is a protocol for transmitting SSO info from an IdP to a third-party application via a message roughly resembling XML SOAP
  • supported protocols:
    • Authentication Request - main one, logs a user into a system. Similar to OAuth's authorization code flow. indicated by the <AuthnRequest> tag
    • Assertion Query and Request - for existing sessions. queries the system (IdP?) for what assertions are available to the user\
    • Artifact Resolution - kinda goofy. SAML message can be transmitted as a reference rather than a value. the receiver of said message would then send an 'ArtifactResolve' request to retrieve the actual message.
    • Name Identifier Management - used to obtain the asserting party's username / principal name
    • Single Logout - ...what it says. logs user out across all systems
    • Name Identifier Mapping - allows for account-linking
  • if you can secure the SAML issuer's private key, you can run the 'Golden SAML' attack with shimit

II: Process

II.A: Attack Surface Discovery

  • Goal: Identify the target's (reachable) assets

II.A.a: Pipeline Overview

Start FromThen GetThen Scan forIdentifying...
DomainsSubdomains & HostnamesRoutes/EndpointsServices
Company NamesHosts (IPs)Ports

II.A.b: Domains & Hosts

  • The output of this stage should be a list of domains and subdomains (hostnames).
  • The output could also include service tenants pointed to by a domain hint rather than a subdomain, e.g. saas.com/<domainhint>
  • Each identified hostname could point directly to an IP, or to a chained series of CNAMEs. Depending on the next-to-last DNS record, the IP may or may not be useful. For example: identifying the URL of a company's AAD tenant is useful. Resolving the IP is not.
  • Types of Names to Look for:
    • 'Owned Domain': e.g. 'company.com'
    • 'Owned Subdomain': e.g. '[wordlist].company.com'
    • Tenant Subdomains: e.g. '[tenantID].[provider URL]', like 'company .onmicrosoft.com'
    • Tenant Subdirs: least promising, might skip. e.g. '[provider URL]/[tenantID]'
II.A.b.i: Techniques
  1. OSINT Datasets
    • Can give us a set of hostnames and expand our list of 'target identifiers' or 'seed values.' Various services can provide some or all of the types of data we are looking for. See tables for examples & links.
  2. Certificate Transparency Reports
    • Can help us to find the first 3 types of names.
    • Nearly every Root CA logs each and every issued cert in CT reports; Most browsers refuse a certificate not logged in CTRs. Perform searches on every target identifier.
  3. Brute-Force DNS Recon
    • use wordlists and brute-force DNS queries for domain and subdomain discovery (can include common tenant patterns, e.g. subdomains on provider domains)

Other:

  • Honorable Mentions:
    • Searching domain hints (e.g. subdirs on provider domains)
    • Google Cache / Wayback Machine / Other Caches - view sites without generating traffic to the site
  • Aside: Subdomain Hijacking
    • Scenario: Company creates CNAME to point to a tenant on some service. Eventually gets rid of the tenant, but not the CNAME ("orphaned CNAME"). You can hijack the subdomain by registering the tenant.
II.A.b.ii: Wordlists
  • We want a few types of wordlists at this stage:
    1. Possible 'seed values', 'target identifiers,' or likely domain & subdomain names - keywords, essentially
    2. Tenant Subdomain Patterns: e.g. tenant.onmicrosoft.com
    3. Common Subdomains: e.g. pattern.known.host
Common subdomains
Tenant Patterns
  • Turns out, no one really maintains a great, consolidated list. Here's what I found:
    • Microsoft & Azure tenant URLs
    • https ://FUZZ.account.box.com
  • Instead of manually checking DNS records, we'll rely on some cloud enumeration tools. See 'Cloud Resources.'
II.A.b.iii: Possible Workflow
  1. Take the 'seed' value, or target identifier. Search open source datasets.
    • WHOIS
    • Censys
    • Shodan org:'Target Name'
    • SecurityTrails
    • IntelX
    • Robtex
  2. Search Certificate Transparency Records for all discovered target identifiers.
    • crt.sh
  3. Brute-force 'front door subdomains' using all target identifiers + subdomain wordlists.
  4. Brute-force tenant subdomains using all target identifiers + tenant wordlists.
  5. Perform DNS recon on each hostname. Get MX records as well.
  6. Perform a final analysis on any IPs retrieved. Find out if they belong to a cloud provider block. Arguably belongs in a data analysis section.

II.A.c: Services

  • In the first step, we gathered domains, subdomains, and hostnames. (We also have IPs.)
  • Now, we need to use those names to identify services. In some cases, names may point to a tenant, and in others, they may point to an IP that is wholly-owned by the target. If the name points to a tenant (e.g. company.onmicrosoft.com), port scanning will not be useful; We will have to identify the service by other means, usually by researching the provider URL.
  • The first step in this stage will be to separate 'wholly-owned' IPs (candidates for IP/Port scanning) from application-layer tenants.
II.A.c.i: Multi-Tenant Endpoints
  • AWS URL Nomenclature: 'protocol://service-code.region-code.amazonaws.com' Reference
  • Microsoft Services: URL nomenclature is inconsistent. List of provider URLs can be found here.
II.A.c.ii: Wholly-Owned IPs
  • Scan the discovered hosts to identify services. Use Masscan and NMAP.
    • nmap args:
    • -p: specify ports
    • -O: OS fingerprinting
    • -sV: version scanning / banner grabbing
    • -sC: enable scripting engine, do default category scans
    • -A: shortcut for -O -sV -sC --traceroute
    • -iL: list of IPs
  • The flow: masscan (large amount of hosts) --> nmap (get ports) --> NSE (get service details)
    • Tools for a combined workflow:
      • ScanCannon does the "masscan --> nmap" pipeline for you... doesn't seem reliable or flexible though.
      • JFScan looks to be a quality masscan --> nmap integrator
      • naabu Project Discovery port scanner that can pipe discovered ports to nmap scans. Not compelling.
  • Tips:
    • Scan all TCP ports
    • DON'T use all UDP ports - just the ones with well-known services
    • 0-1024: well-known ports
    • 1025-10000: common ports
    • 30000-32767: kube NodePort ports
    • Recall that some services require a host header (i.e. web servers)

II.A.d: Identity Systems

Identify whether target organization has a tenant on various IdPs

II.A.d.i: Azure AD
  • Good reference here
  • AAD first prompts for a username w\o a password and redirects differently based on the input
    • valid user + valid domain: prompted for a password
    • invalid user + valid domain: 'This username may be incorrect'
    • invalid domain: 'We couldn't find an account with that username...get a new Microsoft account'
  • to avoid lockout: rotate the service endpoint you try authenticating to
URLEndpoint
graph.microsoft.netMicrosoft Graph
management.azure.comAzure Management
management.core.windows.netWindows Network Management
proxy.cloudwebappproxy.netCloud Web App Proxy
officeapps.live.comOffice Apps
outlook.office365.comOutlook
webshell.suite.office.comWeb Shell Suite
  • Even better:
    • Validate tenant with: https: //login.microsoftonline.com/domain.com/.well-known/openid-configuration
    • Get tenant name and domain auth type: https: //login.microsoftonline.com/GetUserRealm.srf?login=user@domain.com&json=1
    • Validate that a specific user exists:
import requests
body = '{"Username":"test@domain.com"}'
# Can also POST to https://login.microsoft.com/common/oauth2/token
response = requests.post("https://login.microsoftonline.com/common/GetCredentialType", data=body).json()
if response["IfExistsResult"] == 0:
	print("Valid User")
  • All of the above can be accomplished with the AADInternals PowerShell module
  • Note that all AAD tenants, while they might have a custom domain, also have a default tenant: [tenantID].onmicrosoft.com
II.A.d.ii: G-Suite
  • Pretty simple: try logging into a gsuite app (like gmail) with an email address. A valid username will result in a password prompt. An invalid username will not ("Couldn't find your Google Account")
II.A.d.iii: Okta
  • First check is navigating to a suspected tenant: e.g. cisco.okta.com
    • Valid URL --> exists; 404 --> doesn't exist
    • Note: Historically, the 404 page would show a fake Okta login page. Does not appear to do so currently

II.A.e: Cloud Resources

  • focused on discovering cloud resources like S3, EBS, EFS, Azure Blobs, etc.
    • common misconfigurations/misunderstandings:
      • authenticated access (which just requires that you be authenticated to the platform, doesn't matter as what user) and authorized access.
      • also: a surprising amount of data is set to public access
    • AWS has policies (that can be IAM/identity-based or resource-based), and some services support ACLs
      • AWS Resource Policies - easy to misconfigure
      • Breakdown of what services support what IAM constructs
      • S3 ACLs are still supported, but deprecated
  • hunting methodologies
    • S3 buckets
      • have standardized URL structures - though there have been several over the years, and there are still multiple URL types, e.g. website endpoint vs REST endpoint
        • Website Endpoint: https: //[bucketname].s3-website-[region].amazonaws.com/[file]
        • REST Endpoint (global, not recommended): https: //[bucketname].s3.amazonaws.com/[file]
        • REST Endpoint (standard): https: //[bucketname].s3.[region].amazonaws.com/[file]
        • REST Endpoint (path routing, deprecated): https: //s3.[region].amazonaws.com/[bucket]/[file]
      • OR - just use the s3 client: aws s3 ls s3://<bucketname>/ --region <region>
    • Azure storage
      • URLs:
        • [storage account name].blob.core.windows.net
        • [storage account name].file.core.windows.net
        • [storage account name].table.core.windows.net
        • [storage account name].queue.core.windows.net
      • Azure Blobs (object storage) and Files (SMB-ish) both require a storage account (like a server name) and a container name (like a share name)
        • Blobs supports REST/HTTP, NFS, and SFTP
        • Files supports SMB and NFS
        • Common container names: backup, data, share, sql, finance, accounting, etc.
  • hunting tools
    • cloud_enum (appears to be the best option)
      • GCP buckets, app engine sites, firebase, cloud functions, etc.
      • Azure storage accounts, blob containers, DBs, VMs, webapps
      • AWS buckets
    • CloudBrute
      • storage and apps on Azure, AWS, and GCP (though less comprehensive)
      • storage on DigitalOcean, Vultr, Linode, and Alibaba
    • MicroBurst - more general purpose Azure testing w\ one helpful function: "Invoke-EnumerateAzureBlobs"
    • Gobuster - brute force URIs, DNS subdomains, virtual hostnames on webservers, S3 buckets, GCP buckets, TFTP servers
    • CloudStorageFinder - scan S3, DigitalOcean Spaces, and GCP Buckets

II.A.f: Data Analysis

  • At this point, we should have a list of service endpoints. We can begin some data analysis, which may lead to more discovery efforts.
  • Web services:
    • Visualization: gowitness - captures and displays screenshots
      • parameters, or modes: single [URL] | file [host list] | scan --cider [IPs] --ports [port list]
      • most fun mode: nmap [nmap scan file] - may not work though; web services generally require the 'Host' header
      • reporting mode: report server --address [ip]:[port]
    • We should also spider each web app to discovery additional hosts via src and href links

II.A.g: Scanning & Mapping

Though called out separately in the Process, scanning & mapping have been fully integrated into the other sections of Discovery notes.

II.A.h: End-to-End Tools

  • Many tools purport or endeavour to automate (or, at the very least,) accelerate the entirety of the steps described so far in Discovery (plus some that will be described in Enumeration)
    • Companies in the Attack Surface Discovery/Monitoring space
      • RunZero - previously Rumble. honorable mention only, mostly internal-asset-focused
      • SpiderFoot HX - Web UI discovery tool with an excessive number of modules. Does everything from sub-domain enumeration and DNS zone transfers to dark web searches and Bitcoin address extraction.
      • Assetnote
    • Free/Open-Source tools that do a lot
      • amass - from OWASP. can gather data from APIs or bruteforce. Data categories include: APIs, certificates, DNS, routing, scraping, web archives, and whois. Extensible. Plenty of community scripts.
        • 'intel' : collects data from 3rd parties
        • 'enum' : DNS enumeration
        • 'viz' : generates relationship visualizations
        • 'track' : compares enumerations against joint target org, valid for diffing
      • assetfinder - mostly leverages APIs to find assets. Useful for domain, subdomain, and host discovery
      • recon-ng - metasploit-like OSINT recon framework. entirely based on API integrations. Most modules require API keys.
    • Tools that do a LOT
      • reNgine - Web UI for discovery tools. Wrapper for other tools, including assetfinder, amass, sublist3r, naabu, subfinder, and nuclei.

II.B: Enumeration

II.B.a: Identity Systems

II.B.a.i: Username Harvesting
  • Most IdP portals prompt for a username without a password field, then redirect valid users to a password prompt.
  • Much of G-Suite & AAD already addressed above in the context of identifying valid tenants
  • LinkedIn and other social media can help to identify valid users for an organization
  • Tools for scraping metadata (including usernames) out of docs:
    • PowerMeta - given a target domain, will search for files on that domain, download the files, and extract metadata
    • FOCA - similar. retrieves metadata and hidden data from various filetypes
II.B.a.ii: Wordlists for Usernames & Passwords
  • CeWL can be useful for building wordlists by crawling a webpage
  • HaveIBeenPwned hash list
  • PW-Inspector - filters wordlists based on selected criteria. ships with Hydra.

II.B.b: Services

II.B.b.i: Vulnerability Scanning
  • nmap + NSE scripts
  • nuclei
    • supports checks over HTTP, DNS, TCP, and local filesystem
    • HTTP checks support full headless browser interaction
    • templates defined by yaml, relatively easy to create
      • can be simple or advanced; can even craft raw HTTP requests
    • cli parameters
      • -u [url] : specifies a URL to scan
      • -t [dir] : specifies a template directory to use
      • -l [host list] : specifies many targets
      • -w [workflow def] : specifies a workflow to use
      • -exclude-templates [dir] : (straightforward)
    • supports stuff that paid tools typically charge for
      • Versions of burp features such as: pitchfork, cluster bomb, sniper, battering ram

II.C: Exploitation & Escalation

II.C.a: Typical Initial Entries

  • Workstation compromise
  • Social engineering --> account compromise / workstation compromise
  • exploitation of public-facing application (typically a web app)

II.C.b: Web Application Attacks

II.C.b.i: SSRF
  • Server-Side Request Forgery: servers often pull in other data on the backend prior to form a response. These requests are often privileged (via auth) or to non-publicly-addressable systems. SSRF manipulates a server into sending server-side requests on our behalf.
  • Big example: attacks on AWS IMDSv1
    • IMDSv2 added a lot of complexity to the requests required to retrieve keys... this makes it less likely that SSRF could be used to grab keys - though does not prevent someone with RCE from grabbing the keys
    • IMDSv2 requires a PUT request to get a token before then using a GET request
  • Given the amount of containerization / microservice-ization of cloud-native apps, there are a lot of server-side requests going on in modern web applications
  • Possibilities:
    • Manipulate server to retrieve different information from its usual endpoint
    • Remote file/content inclusion - manipulate server to retrieving content from a malicious backend instead of its intended backend, possibly leading to code execution on the server
II.C.b.ii: Command-Line Execution
  • Non-static web applications require some framework, or interface, to receive and process incoming requests in order to generate responses (whether HTML, JSON, etc.)
    • classic: cgi-bin, mod-php
    • modern: .NET ISAPI, php-fpm, wsgi, node, django, etc.
  • all of these frameworks have some way to directly or indirectly call local files, which may be included or executed in the response process
  • an obvious opportunity may be the ping interface in a router portal; we can potentially append additional commands with &, &&, or ;
  • good injection attempts should be minimal, many servers - especially if containerized - have few non-essential binaries available
    • should err towards including full paths, PATH may not be set
    • Windows
      • cmd.exe /k dir C:\, URL-encoded: %26%26cmd.exe+/k+dir+C:\
      • cmd.exe /k set, URL-encoded: %26%26cmd.exe+/k+set
      • set, URL-encoded: %26%26set
    • Linux
      • /bin/id
      • /bin/env
      • /bin/uname
II.C.b.iii: SSJI
  • Server-Side JavaScript Injection - any server-side JS platforms (all of which generally build on top of node.js) are susceptible to SSJI if the client is able to control input to an eval() function
  • if user can pass unsanitized input:
    • require('child_process').execSync('id').toString())
    • runs the id command and returns the output as a string. Note the extra ), which would terminate the eval() command early
II.C.b.iv: SQL Injection
  • the classic attack; web apps often make calls to backend databases, and those queries often incorporate user input. W\o santization, an attacker can execute arbitrary SQL queries by passing unexpected values into a field originally intended as, say, a filter
  • from a blue team/engineer perspective, best way to combat SQLi: ORMs
    • Object-Relational Mapping (ORM) is a technique that lets you query and manipulate data from a database using an object-oriented paradigm. When talking about ORM, most people are referring to a library that implements the Object-Relational Mapping technique, hence the phrase "an ORM" (from Wikipedia)
    • prepared statements also a good option
// ORMs change this:

book_list = new List();
sql = "SELECT book FROM library WHERE author = 'Linus'";
data = query(sql); // an over-simplifcation here ...
while (row = data.next())
{
	book = new Book();
	book.setAuthor(row.get('author'));
	book_list.add(book);
}

// to this:

book_list = BookTable.query(author="Linus");

// src: https://stackoverflow.com/questions/1279613/what-is-an-orm-how-does-it-work-and-how-should-i-use-one 
  • Workflow
    1. Map injection points - all user-controlled inputs
    2. Discover blind and non-blind injections
    3. Fingerprint database type
    4. Discover schema (databases, tables, columns)
    5. Query data (start small, limit output)
  • the classic SQLi Test: ' or 'a' = 'a
  • Tools:

II.C.c: Identity Systems

II.C.c.i: Password Attacks
  • Definitions
    • Credential Stuffing: leverages known password breaches
    • Password Spraying: rotates one password against many users
    • Dictionary: rotates many 'curated' passwords against one or many users
    • Brute Force: brute force all possible passwords. basically never works (except for cracking short hashes)
  • AAD shunning acts on combination of source IP & user; can bypass by changing IP
  • Tools
    • Hydra - Easily the most popular password-cracking tool; supports rdp, ssh, telnet, radius, ike, sap, http, http forms, etc.
      • hydra [-l <username>|-L <usernames.txt>] [-p <password>|-P <passwords.txt>] <server> <service>
    • Omnispray
      • --type [enum|spray]
      • -uf [username list]
      • --module [e.g. o365_enum_office]
      • --count [n] - only valid for spraying, sets number of attempts per username
      • --lockout [n] - specifies how long to wait (in minutes) before lockout timers expire
    • Burp Suite (Intruder)
    • zaproxy
II.C.c.ii: AAD + Microsoft Graph Attack
  • by default, all AAD users can grant access to third-party applications
    • global admins can do so for all users
  • o365-attack-toolkit provides the infrastructure for an oauth phishing attack against AAD
    • it provides a web server that can be registered with Azure as a multi-tenant application.
    • If we can
      • convince a user to navigate to our page
      • grant the application permissions (after they've been redirected to authenticate/authorize with AAD)
    • then our 'application' now has an access token with whatever accesses the user granted us
II.C.c.iii: AWS IAM Escalation
  • escalation vulnerabilities/pathways:
    • create or apply a policy version on oneself, adding to current privileges
    • create an instance profile and attach it to an existing EC2 role
    • create a key-pair and run an EC2 instance with a more-privileged service profile
    • add a user to a group (with potentially higher privileges)
    • attach an existing policy to a user
    • the "IAM:SetDefault" permission - revert or roll-forward policy versions
    • the IAM:PassRole - pass a role to a service. the permission is assigned in a whitelist configuration.

II.C.d: EC2 Escalation

User-Data

When you launch an instance in Amazon EC2, you have the option of passing user data to the instance that can be used to perform common automated configuration tasks and even run scripts after the instance starts. You can pass two types of user data to Amazon EC2: shell scripts and cloud-init directives. You can also pass this data into the launch instance wizard as plain text, as a file (this is useful for launching instances using the command line tools), or as base64-encoded text (for API calls).

  • user-data scripts typically run as root
  • user-data is queryable through IMDS
  • EKS nodes will have the external API URL and certificate in their user-data

Instance Metadata Service

  • If you have execution on an EC2 instance, you can retrieve the key material necessary to run commands under the role assigned to the EC2
  • instances launch with IMDSv1 and v2 by default
# Note: 's3access' is an example role name

# IMDSv1
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/s3access

# IMDSv2 - get token for six hours
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" -v http://169.254.169.254/latest/meta-data/iam/security-credentials/s3access
  • to leverage compromised key material with aws create a new profile in ~/.aws/credentials
[profilename]
aws_access_key_id=<key>
aws_secret_access_key=<key>
aws_session_token=<token>

VPCs

  • Just like on-prem, remember that a given instance may be in a different network than other targets.

II.C.e: Pacu

  • Pacu: Python-based AWS exploitation tool
  • more than 35 modules across recon, enumeration, privesc, persistence, and more
  • menu-driven CLI with ls (list modules), help, run <module>
  • most pertinent recon/enumeration modules:
    • s3__bucket_finder (for public buckets)
    • iam__enum_users (needs valid AWS creds - but any creds)
    • iam__enum_roles (needs valid AWS creds - but any creds)
    • iam__bruteforce_permissions - discovers what you're able to do, but is exceptionally noisy
    • ec2__enum, lambda__enum, codebuild__enum - discover assets within their respective services
    • vpc__enum_lateral_movement - lists all DirectConnect and VPN connections
  • several exploits for gaining access to EC2, Lightsail, and searching EBS for key material

II.C.f: AWS Confused Deputy

  • Vendors / Service Providers frequently request clients create a dedicated role that the SP can assume (via the AssumeRole permission/action) to do their jobs.
  • Clients often do not lock this role down - i.e. anyone can assume it with the Account ID and Rolename
  • SP documentation often contains a suggested or required rolename

II.C.g: Azure Compute

  • Run-Command - similar to AWS SSM in that it allows us to run commands on a VM via cloud platform access
  • Custom Script Extension - very similar to EC2 User-Data
  • Azure Automation - CI/CD tool. "workers" can run PowerShell or Python scripts.
  • Standard WinRM and PSRemote may apply if enabled

II.C.h: Storage Layer

  • If one does not have access to a VM, but has access to its disks:
    • can use forensics to extract credentials
    • can use dism, Azure Storage Explorer, or other tools to add files, including backdoors

II.C.i: k8s

  • kube-hunter
    • k8s vulnerability scanner. can be run inside or outside of k8s cluster being scanned
  • Peirates
    • kubectl-based k8s attack tool
    • shortlist of capabilities:
      • gain shells on a worker node
      • compromsie k8s service accounts
      • list secrets from k8s, or even from AWS/GCP using metadata service
      • move itself laterally

II.C.j: Data Exfiltration

  • cloud-enhanced options for exfil:
    • exfil to cloud services like OneDrive, Box, Google Drive, etc.. Hard to identify tenants, and many organizations don't perform deep inspection due to traffic volume
    • for cloud-hosted data: cross-account roles / copies may be much stealthier than typical network protocol-based exfil

II.D: Elevated Reconnaissance

II.D.a: Searching for Key Material

  • Frequent Locations
    • source code repositories
    • JavaScript code
    • dashboard systems
    • environment variables
    • instance metadata service
    • admin, developer, bastion, pivot systems
    • build systems
  • Search Patterns
    • OpenSSH Keys: '-----BEGIN RSA PRIVATE KEY-----'
    • OpenSSH ECDSA Keys: '-----BEGIN OPENSSH PRIVATE KEY-----'
    • GnuPG Keys: '-----BEGIN PGP PRIVATE KEY BLOCK-----'
    • Certificate PEM: '-----BEGIN PRIVATE KEY-----'
    • env files: [keyname]=[value], '^(?i)[a-z0-9\s]key[a-z0-9](?-i)=.*'
    • yaml files: [key]: [value], '^(?i)[a-z0-9\s]key[a-z0-9](?-i):.*'
    • common variables:
      • host
      • password
      • mysqldb_password
      • db_password
      • postgres_password
      • user
      • username
      • keys
      • ssh_keys
      • ARM_CLIENT_ID
      • ARM_CLIENT_SECRET
      • ARM_SUBSCRIPTION_ID
      • ARM_TENANT_ID
      • AWS_ACCESS_KEY_ID
      • AWS_SECRET_ACCESS_KEY
      • GITHUB_TOKEN
      • do_token
      • DIGITALOCEAN_TOKEN
II.D.a.i: Cloud-Specific Key Material Locations
awsazuregcp
.aws/credentials.azure/.config/gcloud
.aws/config.azure/msal_token_cache.json.config/gcloud/access_tokens.db
.aws/cache.azure/azureProfile.json.config/gcloud/credentials.db

II.E: Pivots and Persistence

II.E.a: Backdooring Containers

  • depending on the scenario, could be a persistence or an exploitation technique
  • requires compromising the code respository, CI/CD and/or build process, a k8s/orchestration configuration files, or the container registry
    • e.g. create a backdoored container, host on Docker Hub, then modify the target's k8s config to pull your container
PodSpec-for-Host-Takeover
apiVersion: v1
kind: Pod
metdata:
	...
spec:
	containers:
		...
		securityContext:
			privileged: true
			allowPrivilegeEscalation: true
  • Pro: containers are ephemeral, so evidence may be destroyed for you
  • Con: containers are ephemeral, so may not last

II.E.b: C2 Payloads

  • Possible backdoor payloads:
    • AutoSSH - monitor ssh tunnels and restart as needed
    • msfvenom payloads
    • sliver payloads
    • Note: The C2 Matrix maintains a list of C2 frameworks, any of which could be used for backdooring
      • Mythic and Caldera have decent Web UIs, though Caldera is more for purple-teaming than true exploitation
  • complications with traditional payloads in the cloud
    • what are they?
      • gen 1 payloads: netcat, socat, sockets
      • gen 2 payloads: meterpreter
    • detectable by modern, off-the-shelf tools
    • may not be reliable and/or stable
    • gen 1 payloads particularly suffer on cloud workloads, which may not have typical LOL binaries
  • techniques for combating challenges
    • statically compile payloads and move them onto systems via curl or similar
    • build custom payloads - common among red-team firms
  • advanced C2 architecture techniques
    • Redirection Nodes - essentially proxying traffic between victim and C2 server. Can be hosted on any cloud platform. Obfuscates true source and can make it difficult to identify as malicious in the first place
      • options: compute nodes (like EC2), load balancers, (API) gateways, serverless functions
    • File-based C2 - communicate job requests and results as files on OneDrive, Dropbox, Google Drive, etc.; hard for defenders to see what's happening without deep inspection that is usually skipped for such services, given traffic volume
    • API Gateway - using serverless cloud platform features like AWS API Gateway or AWS SES (simple email service) to be the middleman between attacker

II.E.c: Pivoting Tools

  • netcat
  • socat
  • native tools
    • Linux: iptables / nftables - can pivot with NAT
    • Windows: netsh / portproxy
  • for linux: requires ipv4 forwarding to be enabled
    • sysctl net.ipv4.ip_forward=1 (temporary)
    • echo "net.ipv4.ip_forward = 1" >> /etc/systctl.conf (sets persistent config)

III: Red Team Ops in the Cloud

  • the cloud can provide advantages for red team infrastructure
    • the cloud's ubiquitous nature can mask red team activity - particularly if enchanced with certain techniques
    • infrastructure can be launched, destroyed, and rotated quickly and easily
    • attacks can rotate IPs and even cloud service providers to avoid defensive controls like IP blocking
    • leveraging legitimate service for malicious ends can complicate protections - what organization afford to block OneDrive, SharePoint, or even Google AppEngine?
  • the primary drawback and/or complication: staying within TOS
  • IP Rotation Techniques
    • ProxyCannon-NG - round-robin routes traffic across compute nodes on multiple clouds
    • Burp Suite "IP Rotate" module performs this technique with AWS API Gateway
  • C2 Obfuscation Techniques
    1. Using a CDN to hide traffic
      • Domain Fronting
        • hides the actual destination of a connection by mismatching the hostname and SNI used for a connection
        • Process
          1. Host C2 on a CDN and identify a valid site also using that CDN
          2. Point payload to the valid site hostname, which will cause DNS to resolve to a CDN endpoint
          3. Ensure payload uses the SNI (Server Name Indication) of the C2 when establishing TLS; like the "HOST" field in an HTTP request... in fact, make sure the "HOST" field is set as well
        • Disabled by Google and Amazon, but still possible elsewhere
    2. Using well-known and/or "good" sites
      • Domain Hunter - Checks expired domains for categorization/reputation and Archive.org history to determine good candidates for phishing and C2 domain names
      • Flippa - marketplace for buying and selling web properties (e.g. not just a domain but an existing web store, blog, etc.)
    3. Proxies and/or Load Balancers