Welcome to the GenAI API Pentest Platform! This guide helps you get started with AI-powered API security testing designed for SMB/SME environments.
Current Status: This is a proof-of-concept implementation (15% complete) with core AI scanning capabilities.
- Python 3.8+ (Python 3.11 recommended)
- 4GB RAM minimum
- 1GB free disk space
- Internet connection for LLM API access (or local LLM setup)
Choose at least one option:
Cloud LLMs (Paid):
- OpenAI: GPT-3.5-turbo (
$0.002/1K tokens) or GPT-4 ($0.03/1K tokens) - Anthropic: Claude models (~$0.008/1K tokens)
- Google AI: Gemini models (competitive pricing)
- OpenRouter: Access multiple models including open-source
Local LLMs (Free):
- Ollama: Run Llama2, CodeLlama, or other models locally
- OpenAPI/Swagger 2.0/3.x specification file or URL
- Written authorization to test the target API
- Network access to the target API endpoints
# Clone the repository
git clone https://github.com/gensecaihq/genai-api-pentest-platform.git
cd genai-api-pentest-platform
# Create virtual environment
python3 -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt
# Copy environment configuration
cp .env.example .envOption A: Cloud LLM Setup
# Edit .env file with your API keys
nano .env
# Add at least one of these:
OPENAI_API_KEY=sk-your-openai-key
ANTHROPIC_API_KEY=sk-ant-your-anthropic-key
GOOGLE_API_KEY=your-google-key
# Optional: Adjust settings
LOG_LEVEL=INFO
HTTP_TIMEOUT=30
MAX_PAYLOADS_PER_ENDPOINT=25Option B: Local LLM Setup (Free)
# Install Ollama
curl -fsSL https://ollama.ai/install.sh | sh
# Download a model
ollama pull llama2
# Configure .env for local LLM
echo "OLLAMA_BASE_URL=http://localhost:11434" >> .env
echo "LOCAL_MODEL=llama2" >> .env# Validate configuration
python -c "from src.core.config_validator import validate_config_dict; print('✅ Configuration valid')"
# Run example scan
python scripts/example_scan.py examples/vulnerable-api.yamlEdit your .env file with at least these settings:
# Required: At least one LLM provider
OPENAI_API_KEY=sk-your-openai-key-here
# OR
ANTHROPIC_API_KEY=sk-ant-your-anthropic-key-here
# OR
GOOGLE_API_KEY=your-google-ai-key-here
# Security (generate random values)
SECRET_KEY=your-secret-key-here
JWT_SECRET=your-jwt-secret-here
# Application
ENVIRONMENT=development
DEBUG=true# Generate SECRET_KEY
python3 -c "import secrets; print('SECRET_KEY=' + secrets.token_urlsafe(32))"
# Generate JWT_SECRET
python3 -c "import secrets; print('JWT_SECRET=' + secrets.token_urlsafe(32))"Note: Web interface and CLI are planned features. Current version uses Python API:
import asyncio
from src.api.parser import OpenAPIParser
from src.attack.bola_scanner import BOLAScanner
from src.validation.vulnerability_validator import VulnerabilityValidator
async def scan_api():
# Parse OpenAPI specification
async with OpenAPIParser() as parser:
api_spec = await parser.parse_from_url('https://api.example.com/openapi.json')
# Or from file: api_spec = await parser.parse_from_file('api.yaml')
# Configure scanner
config = {
'genai': {
'providers': {
'openai': {'api_key': 'your-key', 'enabled': True}
}
},
'http_client': {'verify_ssl': False, 'timeout': 30}
}
# Run BOLA scan on endpoints
scanner = BOLAScanner(config)
validator = VulnerabilityValidator(config)
vulnerabilities = []
for endpoint in api_spec.endpoints[:5]: # Test first 5 endpoints
async for vuln in scanner.scan(endpoint):
# Validate to reduce false positives
validation = await validator.validate_vulnerability(vuln)
if validation.is_valid:
vulnerabilities.append(vuln)
print(f"✅ Found: {vuln.title} (confidence: {validation.confidence_score:.2f})")
return vulnerabilities
# Run the scan
results = asyncio.run(scan_api())Use the provided example script:
# Scan a remote OpenAPI spec
python scripts/example_scan.py https://api.example.com/openapi.json
# Scan a local file
python scripts/example_scan.py ./examples/vulnerable-api.yaml
# The script will:
# 1. Parse the OpenAPI specification
# 2. Prioritize endpoints for testing
# 3. Run BOLA scans with AI-generated payloads
# 4. Validate findings to reduce false positives
# 5. Display results with actionable recommendationsThe platform generates comprehensive reports including:
- Severity: Critical, High, Medium, Low, Info
- Confidence: AI confidence score (0.0-1.0)
- Vulnerability Type: OWASP category classification
- Affected Endpoints: Specific API endpoints and methods
- Business Logic Assessment: Understanding of application flow
- Exploit Chain Discovery: Multi-step attack scenarios
- Custom Payload Generation: Context-aware attack vectors
- False Positive Reduction: AI validation of findings
{
"vulnerability": {
"id": "bola_users_456",
"title": "BOLA: Successful access to unauthorized object",
"severity": "HIGH",
"confidence": 0.85,
"attack_type": "authorization",
"endpoint": {
"path": "/users/{id}",
"method": "GET"
},
"payload": "admin",
"evidence": {
"response_status": 200,
"response_time": 150,
"technique": "privilege_escalation"
},
"ai_analysis": "AI detected unauthorized access to user data using 'admin' payload. Response contains sensitive user information that should require proper authorization.",
"business_impact": "High business impact: Unauthorized access to sensitive user data, potential data breaches, compliance violations",
"remediation": [
"Implement proper authorization checks for object access",
"Use indirect object references (e.g., session-based identifiers)",
"Validate user permissions for each object request"
],
"validation_result": {
"is_valid": true,
"confidence_score": 0.82,
"false_positive_probability": 0.15
}
}
}Monitor scan progress with:
- Real-time updates via web interface or WebSocket
- Detailed logs showing tested endpoints
- Performance metrics (requests/second, response times)
- AI provider usage and consensus results
# Comprehensive security assessment
python -m src.cli scan target-api.yaml \
--mode comprehensive \
--providers openai,anthropic \
--output-format html,pdf \
--auth-header "Authorization: Bearer $API_TOKEN"# Quick security check in pipeline
python -m src.cli scan swagger.json \
--mode basic \
--fail-on critical,high \
--output-format json# Deep AI analysis for advanced attacks
python -m src.cli scan api-spec.yaml \
--mode ai-deep \
--enable-business-logic \
--enable-exploit-chains \
--providers openai,anthropic,google# Development-friendly scan
python -m src.cli scan local-api.yaml \
--mode standard \
--exclude-destructive \
--output-format htmlproviders = [
{"name": "openai", "api_key": "sk-...", "model": "gpt-4"},
{"name": "anthropic", "api_key": "sk-ant-...", "model": "claude-3-opus"},
{"name": "google", "api_key": "...", "model": "gemini-pro"}
]
pentest = GenAIPentest(
providers=providers,
consensus_threshold=0.8 # Require 80% agreement
)# API Key authentication
auth = {"type": "api_key", "key": "your-api-key", "location": "header"}
# Bearer token authentication
auth = {"type": "bearer", "token": "your-jwt-token"}
# Custom header authentication
auth = {"type": "custom", "headers": {"X-API-Key": "your-key"}}
results = await pentest.scan(target_url, auth=auth)scan_config = {
"mode": "comprehensive",
"max_concurrent_requests": 10,
"request_timeout": 30,
"follow_redirects": False,
"verify_ssl": True,
"enable_business_logic": True,
"enable_exploit_chains": True
}
results = await pentest.scan(target_url, config=scan_config)# Fix Python path issues
export PYTHONPATH="${PYTHONPATH}:$(pwd)"
pip install -e .# Check database connectivity
python3 -c "from src.core.database import test_connection; import asyncio; asyncio.run(test_connection())"
# Reset database
alembic downgrade base
alembic upgrade head# Test API keys
python3 -c "
from src.genai.providers import test_providers
import asyncio
asyncio.run(test_providers())
"# Fix file permissions
chmod +x scripts/setup.sh
mkdir -p data/reports logs
chmod 755 data logs- Debug Mode: Set
DEBUG=truein.envfor detailed logging - Verbose CLI: Use
--verboseflag for detailed output - Log Files: Check
logs/genai_pentest.logfor application logs - Health Check: Run
python3 smoke_test.pyto verify setup
- Configuration Guide - Detailed configuration options
- Security Best Practices - Secure deployment guidelines
- Complete Documentation - Full platform documentation
- Contributing Guide - How to contribute to the project
- BOLA/IDOR Detection: AI-powered authorization bypass testing
- OpenAPI Parsing: Automatic endpoint discovery and analysis
- Multi-LLM Consensus: Validation across multiple AI providers
- Advanced Validation: False positive reduction techniques
- Payload Intelligence: AI-generated context-aware attack payloads
- Response Analysis: Pattern recognition and anomaly detection
- Additional OWASP Top 10: SQL injection, XSS, and other vulnerability types
- Web Interface: User-friendly scanning dashboard
- CLI Tool: Command-line interface for automation
- Reporting: HTML/PDF report generation
- CI/CD Integration: Pipeline integration tools
- GraphQL Support: Schema parsing and testing
- Postman Collections: Import and test Postman files
- Team Features: Multi-user collaboration
- Advanced Analytics: Vulnerability trending and insights
- Always obtain written authorization before testing any API
- Comply with all applicable laws and regulations
- Follow responsible disclosure practices for found vulnerabilities
- Use only for defensive security purposes
- This is proof-of-concept software - use in controlled environments
- Start with GPT-3.5-turbo for cost-effective testing (~$0.10-$2.00 per API)
- Use local LLMs (Ollama) for free testing with reduced accuracy
- Monitor API usage through provider dashboards
- Set usage limits to control costs
- Built-in rate limiting protects target APIs
- Configurable request delays via
RATE_LIMIT_DELAY - Limited payload count via
MAX_PAYLOADS_PER_ENDPOINT - Test on staging environments first
Ready to start securing APIs with AI? 🚀
This is an active development project - expect frequent updates and improvements. Check SCOPE-NEW.md for the latest roadmap.