Microsoft Graph AI Red Team Framework
AI-Powered Multi-Agent Security Testing Framework for Microsoft Graph API Penetration Testing
Overview
The Microsoft Graph AI Red Team Framework is an advanced autonomous security testing tool that leverages GPT-4 powered AI agents to perform intelligent penetration testing against Microsoft Graph API endpoints. This framework automates the entire attack lifecycle from reconnaissance to exploitation using three specialized AI agents.
Key Features
- Autonomous AI Agents: Three specialized agents (Scout, Strategist, Operative) work together to perform complex attack chains
- GPT-4 Powered Planning: Intelligent exploitation strategies generated dynamically based on available permissions
- Adaptive Attack Logic: Learns from failures and adjusts tactics in real-time
- Comprehensive Reconnaissance: Automated discovery of users, groups, applications, and sensitive resources
- Crown Jewel Detection: Automatically identifies and flags high-value targets
- Complete Audit Trail: All operations logged with curl equivalents for reproducibility
- Multi-Step Attack Chains: Orchestrates complex sequences like privilege escalation and persistence
Perfect For
- Red Team Operations: Automated Microsoft 365 and Azure AD penetration testing
- Security Assessments: Validate Graph API security controls and permissions
- OAuth Security Testing: Test application permission abuse scenarios
- Purple Team Exercises: Generate realistic attack patterns for detection engineering
- Security Research: Explore Microsoft Graph API attack surface
- Compliance Validation: Test security controls required by regulations
Demo Video
🎥 Watch the full demonstration from LASCON:
Click the image above to watch the complete walkthrough of autonomous AI-driven Graph API exploitation
How It Works
The Three AI Agents
1. Scout Agent (ReconAgent)
- Analyzes OAuth token scopes and permissions
- Enumerates all accessible Microsoft Graph API endpoints
- Discovers users, groups, applications, devices, and roles
- Extracts entity IDs for exploitation chaining
- Identifies "crown jewel" targets (admin roles, audit logs, etc.)
2. Strategist Agent (PlannerAgent)
- Powered by GPT-4 for intelligent attack planning
- Generates multi-step exploitation plans based on available permissions
- Adapts strategies when operations fail
- Prioritizes high-impact attack paths
- Creates realistic attack scenarios (privilege escalation, persistence, lateral movement)
3. Operative Agent (ExploitExecutor)
- Executes attack plans with precision
- Handles dynamic placeholder resolution (user IDs, group IDs, etc.)
- Implements retry logic for transient failures
- Detects and flags successful crown jewel accesses
- Logs all operations with full curl command equivalents
Attack Flow
1. Token Analysis → 2. Reconnaissance → 3. AI Planning → 4. Execution → 5. Adapt & Retry
↓ ↓ ↓ ↓ ↓
Parse scopes Enumerate endpoints GPT-4 strategy Run attacks Learn from failures
Installation
Prerequisites
- Python 3.8 or higher
- OpenAI API key (for GPT-4 access)
- Microsoft Graph API access token with appropriate scopes
- Azure CLI (for token acquisition)
Quick Start
- Clone the repository
git clone https://github.com/securelayer7/msg-ai-agent.git
cd msg-ai-agent- Install dependencies
pip install -r requirements.txt
- Configure OpenAI API key
cp .env.example .env # Edit .env and add your OpenAI API key echo "OPENAI_API_KEY=sk-your-key-here" > .env
- Acquire Microsoft Graph token
Choose one of the following methods:
Method 1: Quick Script (Easiest)
Method 2: Azure CLI
az login
az account get-access-token --resource https://graph.microsoft.com --query accessToken -o tsv > token.txtMethod 3: Using PowerShell (Windows)
Connect-AzAccount (Get-AzAccessToken -ResourceUrl "https://graph.microsoft.com").Token | Out-File -FilePath token.txt -NoNewline
Method 4: Device Code Flow (Headless/Remote)
az login --use-device-code
az account get-access-token --resource https://graph.microsoft.com --query accessToken -o tsv > token.txtMethod 5: Service Principal (Automated Testing)
az login --service-principal -u <app-id> -p <password-or-cert> --tenant <tenant-id> az account get-access-token --resource https://graph.microsoft.com --query accessToken -o tsv > token.txt
Method 6: Browser Developer Tools (Manual)
- Login to https://portal.azure.com
- Open browser DevTools (F12)
- Go to Network tab
- Filter for "graph.microsoft.com"
- Copy the Bearer token from Authorization header
- Save to
token.txt
Method 7: Using Postman/Insomnia
- Create OAuth 2.0 request
- Auth URL:
https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize - Access Token URL:
https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token - Scope:
https://graph.microsoft.com/.default - Copy access token to
token.txt
Method 8: Python Script (Programmatic)
from msal import PublicClientApplication app = PublicClientApplication(client_id="your-app-id", authority="https://login.microsoftonline.com/your-tenant") result = app.acquire_token_interactive(scopes=["https://graph.microsoft.com/.default"]) with open('token.txt', 'w') as f: f.write(result['access_token'])
- Run the framework
Usage
Basic Execution
The framework will automatically:
- Load and validate your Graph API token
- Perform comprehensive reconnaissance
- Generate AI-powered exploitation plans
- Execute attacks with adaptive retry logic
- Save all results to
runs/{timestamp}/
Output Structure
runs/
└── 2025-10-23T15-30-00Z/
├── recon.json # Complete reconnaissance data
├── crown_jewels.json # High-value targets accessed
├── recon/
│ ├── {timestamp}_users.json
│ ├── {timestamp}_groups.json
│ ├── {timestamp}_applications.json
│ └── {timestamp}_directoryRoles.json
└── {uuid}_{METHOD}_{endpoint}.json # Individual operation logs
Attack Scenarios
The framework can autonomously execute various red team scenarios:
1. Privilege Escalation
- Create backdoor admin accounts
- Assign Global Administrator roles
- Add users to privileged groups
2. Persistence Mechanisms
- Create hidden OAuth applications
- Generate application secrets for persistent access
- Create service principals with high privileges
3. Lateral Movement
- Enumerate organizational structure
- Identify high-value users and groups
- Add backdoor accounts to sensitive groups
4. Stealth & Evasion
- Hide groups from Global Address List
- Create shadow infrastructure
- Minimize detection footprint
5. Data Exfiltration
- Access audit logs
- Enumerate SharePoint sites
- Discover sensitive documents and emails
Configuration
Token Scopes
For comprehensive testing, your token should include:
High-Privilege Scopes:
User.ReadWrite.All- User manipulationGroup.ReadWrite.All- Group operationsDirectory.ReadWrite.All- Directory modificationsApplication.ReadWrite.All- App registration controlRoleManagement.ReadWrite.Directory- Role assignments
Read-Only Scopes (for safer testing):
User.Read.AllGroup.Read.AllDirectory.Read.AllAuditLog.Read.All
Environment Variables
Create a .env file:
OPENAI_API_KEY=sk-your-openai-api-key-here
Security & Ethics
This framework is designed for:
- Authorized penetration testing
- Red team exercises with proper authorization
- Security research in controlled environments
- Educational purposes
DO NOT use this tool against:
- Systems you don't own
- Environments without explicit written permission
- Production systems without proper change control
- Any unauthorized targets
All operations are logged. You are responsible for your actions.
Architecture Details
Technology Stack
- AI/ML: OpenAI GPT-4 for strategic planning
- Framework: CrewAI for multi-agent orchestration
- Graph API: Microsoft Graph REST API v1.0
- Authentication: OAuth 2.0 Bearer tokens
- Language: Python 3.8+
Agent Communication
ReconAgent → PlannerAgent → ExploitExecutor
↓ ↓ ↓
Entity IDs Attack Plan Execution Results
↓ ↓
Failure Analysis → Replanning
Dependencies
crewai # Multi-agent orchestration
langchain-openai # GPT-4 integration
requests # HTTP operations
python-jose # JWT token parsing
python-dotenv # Environment management
Roadmap
- Support for Microsoft Graph Beta endpoints
- Integration with MITRE ATT&CK framework
- Enhanced stealth and evasion techniques
- Custom attack scenario templates
- Integration with SIEM detection testing
- Multi-tenant attack simulation
- Automated report generation
Contributing
Contributions are welcome! Please follow these guidelines:
- Fork the repository
- Create a feature branch (
git checkout -b feature/improvement) - Commit your changes (
git commit -m 'Add new feature') - Push to the branch (
git push origin feature/improvement) - Open a Pull Request
Troubleshooting
Common Issues
Token Expired
# Re-authenticate and get new token
./get_token.shPermission Denied
Ensure your token has the required scopes. Check token claims with:
python -c "from core.utils.token_utils import get_token_claims; import json; print(json.dumps(get_token_claims(open('token.txt').read()), indent=2))"
OpenAI API Errors
- Verify your API key is valid
- Check you have GPT-4 access
- Ensure sufficient API credits
License
This project is licensed under the MIT License - see the LICENSE file for details.
Disclaimer
This tool is provided for educational and authorized security testing purposes only. The authors and contributors are not responsible for any misuse or damage caused by this tool. Always obtain proper authorization before testing any systems.
Keywords
Microsoft Graph API, Graph API security testing, Azure AD penetration testing, Microsoft 365 red team, OAuth security testing, AI-powered penetration testing, GPT-4 security tools, autonomous security agents, Graph API exploitation, Azure security assessment, M365 security testing, privilege escalation Microsoft Graph, AI red team tools, Microsoft security research
