

Author: ICARAX Engineering Team
Topic: Defensive implementation against device-aware phishing attacks.
In modern phishing, attackers no longer use generic templates. They use "Adaptive Phishing" where the payload (e.o.g., a fake Microsoft login vs. a fake Apple ID page) changes dynamically based on the victim'0s User-Agent string. To defend against this, developers must implement robust client-side telemetry to detect when a session's device profile deviates from expected patterns.
Before implementing device-aware detection, ensure you have the following:
ua-parser-js or a backend service like device-detector).navigator.userAgent API.# Create a virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install necessary libraries
pip install user-agents flask python-dotenv
# Initialize project
npm init -y
# Install dependencies
npm install ua-parser-js dotenv express
# For TypeScript users
npm install --save-dev typescript @types/node @types/express
s## Step 1: Basic Implementation
We will implement a "Device Fingerprint Validator." This logic detects if a user's device profile matches the expected profile of a legitimate session, helping identify "Man-in-the-Middle" (MitM) proxies used in adaptive phishing.
import os
from flask import Flask, request, jsonify
from user_agents import parse
from dotenv import load_dotenv
# Load environment variables from.env file
load_dotenv()
app = Flask(__name__)
# Mock database of "Known Good" device profiles for a user
# In production, this would be fetched from Redis or PostgreSQL
USER_DEVICE_WHITELIST = {
"user_123": {
"os": "iOS",
"browser": "Mobile Safari",
"device": "iPhone"
}
}
@app.route('/api/v1/validate-session', methods=['POST'])
def validate_session():
"""
Analyzes the incoming User-Agent to detect device mismatches
which may indicate an adaptive phishing proxy.
"""
try:
data = request.get_json()
user_id = data.get('user_id')
# The raw User-Agent string sent by the client
user_agent_string = request.headers.get('User-Agent')
if not user_agent_string:
return jsonify({"error": "Missing User-Agent header"}), 400
# Parse the User-Agent
ua = parse(user_agent_string)
current_device = {
"os": ua.os.family,
"browser": ua.browser.family,
"device": ua.device.family
}
# Logic: Check if the device matches the user's historical profile
expected_profile = USER_DEVICE_WHITELIST.get(user_id)
if expected_profile:
# Check for discrepancies (e.s. user is on iPhone, but request comes from Windows/Chrome)
is_mismatch = (
expected_profile['os']!= current_device['os'] or
expected_profile['device']!= current_device['device']
)
if is_mismatch:
# LOG THIS: This is a high-signal indicator of a proxy/phishing-in-the-middle attack
print(f"ALERT: Device mismatch for {user_id}! Expected {expected_profile}, got {current_device}")
return jsonify({
"status": "flagged",
"reason": "Device profile mismatch detected",
"detected_device": current_device
}), 403
return jsonify({"status": "success", "device": current_device}), 200
except Exception as e:
# Robust error handling for production logging
print(f"Internal Error: {str(e)}")
return jsonify({"error": "Internal server error"}), 500
if __name__서:
app.run(debug=True, port=5000)
import { UAParser } from 'ua-parser-js';
interface DeviceProfile {
os: string;
browser: string;
device: string;
}
/**
* Captures the current device fingerprint to send to the backend.
* This helps detect if a phishing proxy is spoofing the device.
*/
export async function captureDeviceTelemetry(): Promise<void> {
try {
const parser = new UAParser();
const result = parser.getResult();
const profile: DeviceProfile = {
os: result.os.name || 'Unknown',
browser: result.browser.name || 'Unknown',
device: result.device.type || 'desktop'
};
console.log('Telemetry Captured:', profile);
const response = await fetch('https://api.yourdomain.com/v1/telemetry', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
// Include a CSRF token in real production environments
'X-CSRF-Token': (document.getElementById('csrf-token') as HTMLInputElement)?.value || ''
},
body: JSON.stringify({
telemetry: profile,
timestamp: new Date().toISOString(),
url: window.location.href
}),
});
if (!response.ok) {
// If telemetry fails, it could indicate an interception attempt
throw new Error(`Telemetry upload failed: ${response.statusText}`);
}
const data = await response.json();
console.log('Telemetry synced successfully');
} catch (error) {
// In a security context, we log errors locally but avoid alerting the user
// to prevent "adversary awareness" during a live attack.
console.error('Telemetry Error:', error instanceof Error? error.message : error);
}
}
// Usage
captureDeviceTelemetry();
Create a .env file in your root directory to manage sensitive configurations.
# Server Configuration
PORT=5000
ENVIRONMENT=development
# Security Configuration
# In production, use a secret key for signing session tokens
SECRET_KEY=your_super_secret_random_string_here
# Threshold for flagging device mismatches (0.0 to 1.0)
DETECTION_SENSITIVITY=0.8
The most common way to detect adaptive phishing is comparing the User-Agent against a known-good session fingerprint.
def is_suspicious_request(request, user_session):
current_ua = request.headers.get('User-Agent')
# Compare current UA against the one used during initial MFA/Login
if current_ua!= user_session.get('original_ua'):
return True
return False
Phishing proxies often fail to execute complex-client-side logic. Sending a "challenge" (like a specific canvas rendering or WebGL check) via telemetry can reveal if the user is behind a proxy.
| Error | Cause | Fix | | :
| Error | Cause | Fix |
|---|---|---|
ModuleNotFoundError: No module named 'user_agents' | Python library not installed. | Run pip install user-agents |
CORS Error in Browser | Frontend trying to send telemetry to a different domain. | Configure CORS headers on your backend. |
False Positives | Users updating browsers or OS versions. | Implement a "Grace Period" or trigger MFA instead of a hard block. |
UA Spoofing | Soph-level attackers spoofing headers. | Combine UA detection with-IP reputation and behavioral biometrics. |
Source: Dark Reading
Follow ICARAX for more AI insights and tutorials.
