Skip to content

securelayer7/msg-ai-agent

Repository files navigation

Microsoft Graph AI Red Team Framework

AI-Powered Multi-Agent Security Testing Framework for Microsoft Graph API Penetration Testing

GitHub stars GitHub forks License Python 3.8+

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:

Microsoft Graph AI Red Team Framework - LASCON Demo

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

  1. Clone the repository
git clone https://github.com/securelayer7/msg-ai-agent.git
cd msg-ai-agent
  1. Install dependencies
pip install -r requirements.txt
  1. 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
  1. Acquire Microsoft Graph token

Choose one of the following methods:

Method 1: Quick Script (Easiest)

./get_token.sh

Method 2: Azure CLI

az login
az account get-access-token --resource https://graph.microsoft.com --query accessToken -o tsv > token.txt

Method 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.txt

Method 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)

  1. Login to https://portal.azure.com
  2. Open browser DevTools (F12)
  3. Go to Network tab
  4. Filter for "graph.microsoft.com"
  5. Copy the Bearer token from Authorization header
  6. Save to token.txt

Method 7: Using Postman/Insomnia

  1. Create OAuth 2.0 request
  2. Auth URL: https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize
  3. Access Token URL: https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token
  4. Scope: https://graph.microsoft.com/.default
  5. 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'])
  1. Run the framework
python main.py

Usage

Basic Execution

python main.py

The framework will automatically:

  1. Load and validate your Graph API token
  2. Perform comprehensive reconnaissance
  3. Generate AI-powered exploitation plans
  4. Execute attacks with adaptive retry logic
  5. 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 manipulation
  • Group.ReadWrite.All - Group operations
  • Directory.ReadWrite.All - Directory modifications
  • Application.ReadWrite.All - App registration control
  • RoleManagement.ReadWrite.Directory - Role assignments

Read-Only Scopes (for safer testing):

  • User.Read.All
  • Group.Read.All
  • Directory.Read.All
  • AuditLog.Read.All

Environment Variables

Create a .env file:

OPENAI_API_KEY=sk-your-openai-api-key-here

Security & Ethics

⚠️ IMPORTANT: AUTHORIZED USE ONLY

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:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/improvement)
  3. Commit your changes (git commit -m 'Add new feature')
  4. Push to the branch (git push origin feature/improvement)
  5. Open a Pull Request

Troubleshooting

Common Issues

Token Expired

# Re-authenticate and get new token
./get_token.sh

Permission 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


Developed by SecureLayer7 | Website | GitHub

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published