# Azure APIM Key Scanner - Usage Guide

## 🎯 What We Learned from RoseSecurity's Azure Enumeration

### Key Techniques Applied:

1. **DNS-Based Discovery** - Use DNS queries to find valid Azure subdomains before wasting time on HTTP requests
2. **Subdomain Permutations** - Systematically test common patterns (dev, prod, api, etc.)
3. **Multiple Record Types** - Check A, CNAME, TXT, MX, NS records for comprehensive coverage
4. **Regional Variations** - Include Azure region-specific subdomains (eastus, westeu, etc.)

## 📦 Installation

```bash
# Install required packages
pip install requests dnspython beautifulsoup4
```

## 🚀 Quick Start

### 1. Basic Azure APIM Enumeration (Fast)
```bash
python azure_apim_enum.py -d purolator -v
```
**What it does:**
- Tests `purolator.azure-api.net`
- DNS queries only (very fast, ~19 domains)
- Finds valid APIM endpoints
- No permutations

**Time:** ~10 seconds

---

### 2. Full Enumeration with Permutations (Thorough)
```bash
python azure_apim_enum.py -d purolator -p -v
```
**What it does:**
- Tests 500+ subdomain variations:
  - `api-purolator.azure-api.net`
  - `purolator-prod.azure-api.net`
  - `purolator-eastus.azure-api.net`
  - `dev-purolator.azure-api.net`
  - And many more...
- Scans all discovered endpoints
- Extracts keys from responses
- Tests keys automatically

**Time:** ~2-5 minutes (depending on findings)

---

### 3. Target Specific Website (Direct)
```bash
python apim_discovery_scanner.py -u https://example.com -v
```
**What it does:**
- Checks if site uses APIM
- Downloads JS bundles
- Extracts APIM endpoints and keys
- Tests found keys

**Time:** ~30-60 seconds

---

## 🎬 Real-World Example

### Scenario: You want to find all APIM keys for "Contoso" company

```bash
# Step 1: Enumerate Azure infrastructure
python azure_apim_enum.py -d contoso -p -v -o contoso_enum.json

# Results might show:
# ✓ Found: contoso-api.azure-api.net
# ✓ Found: contoso-prod.azure-api.net
# ✓✓ APIM endpoint: https://contoso-api.azure-api.net
# ✓✓✓ KEYS FOUND in https://contoso-api.azure-api.net!
```

```bash
# Step 2: Check their public website
python apim_discovery_scanner.py -u https://www.contoso.com -v -o contoso_web.json

# Results might show:
# [SUCCESS] ✓ Found in https://www.contoso.com/static/js/main.js
# Keys Found: 1
#   → ed079319...26e3
```

```bash
# Step 3: Scan a local file (if you have their mobile app)
python apim_key_scanner.py -f contoso_app.js -v
```

---

## 🔍 What Makes This Different?

### Traditional Approach (Slow):
```
1. Guess a URL: https://api.example.com
2. Try accessing it
3. Get blocked or timeout
4. Try another guess...
```

### Our Approach (Smart):
```
1. DNS Query: "Does company.azure-api.net exist?" (milliseconds)
   ✗ NXDOMAIN = Skip instantly
   ✓ Valid = Continue scanning
2. If valid: Check HTTP, extract keys, test keys
```

**Result:** 100x faster, no wasted HTTP requests

---

## 📊 Output Formats

### Console Output (Human Readable)
```
[VALID SUBDOMAINS] (3)
  • purolator-api.azure-api.net
    A: 20.123.45.67
    CNAME: purolator-api.trafficmanager.net

[APIM ENDPOINTS] (1)
  • https://purolator-api.azure-api.net (Status: 401)

[EXPOSED KEYS] (1)
  • ed079319...26e3 (Full: ed079319-cdf9-4aba-a312-8bf28eaf26e3)

[WORKING KEYS] (1)
  ✓ ACTIVE KEY:
    Key: ed079319-cdf9-4aba-a312-8bf28eaf26e3
    Endpoint: purolator-api.azure-api.net
    Header: Ocp-Apim-Subscription-Key
    Status: 200
```

### JSON Output (Machine Readable)
```json
{
  "domain": "purolator",
  "findings": {
    "valid_subdomains": [...],
    "apim_endpoints": [...],
    "exposed_keys": ["ed079319-cdf9-4aba-a312-8bf28eaf26e3"],
    "working_keys": [...]
  }
}
```

