A real-time Machine Learningβpowered microservice for detecting masked, anonymous, and suspicious IP addresses.
Strengthens Web Application Firewall (WAF) security by identifying VPNs, proxies, Tor nodes, and datacenter traffic.
This demo showcases:
- β Web UI interaction
- β Real-time masked vs legitimate IP detection
- β Risk level scoring & confidence metrics
- β API usage via Swagger UI
| Feature | Description |
|---|---|
| β‘ Real-time Analysis | <50ms per request with intelligent caching |
| π§ ML Ensemble Model | Random Forest + XGBoost |
| π― 96%+ Accuracy | Highly accurate masked IP detection |
| π Multi-type Detection | Tor, VPN, Proxy, Datacenter IPs |
| π FastAPI Backend | High-performance async REST API |
| π Risk Scoring | LOW β MEDIUM β HIGH β CRITICAL levels |
| πΎ Smart Caching | Redis with automatic in-memory fallback |
| π₯οΈ Web Dashboard | Interactive UI for live testing |
| π Explainable AI | Confidence scores and feature importance |
| π Continuous Learning | Auto-updates from threat intelligence feeds |
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Web Application / WAF β
ββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββ
β HTTP Request
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Masked IP Detection API β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββ β
β β IP Validator β β β Feature β β β ML Ensembleβ β
β β & Parser β β Extraction β β Prediction β β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββ β
β β β β β
β βββββββββββββββββββ΄ββββββββββββββββββββ β
β β β
β βΌ β
β ββββββββββββββββββββ β
β β Risk Scoring & β β
β β Response Builder β β
β ββββββββββββββββββββ β
β β β
β ββββββββββββββββββββββββββββ΄βββββββββββββββββββββββ β
β β Cache Layer (Redis / In-Memory) β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β JSON Response
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Client Application / Security Dashboard β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- βοΈ IP Structural Analysis: IPv4/IPv6 validation and feature extraction
- βοΈ ML-Based Classification: Ensemble model for masked vs legitimate detection
- βοΈ Probability Scoring: Confidence levels (0-100%)
- βοΈ Risk Categorization: Four-tier risk assessment
- βοΈ Batch Processing: Check multiple IPs simultaneously
- βοΈ REST API: Production-ready endpoints
- βοΈ Web Dashboard: Live testing interface
- βοΈ Intelligent Caching: Performance optimization
- π Live Tor Integration: Real-time Tor exit node feed
- π ASN-Based Detection: VPN & datacenter identification
- π GeoIP Enrichment: MaxMind GeoIP2 integration
- π Threat Intelligence: AbuseIPDB & IPQualityScore APIs
- π Online Learning: Incremental model retraining
- π Behavioral Analysis: Advanced anomaly detection
Note: These sources are used during model training and planned for future integration.
- Regional Registries: RIPE, ARIN, APNIC
- Cloud Providers: AWS, GCP, Azure, DigitalOcean
- Hosting: OVH, Hetzner, Vultr, Linode
- AbuseIPDB - Malicious IP database
- IPQualityScore - Fraud detection
- MaxMind GeoLite2 - City + ASN data
β
Python 3.8 or higher
β
pip package manager
β
Git
β οΈ Redis (optional, but recommended for production)git clone https://github.com/rt1856/masked-ip-detection.git
cd masked-ip-detectionWindows:
python -m venv venv
venv\Scripts\activateLinux/Mac:
python3 -m venv venv
source venv/bin/activatepip install -r requirements.txtOption A: Download Pre-trained Models
# Download from project releases or Google Drive
# Place in models/ directory:
models/
βββ random_forest_model.pkl
βββ xgboost_model.pkl
βββ feature_names.pklOption B: Train Your Own Models
# Use provided Google Colab notebooks:
# 1. Complete_Data_Collection.ipynb (collect datasets)
# 2. 02_preprocessing.ipynb (feature engineering)
# 3. 03_model_training.ipynb (train models)uvicorn src.api.main:app --reload --host 0.0.0.0 --port 8000Output:
INFO: Uvicorn running on http://0.0.0.0:8000
INFO: Loaded 3 models successfully
INFO: Feature count: 18
INFO: Masked IP Detection API started successfully
| Service | URL | Description |
|---|---|---|
| π Web Dashboard | http://localhost:8000/ | Interactive testing interface |
| π API Documentation | http://localhost:8000/docs | Swagger UI (interactive) |
| π Alternative Docs | http://localhost:8000/redoc | ReDoc (clean layout) |
| β€οΈ Health Check | http://localhost:8000/health | Service status |
| βΉοΈ API Info | http://localhost:8000/ | Metadata & endpoints |
cURL:
curl -X POST "http://localhost:8000/api/v1/check" \
-H "Content-Type: application/json" \
-d '{
"ip_address": "8.8.8.8",
"include_details": true
}'Response:
{
"ip_address": "8.8.8.8",
"is_masked": false,
"confidence": 0.92,
"risk_level": "LOW",
"detected_type": null,
"details": {
"ensemble_probability": 0.08,
"model_predictions": {
"random_forest": 0,
"xgboost": 0,
}
},
"timestamp": "2025-01-15T10:30:00"
}cURL:
curl -X POST "http://localhost:8000/api/v1/batch" \
-H "Content-Type: application/json" \
-d '{
"ip_addresses": ["8.8.8.8", "1.1.1.1", "185.220.101.1"],
"include_details": false
}'Response:
{
"total_checked": 3,
"results": [
{
"ip_address": "8.8.8.8",
"is_masked": false,
"confidence": 0.92,
"risk_level": "LOW"
},
{
"ip_address": "185.220.101.1",
"is_masked": true,
"confidence": 0.95,
"risk_level": "CRITICAL",
"detected_type": "tor"
}
],
"timestamp": "2025-01-15T10:31:00"
}import requests
def check_ip(ip_address):
"""Check if IP is masked"""
response = requests.post(
"http://localhost:8000/api/v1/check",
json={
"ip_address": ip_address,
"include_details": True
}
)
return response.json()
# Example usage
result = check_ip("8.8.8.8")
print(f"IP: {result['ip_address']}")
print(f"Is Masked: {result['is_masked']}")
print(f"Confidence: {result['confidence']:.2%}")
print(f"Risk Level: {result['risk_level']}")async function checkIP(ipAddress) {
const response = await fetch('http://localhost:8000/api/v1/check', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
ip_address: ipAddress,
include_details: true
})
});
return await response.json();
}
// Example usage
checkIP('8.8.8.8').then(result => {
console.log(`IP: ${result.ip_address}`);
console.log(`Is Masked: ${result.is_masked}`);
console.log(`Confidence: ${(result.confidence * 100).toFixed(1)}%`);
console.log(`Risk Level: ${result.risk_level}`);
});| Model | Accuracy | Precision | Recall | F1-Score | ROC-AUC |
|---|---|---|---|---|---|
| Random Forest | 94.2% | 93.8% | 94.5% | 94.1% | 0.972 |
| XGBoost | 95.1% | 94.9% | 95.3% | 95.1% | 0.981 |
| Ensemble | 96.3% | 96.1% | 96.5% | 96.3% | 0.987 |
Note: Metrics are based on offline evaluation datasets. Real-world performance may vary based on traffic patterns and threat landscape.
- β‘ Latency: <50ms per request (with caching: <10ms)
- π Throughput: 1000+ requests/second
- πΎ Memory: ~200MB RAM
- π False Positive Rate: <3%
from fastapi import FastAPI, Request, HTTPException
import httpx
app = FastAPI()
async def check_masked_ip(ip: str) -> dict:
"""Check if IP is masked using the microservice"""
async with httpx.AsyncClient() as client:
response = await client.post(
'http://localhost:8000/api/v1/check',
json={'ip_address': ip}
)
return response.json()
@app.middleware("http")
async def ip_filtering_middleware(request: Request, call_next):
"""Block high-risk masked IPs"""
client_ip = request.client.host
result = await check_masked_ip(client_ip)
if result['is_masked'] and result['risk_level'] in ['HIGH', 'CRITICAL']:
raise HTTPException(
status_code=403,
detail="Access denied: Suspicious IP detected"
)
return await call_next(request)# Custom rule to check IPs
SecRule REQUEST_HEADERS:X-Forwarded-For "@rx ^(.*)$" \
"id:9001,\
phase:1,\
t:none,\
capture,\
chain"
SecRule TX:1 "@external /usr/local/bin/check_masked_ip.sh" \
"deny,status:403,msg:'Masked IP Detected'"check_masked_ip.sh:
#!/bin/bash
IP=$1
RESULT=$(curl -s -X POST http://localhost:8000/api/v1/check \
-H "Content-Type: application/json" \
-d "{\"ip_address\":\"$IP\"}" | jq -r '.is_masked')
if [ "$RESULT" = "true" ]; then
exit 1 # Block
else
exit 0 # Allow
fi# Run all tests
pytest tests/
# Run with coverage
pytest tests/ --cov=src --cov-report=html
# Run specific test file
pytest tests/test_api.py -v# Test legitimate IP
curl -X POST http://localhost:8000/api/v1/check \
-H "Content-Type: application/json" \
-d '{"ip_address": "8.8.8.8"}'
# Test Tor exit node (example)
curl -X POST http://localhost:8000/api/v1/check \
-H "Content-Type: application/json" \
-d '{"ip_address": "185.220.101.1"}'
# Test private IP
curl -X POST http://localhost:8000/api/v1/check \
-H "Content-Type: application/json" \
-d '{"ip_address": "192.168.1.1"}'# Build and start services
docker-compose up -d
# View logs
docker-compose logs -f api
# Stop services
docker-compose down# Build image
docker build -t masked-ip-detection -f docker/Dockerfile .
# Run container
docker run -d \
-p 8000:8000 \
-v $(pwd)/models:/app/models \
--name masked-ip-api \
masked-ip-detectionmasked-ip-detection/
βββ src/
β βββ api/
β β βββ main.py # FastAPI application
β β βββ routes.py # API endpoints
β β βββ schemas.py # Pydantic models
β βββ data/
β β βββ collectors.py # Data collection scripts
β βββ features/
β β βββ ip_features.py # Feature extraction
β βββ models/
β βββ predictor.py # ML prediction logic
βββ models/ # Trained ML models (gitignored)
β βββ random_forest_model.pkl
β βββ xgboost_model.pkl
β βββ feature_names.pkl
βββ notebooks/ # Google Colab notebooks
β βββ Complete_Data_Collection.ipynb
β βββ 02_preprocessing.ipynb
β βββ 03_model_training.ipynb
βββ dashboard/ # Web UI
β βββ templates/
β βββ index.html
βββ tests/ # Test suite
β βββ test_api.py
β βββ test_features.py
βββ docker/
β βββ Dockerfile
β βββ docker-compose.yml
βββ requirements.txt # Python dependencies
βββ .gitignore
βββ README.md
- Enable HTTPS: Use SSL/TLS certificates
- API Authentication: Implement API keys or OAuth2
- Rate Limiting: Prevent abuse (e.g., 100 requests/minute)
- Input Validation: Already implemented via Pydantic
- Logging: Monitor all requests and predictions
- Redis Security: Use password authentication
- CORS Configuration: Restrict allowed origins
- Error Handling: Don't expose internal details
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
@app.post("/api/v1/check")
@limiter.limit("100/minute")
async def check_ip(request: Request, ip_request: IPCheckRequest):
# ... existing codeWe welcome contributions! Please follow these guidelines:
- Fork the repository
- Create a feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
# Install development dependencies
pip install -r requirements-dev.txt
# Run linting
flake8 src/
black src/
# Run type checking
mypy src/This project is licensed under the MIT License - see the LICENSE file for details.
- GitHub Issues: Report bugs or request features
- Discussions: Join community discussions
- Email: thakkarriddhi1510@gmail.com
Special thanks to:
- Tor Project - Tor exit node data
- MaxMind - GeoIP2 databases
- Open-source proxy list maintainers - Community-driven threat intelligence
- FastAPI - Modern Python web framework
- Scikit-learn & XGBoost - ML ecosystem
- SWAVLAMBAN 2025 Organizers - Hackathon opportunity