---

## 🎯 Targeting Strategies

### Strategy 1: Known Company Name
```bash
# If you know the company uses Azure
python azure_apim_enum.py -d microsoft -p
python azure_apim_enum.py -d google -p
python azure_apim_enum.py -d amazon -p
```

### Strategy 2: From APK/Mobile App
```bash
# Extract libapp.so or main.js from mobile app
python apim_key_scanner.py -f libapp.so -v

# If you find a domain like "company.azure-api.net"
python azure_apim_enum.py -d company -p
```

### Strategy 3: Bug Bounty Hunting
```bash
# 1. Get target list from bug bounty program
# 2. Check each for APIM usage
for domain in $(cat targets.txt); do
    python azure_apim_enum.py -d $domain -p -o ${domain}_results.json
done
```

### Strategy 4: Passive Reconnaissance
```bash
# Use Google dorks first:
site:azure-api.net "company-name"

# Then enumerate the found subdomains:
python azure_apim_enum.py -d company-name -p
```

---

## ⚠️ Legal & Ethical Use

### ✅ Legal Use Cases:
- Bug bounty programs (within scope)
- Security audits (with permission)
- Your own infrastructure
- Public APIs (documented)
- Open-source projects

### ❌ DO NOT:
- Scan infrastructure without permission
- Use found keys for unauthorized access
- Exploit discovered vulnerabilities without disclosure
- Access production systems without authorization

---

## 🛡️ Defense Recommendations

If you're defending against this type of scanning:

1. **Rotate API Keys Regularly** - Don't use the same key for years
2. **Use Key Vaults** - Don't hardcode keys in client apps
3. **Implement Rate Limiting** - Throttle suspicious enumeration
4. **Monitor DNS Queries** - Alert on unusual subdomain lookups
5. **Use IP Restrictions** - Whitelist known IPs for APIM keys
6. **Obfuscate Endpoints** - Don't use obvious naming patterns
7. **Remove Source Maps** - Don't deploy .map files to production

---

## 🔧 Troubleshooting

### "No valid subdomains found"
- Try with `-p` flag for permutations
- Company might not use Azure APIM
- DNS might be blocking queries (try different DNS server)

### "Keys found but not working"
- Keys might be revoked
- Need different header name
- Endpoint might require additional authentication
- Rate limiting might be active

### "Connection timeouts"
- Reduce threads: `--threads 5`
- Increase timeout: `-t 10`
- Check your internet connection
- Target might be blocking your IP

---

## 📚 Advanced Techniques

### Custom Permutation List
```python
# Edit azure_apim_enum.py
PERMUTATIONS = [
    'your', 'custom', 'keywords',
    'based', 'on', 'target', 'research'
]
```

### Combine with Other Tools
```bash
# Use with subfinder
subfinder -d example.com | grep azure-api.net

# Use with amass
amass enum -d example.com | grep azure-api.net

# Feed results to our scanner
python azure_apim_enum.py -d discovered-subdomain
```

---

## 🎓 Learning from RoseSecurity's Approach

**What made their module effective:**

1. **Minimal False Positives** - DNS queries confirm existence before HTTP
2. **Comprehensive Coverage** - Multiple record types (A, CNAME, TXT, etc.)
3. **Systematic Permutations** - Predictable Azure naming conventions
4. **Efficient Threading** - Parallel DNS queries (fast)
5. **Metasploit Integration** - Professional framework (we adapted to standalone)

**Our Enhancements:**

1. ✅ APIM-specific domains (not just general Azure)
2. ✅ Automatic key extraction from responses
3. ✅ Key validation and testing
4. ✅ HTTP endpoint verification
5. ✅ JSON output for automation
6. ✅ Working key identification

---

## 🚀 Next Steps

After finding exposed keys:

1. **Document Everything** - Screenshot, save outputs
2. **Responsible Disclosure** - Contact security team
3. **Follow Bug Bounty Rules** - Don't exceed scope
4. **Wait for Fix** - Don't publish until patched
5. **Claim Reward** - Submit for bounty payment

---

## 📞 Credits

- **RoseSecurity** - Original Azure enumeration methodology
- **Metasploit Framework** - enum_azuresubdomains.rb module
- **This Implementation** - Enhanced for APIM-specific hunting

**Exploit-DB ID:** 38972 (2023-08-15)
